Python Notes
Python Notes
1) High-level
Python is a high-level programming language that makes it easy to learn. Python doesn’t
require you to understand the details of the computer in order to develop programs
efficiently.
2) General-purpose
Python is a general-purpose language. It means that you can use Python in various domains
including:
Web applications
Big data applications
Testing
Automation
Data science, machine learning, and AI
Desktop software
Mobile apps
The targeted language like SQL which can be used for querying data from relational
databases.
3) Interpreted
Python is an interpreted language. To develop a Python program, you write Python code into
a file called source code.
To execute the source code, you need to convert it to the machine language that the computer
can understand. And the Python interpreter turns the source code, line by line, once at a
time, into the machine code when the Python program executes.
Compiled languages like Java and C# use a compiler that compiles the whole source code
before the program executes.
4) Interactive
You can actually sit at a Python prompt and interact with the interpreter directly to write your
programs.
1
Features of Python
The latest release of Python is 3.x. As mentioned before, Python is one of the most widely
used languages on the web. I'm going to list a few of them here:
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-maintain.
A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode that allows
interactive testing and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial databases.
GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries, and Windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
Scalable − Python provides a better structure and support for large programs than
shell scripting.
Applications of Python:
Python, a versatile programming language, finds applications in diverse fields, including web
development, data science, automation, and more, with notable uses in platforms like
Instagram, Spotify, and Pinterest.
Here's a more detailed look at Python's applications:
Web Development:
Frameworks:
Python excels in web development thanks to frameworks like Django and Flask,
which simplify the creation of dynamic and robust web applications.
Backend Infrastructure:
Many popular websites and applications, including Instagram, rely on Python for their
backend infrastructure.
Example:
Instagram, initially developed using Django, leverages Python for its backend.
Data Analysis:
Python's libraries like Pandas and SciPy make it a powerful tool for analyzing and
manipulating large datasets.
Data Visualization:
2
Python offers various libraries for creating interactive and informative visualizations,
aiding in data exploration and communication.
Machine Learning:
Python is a leading language for machine learning, with libraries like Scikit-learn and
TensorFlow enabling the development of predictive models and algorithms.
Automation and Scripting:
Task Automation: -Python scripts can automate repetitive tasks, streamlining
workflows and saving time.
System Administration:
Python's ability to interact with operating systems and network protocols makes it
useful for system administration tasks.
Web Scraping:
Python libraries like Beautiful Soup and Scrapy facilitate the extraction of data from
websites.
Other Applications:
Desktop GUI:
Python offers libraries like Tkinter and PyQt for creating graphical user interfaces for
desktop applications.
Scripting languages are interpreted from source code directly, without the need for compilation,
using an interpreter to translate commands. It is important to note that all scripting languages are
programming languages, but not all programming languages are scripting languages.
3
1. Server-side scripting language:
A server-side scripting language operates on the server to generate responses for client
requests, with the primary objective of creating dynamic content for web pages. In this
process, web servers execute these server-side scripts. This approach is considered more
secure than client-side scripting, as the server handles the execution, enhancing overall
security measures. Examples of server-side scripting languages include PHP, Java, Ruby,
Python, C#, and Go.
A client-side scripting language executes scripts directly in the client's web browser without
the need for server interaction. Its primary objectives encompass tasks such as data
validation, handling UI components, and managing dynamic elements like navigation tools.
In this scenario, the browser runs the code locally on the user's computer, independent of the
server. However, it's worth noting that client-side scripting is considered less secure
compared to server-side scripting due to its reliance on the user's browser. Examples of
client-side scripting languages include JavaScript, TypeScript, HTML/CSS, and AJAX.
Features
1. Cross Platform Dependency:
The scripting languages are independent of the Operating system they are executing.
2. Fast Development:
The scripting languages are easy to code, test, and debug and make any changes faster than
other programming languages.
3. Easy Integration:
The scripting language can be easily integrated with other programming languages like Java,
and C++.
4. Versatile:
Scripting languages are very versatile they can be used for different purposes.
It can be used for web development, scientific study, administration, and analysis.
5. Easy to learn:
One of the major benefits of scripting language is that it is easy to learn when compared to
programming languages.
4
Usage of scripting languages
Different scripting languages have different usages, and they can be used in different
industries. Some of them include:
Automation: They are widely used to automate tasks like data manipulation,
maintenance, maintenance, and managing updates and backups.
Dynamic web development: Using JavaScript and its interactive framework greatly
enhances the user experience of the website. They are used to develop web
applications on the client and server sides.
Data Analytics: Scripting languages like R programming and Python are widely used
as tools for the analysis of the data and also to visualize it.
Testing: They are used to check the software product developed and ensure the
quality is maintained. Frameworks like Selenium and PyTest are used for testing
software components.
They are used to create dynamic web Programming languages are used to write
3.
applications computer programs.
Scripting languages contain different
4. They are high-speed languages.
libraries
Example -: Bash, Ruby, Python,
5. Example -: C++, Java, PHP High-level etc.
JavaScript etc.
6. Scripting languages can be easily Programming languages are translation free
ported among various operating languages
5
systems.
7. These languages requires a host. These languages are self executable.
8. Do not create a .exe file. These generate .exe files.
Most of the scripting languages are Most of the programming languages are
9.
interpreted language. compiled languages.
All the scripting languages are All the programming languages are not scripting
10.
programming languages. languages.
It is easier to learn than programming
11. It can take significant amount of time to learn.
language.
It is less code intensive when
12. compared with programming It is code intensive.
language.
13. It does not create any binary files. It does creates binary files.
It is easy for the beginner to write and It is difficult for the beginner to write and
14.
understand the code. understand the code.
15. It is run inside another program. It is independently run.
16. It needs lesser line of codes. It needs numerous lines of code.
17. It has low maintenance cost. It has high maintenance cost.
What it is:
The PVM is an abstract machine that interprets and executes Python bytecode.
How it works:
Python source code (e.g., .py files) is compiled into bytecode (e.g., .pyc files).
The PVM then reads and executes this bytecode, effectively running your Python
program.
Why it's important:
Abstraction: The PVM hides the complexities of the underlying hardware, allowing
developers to focus on writing code without worrying about platform-specific details.
CPython:
The most widely used Python implementation, CPython, is the name of the VM that
interprets and executes Python bytecode.
Other Python Implementations:
Besides CPython, there are other Python implementations like Jython (runs on JVM)
and IronPython (runs on .NET), each with its own VM.
6
Python Version History
Python's journey began with version 0.9.0, released by Guido van Rossum in 1991. This
initial release included core features such as exception handling, functions, and the core data
types: list, dict, str, and others. It also introduced the module system, allowing the
organization of code into reusable libraries.
Python 1.0 marked the official public release, bringing in significant features such as:
Lambda, Map, Filter, and Reduce: Functional programming constructs that allowed concise
and powerful data manipulation.
Standard Library Enhancements: Expansion of the standard library, making Python more
versatile.
Python 2.0 was a pivotal release that laid the groundwork for modern Python with:
List Comprehensions: A syntactic construct for creating lists based on existing lists.
7
Garbage Collection: Automatic memory management to reclaim unused memory.
Unicode Support: Full support for Unicode, enabling better handling of international text.
Python 2.7 was the final major release in the Python 2.x series, bringing several features from
Python 3.x to ease the transition:
Improved Syntax: Enhanced syntax features, including more robust error handling and new
string formatting methods.
Python 3.0, also known as "Python 3000" or "Py3k," was a revolutionary release designed to
fix inconsistencies and remove redundant constructs from Python 2.x:
New Syntax and Semantics: Changes to integer division, Unicode string handling, and more.
Asyncio: A framework for writing asynchronous programs, allowing for concurrent code
execution.
Type Hints: A syntax for adding type annotations to function arguments and return values.
Async and Await: Syntactic support for asynchronous programming, making async code
more readable and maintainable.
5. Modern Python
8
Python 3.6 (2016)
Formatted String Literals (f-strings): A concise and readable way to embed expressions
inside string literals.
Data Classes: A decorator for automatically generating special methods like __init__ and
__repr__ in classes.
Walrus Operator (:=): An assignment expression that allows assignment and return of a
value within an expression.
Dictionary Merge and Update Operators: New operators | and |= for merging and updating
dictionaries.
Parenthesized Context Managers: Support for multiple context managers in a single with
statement.
The future release of Python 3.12 bring more optimizations and features, continuing the
evolution of the language.
Improvement in Modules
The future release of Python 3.12 is expected to bring more optimizations and features,
continuing the evolution of the language.
In this mode, you basically call the Python interpreter and throw a bunch of commands to it
to execute. To enter into the interactive mode of Python use the below commands:
$python # Unix/Linux
or
python% # Unix/Linux
or
C:> python # Windows/DOS
Example:
Here we will enter the interactive mode and ask Python to solve a simple computation. Look
at the image below:
10
Using command-line:
In this method of using python, you need to call the python interpreter first and then ask it to
run a python file.
Example:
Let’s make a python file that simply computes the sum of 5 and 10 and returns the result and
save it as [Link] file. This would look somewhat like the below:
python [Link]
There are plenty of IDEs available on the internet like VScode, Sublime editor, and pycharm,
etc. Here we will demonstrate the use of python using Jupyter Notebook, a python IDE from
Anaconda.
Example:
Here we will write a simple python code and ask the IDE to execute it in Python.
Now if you hit the Run Button on the IDE it will call for the interpreter automatically and
execute the program. This would look like below:
12
Python Data Types
13
[Link]
S. Numeric Description
No. Data Type
1. Integer (int)
An Integer is said to be a whole number (positive, negative, or zero)
without any decimal or fractional part. For example, 15, -7, 12, 0, -125,
14
268, and more. The integer values are represented by the 'int' class. In
Python, there is no limit to length of the integer values. The value can be
of any length and can reach the maximum available memory of the
system.
Example
1. # python program to show how to declare integers in Python
2.
3. # initializing some variables with integers
4. var_1 = 16 # positive integer
5. var_2 = -21 # negative integer
6. var_3 = 0 # zero
7.
8. # printing the types of initialized variables
9. print("Data Type of", var_1, "=", type(var_1))
[Link]("Data Type of", var_2, "=", type(var_2))
[Link]("Data Type of", var_3, "=", type(var_3))
Execute Now
Output:
2. Floating-point (float)
A floating-point number is said to be a number that can have a decimal
point or be written in scientific notation. For example, 14.523, 3.14, 1.5e3,
and more. In Python, a class known as 'float' is used for storing decimal
numbers which can either be positive, negative or zero. It has a support
for scientific notations (e.g., 1.6e4 = 16000.0). The float class follows IEEE
754 floating-point standard and has a precision limit up to 15 decimal
points.
Example
1. # python program to show how to declare floating-point numbers in Python
2.
3. # initializing some variables with floating-point numbers
4. var_1 = 1.72 # positive float
5. var_2 = -0.05 # negative float
6. var_3 = 0.0 # zero as a float
7. var_4 = 1.6e4 # scientific notation
8.
15
9. # printing the types of initialized variables
[Link]("Data Type of", var_1, "=", type(var_1))
[Link]("Data Type of", var_2, "=", type(var_2))
[Link]("Data Type of", var_3, "=", type(var_3))
[Link]("Data Type of", var_4, "=", type(var_4))
Execute Now
Output:
1. a + bj
where:
Example
1. # python program to show how to declare complex numbers in Python
2.
3. # initializing some variables with complex numbers
4. var_1 = 3 + 5j # where 2 is the real part and 5 is the imaginary part
5. var_2 = -3.4 + 2.8j
6. var_3 = -5 - 1.9j
7. var_4 = -6 + 0j
8.
9. # printing the types of initialized variables
[Link]("Data Type of", var_1, "=", type(var_1))
[Link]("Data Type of", var_2, "=", type(var_2))
[Link]("Data Type of", var_3, "=", type(var_3))
[Link]("Data Type of", var_4, "=", type(var_4))
Execute Now
Output:
In the above snippet of code, we have initialized few variables with some
complex numbers. We have then used the type() method to return their
types and print them for the users. As a result, we can observe that all the
initialized variables belong to the 'complex' class.
1. Lists (list)
Similar to array in other programming languages, List in Python is an
ordered collection of data elements. It can simultaneously store elements
of different data types separately by commas. Lists are mutable in nature,
meaning that we can modify its elements anytime.
Example
1. # simple python program to show how to initialize a list
2.
3. # creating a list
4. list_1 = [1, 0.5, 'hello', 1+5j, 1.7e2, -12, 'welcome'] # different types of element
s
5.
6. # printing details
7. print("Initialized List:", list_1) # printing elements of the list
8. print("Data Type:", type(list_1)) # printing data type
Execute Now
Output:
3. Tuples (tuple)
Tuples are the ordered sequence of data elements same as the lists. The
only difference between the two is that Tuples are immutable in nature.
This means that we cannot modify the elements of the tuple once created.
Example
1. # simple python program to show how to initialize a tuple
2.
3. # creating a tuple
4. tuple_1 = (1, 0.5, 'hello', 1+5j, 1.7e2, -12, 'welcome') # different types of eleme
nts
5.
6. # printing details
7. print("Initialized tuple:", tuple_1) # printing elements of the tuple
8. print("Data Type:", type(tuple_1)) # printing data type
Execute Now
Output:
In the above snippet of code, we have initialized a tuple with some items
of mixed data types. We have then printed the tuple for reference, and
used the type() method to return their types and print them for the users.
As a result, we can observe that the initialized tuple can store multiple
data types simultaneously and belongs to the 'tuple' class.
3. String (str)
A String is a sequence of characters enclosed in single (') or double (")
quotes. Similar to Tuples, strings are also immutable in nature. In Python,
the strings are represented using the 'str' class.
Example
1. # simple python program to show how to initialize string
2.
3. # initializing variables with some string
4. str_1 = 'TpointTech'
5. str_2 = 'I love learning Python from TpointTech'
6.
7. # printing details
18
8. print("String 1 :", str_1) # printing string
9. print("Data Type of String 1:", type(str_1)) # printing data type
10.
[Link]("String 2 :", str_2) # printing string
[Link]("Data Type of String 2:", type(str_2)) # printing data type
Execute Now
Output:
String 1 : TpointTech
Data Type of String 1: <class 'str'>
String 2 : I love learning Python from TpointTech
Data Type of String 2: <class 'str'>
Explanation:
In the above snippet of code, we have defined two variables as str_1 and
str_2 and initialized them with some text. We have then printed the
strings, and used the type() method to return their types and print them
for the users. As a result, the printed texts belong to the 'str' class.
4. Range (range)
Additionally, there is one more type belonging to the sequence data type.
This data type is known as range. A range is an object in Python used to
represent the sequence of numbers.
Example
1. # simple python program to show how to initialize a range
2.
3. # creating a range
4. r = range(3, 26, 2)
5.
6. # printing the results
7. print("Range:", r) # printing range
8. print("Range as List:", list(r)) # printing range as a list
9. print("Data Type:", type(r)) # printing data type
Execute Now
Output:
In the above snippet of code, we have used the range() function to create
a range from 3 to 26 incrementing by 2. We have then printed the range
for reference. We have also printed the range as a list displaying all the
elements of the generated sequence. At last, we have printed its data
type. As a result, we can observe that it belongs to the 'range' class.
There are generally two types belonging to the set data types.
1. set
A set in Python is said to be an unordered, mutable and unindexed
collection of unique data elements. Sets are useful in storing distinct
values and perform various mathematical operations like union,
intersection, and difference.
Example
1. # simple python program to show how to initialize a set
2.
3. # creating sets
4. set_1 = {"mango", "apple", "orange", "banana"} # using {}
5. set_2 = set(["ginger", "lemon", "potato", "tomato"])
6.
7. # printing the results
8. print("Set 1:", set_1) # set 1
9. print("Data type of Set 1:", type(set_1)) # data type of set 1
10.
[Link]("Set 2:", set_2) # set 2
[Link]("Data type of Set 2:", type(set_2)) # data type of set 2
Execute Now
Output:
20
elements of both sets along with their data types. As a result, we can
observe that both sets belong to the 'set' class.
2. frozenset
In Python, a function called frozenset() is used to return a frozenset
object. This object is an immutable, unordered data type. A frozenset
consists of unique items, making it similar to the set data type; however,
it is unchangeable like tuples.
Example
1. # simple python program to show how to create a frozeset
2.
3. # creating an iterable
4. list_1 = ["berries", "orange", "mango", "apple"] # a list
5.
6. # using the frozenset() function to create a frozenset object
7. f_1 = frozenset(list_1)
8.
9. # printing results
[Link]("Frozenset:", f_1) # frozenset
[Link]("Data Type:", type(f_1)) # data type
Execute Now
Output:
Example
1. # simple python program to show how to create a dictionary
2.
3. # creating a dictionary
4. person_1 = {
5. 'name' : 'Mark',
6. 'age': '25',
21
7. 'gender' : 'Male',
8. }
9.
10.# printing results
[Link]("Person Details:\n", person_1) # dictionary
[Link]("Data Type:", type(person_1)) # its data type
Execute Now
Output:
Person Details:
{'name': 'Mark', 'age': '25', 'gender': 'Male'}
Data Type: <class 'dict'>
Explanation:
In the above example, we have created a dictionary and printed its data
type for reference. Here 'name', 'age', and 'gender' are the keys having
the values as 'Mark', '25', and 'Male', respectively.
o True: The Boolean value 'True' represents 1 and is returned when the
expression or object are considered truthful.
o False: The Boolean value 'False' represents 0 and is returned when the
expression or object turns out to be false.
We can also evaluate non-Boolean objects in a Boolean context and
identify them as either True or False. A class called 'bool' is used to store
the Boolean objects in Python.
Example
1. # simple python program to show the Boolean data types
2.
3. # initializing variables
4. a = True
5. b = False
6. # c = true <= Will Return Error
7.
8. # printing the results
9. print("Value of a:", a)
[Link]("Data Type of a:", type(a))
[Link]("Value of b:", b)
[Link]("Data Type of b:", type(b))
13.# print("Value of c:", c)
14.# print("Data Type of c:", type(c))
Execute Now
Output:
22
Value of a: True
Data Type of a: <class 'bool'>
Value of b: False
Data Type of b: <class 'bool'>
Explanation:
In the above example, we have initialized two variables - a, and b with the
values - True and False, respectively. We then printed them for reference
and used the type() function to return their data types. As a result, we can
observe that the variable a, and b, belongs to the 'bool' class.
1. bytes
The bytes data type is an immutable sequence of bytes, value ranging
from 0 to 255. It is useful for working with binary files, network
communication, or cryptographic functions.
Example
1. # simple python program to show the creation of bytes object
2.
3. # creating bytes using a list of integers (0-255)
4. obj_1 = bytes([78, 79, 80, 81, 82]) # ASCII values
5.
6. # printing results
7. print("Value of Object 1:", obj_1)
8. print("Data Type of Object 1:", type(obj_1))
Execute Now
Output:
2. bytearray
Unlike bytes, the bytearray data type is a mutable sequence of bytes that
allows modification in the binary data in place.
Example
1. # simple python program to show the creation of bytearray object
2.
3. # creating a bytearray object using a list of integers
4. obj_1 = bytearray([78, 79, 80, 81, 82]) # ASCII values
5.
6. # printing results
7. print("Value of Object 1:", obj_1)
8. print("Data Type of Object 1:", type(obj_1))
Execute Now
Output:
3. memoryview
memoryview is a data type that is used to provide a lightweight and
efficient way to access binary data without copying it. This data type is
useful for large data operations where performance has relevance.
Example
1. # simple python program to show the creation of bytearray object
2.
3. # creating a bytearray object using a list of integers
4. obj_1 = bytearray([78, 79, 80, 81, 82]) # ASCII values
5.
6. # creating a memoryview object
7. obj_2 = memoryview(obj_1)
24
8.
9. # printing results
[Link]("Value of Object 2:", obj_2)
[Link]("Data Type of Object 2:", type(obj_2))
Execute Now
Output:
Example
1. # simple python program to show the creation of NoneType object
2.
3. # initializing a variable with None
4. var_1 = None
5.
6. # printing results
7. print("Value of var_1:", var_1)
8. print("Data Type of var_1:", type(var_1))
Execute Now
Output:
In the above example, we have initialized a variable var_1 with None as its
value. We have then printed it for reference and used the type() function
to return its type. As a result, we can observe that the variable var_1 has
a value of None, and it belongs to the 'NoneType' class.
25
Type Casting in Python
Python is a dynamically typed language, allowing us not to explicitly define the data types
of the variables. However, Python offers us accessibility to convert one data type into
another.
The process of converting one data type into another is known as Type Casting. Python
offers two ways to type cast the variables:
1. Implicit Type Casting (Automatic): Python converts smaller data types to larger
ones automatically.
Example
1. # python program to show implicit type casting
Output:
In the above example, we have initialized two variables, p and q, of different types (int and
float). We then added them and stored their sum in another variable, r. We then printed
their data types. As a result, we can observe that r is implicitly converted into 'float'.
Example
1. # python program to show explicit type casting
26
10.
11.# converting string to int
12.r = int("7295")
[Link](r)
14.
15.# converting list to tuple
16.list_1 = [4, 7, 10]
17.tuple_1 = tuple(list_1)
18.
[Link](type(list_1))
[Link](type(tuple_1))
Execute Now
Output:
14.0
7
7295
<class 'list'>
<class 'tuple'>
Explanation:
In the above example, we have used some built-in functions like float(), int(), tuple() in
order to convert the data type of the passed variable into the required data type.
Conclusion
Understanding Python data types is important for writing efficient code. These built-in data
types allow developers for storing and manipulating various kinds of data effectively and
efficiently. Mastering them will enable better programming practices and problem-solving
skills.
q=7
print(type(q))
a. <class 'float'>
b. <class 'str'>
c. <class 'int'>
d. <class 'list'>
Show AnswerWorkspace
p = 62.5
27
a. int
b. float
c. complex
d. bool
Show AnswerWorkspace
a. tuple
b. str
c. list
d. frozenset
Show AnswerWorkspace
x = 3 + 4j
print(type(x))
a. <class 'float'>
b. <class 'int'>
c. <class 'complex'>
d. <class 'tuple'>
Show AnswerWorkspace
a. {5, 4, 3}
b. [5, 4, 3]
c. (5, 4, 3)
d. set[5, 4, 3]
Show AnswerWorkspace
← prevnext →
28
Related Posts
Imagine you have got a container of toys categorised "wood blocks," however
That's basically what type casting, or type conversion, does in Python. Think of
12 min read
Python Numbers
The number data types are used to store the numeric values inside the
variable. For example, a = 5 will create a number object a with value 5. Python
3 min read
29
Python Boolean
Python includes a built-in data type called Boolean, which can be either
True or False. This type is commonly used to represent the outcome of logical
8 min read
Python Variables
30