Python Notes - Unit - 1
Python Notes - Unit - 1
1
open-source means, "Anyone can download its source code without paying any
penny."
6. Object-Oriented Language: Python supports object-oriented language and concepts
of classes and objects come into existence. It supports inheritance, polymorphism, and
encapsulation, etc. The object- oriented procedure helps to programmer to write
reusable code and develop applications in less code.
7. Extensible: It implies that other languages such as C/C++ can be used to compile the
code and thus it can be used further in our Python code. It converts the program into
byte code, and any platform can use that byte code.
8. Large Standard Library: It provides a vast range of libraries for the various fields
such as machine learning, web developer, and also for the scripting. There are various
machine learning libraries, such as Tensor flow, Pandas, Numpy, Keras, and Pytorch,
etc. Django, flask, pyramids are the popular framework for Python web development.
9. GUI Programming Support: Graphical User Interface is used for the developing
Desktop application. PyQT5, Tkinter, Kivy are the libraries which are used for
developing the web application.
10. Integrated: It can be easily integrated with languages like C, C++, and JAVA, etc.
Python runs code line by line like C, C++ Java. It makes easy to debug the code.
11. Embeddable: The code of the other programming language can use in the Python
source code. We can use Python source code in another programming language as
well. It can embed other language into our code.
12. Dynamic Memory Allocation: In Python, we don't need to specify the data-type of
the variable. When we assign some value to the variable, it automatically allocates the
memory to the variable at run time. Suppose we are assigned integer value 15
to x, then we don't need to write int x = 15. Just write x = 15.
Python Applications
Python is known for its general-purpose nature that makes it applicable in almost
every domain of software development. Python makes its presence in every emerging
field. It is the fastest-growing programming language and can develop any
application.
Here, we are specifying application areas where Python can be applied.
2
processing, request, beautifulSoup, Feedparser, etc. One of Python web-framework
named Django is used on Instagram.
2. Desktop GUI Applications: The GUI stands for the Graphical User Interface, which
provides a smooth interaction to any application. Python provides a Tk GUI
library to develop a user interface. Some popular GUI libraries are given below.
3. Software Development: Python is useful for the software development process. It
works as a support language and can be used to build control and management,
testing, etc.
4. Scientific and Numeric: Python language is the most suitable language for Artificial
intelligence or machine learning. It consists of many scientific and mathematical
libraries, which makes easy to solve complex calculations. Implementing machine
learning algorithms require complex mathematical calculation. Python has many
libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-learn, etc
5. Business Applications: Business Applications differ from standard applications. E-
commerce and ERP are an example of a business application. This kind of application
requires extensively, scalability and readability, and Python provides all these
features. Python provides a Tryton platform which is used to develop the business
application.
6. Audio or Video-based Applications: Python is flexible to perform multiple tasks and
can be used to create multimedia applications. Some multimedia applications which
are made by using Python are TimPlayer, cplay, etc.
7. 3D CAD Applications: The CAD (Computer-aided design) is used to design
engineering related architecture. It is used to develop the 3D representation of a part
of a system. Python can create a 3D CAD application by using Fandango which is a
real application with full features of CAD.
8. Enterprise Applications: Python can be used to create applications that can be used
within an Enterprise or an Organization. Some real-time applications are OpenERP,
Tryton, Picalo, etc.
9. Image Processing Application: Python contains many libraries that are used to work
with the image. Using Python several applications can be developed for image.
Installation of Python: Python is a widely used high level programming language. To write
and execute code in Python, we first need to install Python on our system, installing Python
on windows takes a series of few easy steps.
3
Step 1: Select version of Python to install:
Python has various versions available with differences between the syntax and working of
different versions of the language. We need to choose the version which we want to user or
need. Python has two main different versions: Python 2 and Python 3. Both are really
different. Python is currently at version 3.13.
Step 2: Download Python Executable Installer
On the web browser, in the official site of python ( [Link] move to
download for windows section. Click on download 3.13.1 in download for windows section.
We can view the list of versions available by clicking on “View the full list of downloads”.
We can Select the required versions..
Step 3: Click on Install now
Double-click the executable file, which is downloaded. Installation window will open.
The following window will open. Click on the Add Path check box, it will set the Python
path automatically.
Now, Select Customize installation and proceed. We can also click on the customize
installation to choose desired location and features
Select the required checkboxes in advanced options.
If required we can change the installation location by clicking on “browse”
Now, click on “Install”. The installation process will take few minutes to complete and once
the installation is successful, the page will appear saying "Setup was successful ".
Step 4: Verifying the Python Installation
To verify whether the python is installed or not in our system, we have to do the following.
Go to "Start" button, and search "cmd ".
Then type, " python - - version ".
If python is successfully installed, then we can see the version of the python installed.
If not installed, then it will print the error as "python” is not recognized as an internal or
external command, operable program or batch file.
Python Keywords:
Every scripting language has designated words or keywords, with particular definitions and
usage guidelines. Python is no exception. The fundamental constituent elements of any
Python program are Python keywords.
Python keywords are unique words reserved with defined meanings and functions that we can
only apply for those functions. You'll never need to import any keyword into your program
because they're permanently present.
4
Assigning a particular meaning to Python keywords means you can't use them for other
purposes in our code. You'll get a message of Syntax Error if you attempt to do the same. If
you attempt to assign anything to a built-in method or type, you will not receive a Syntax
Error message; however, it is still not a smart idea.
Python contains thirty-five keywords. Here is the complete list of Python keywords.
In distinct versions of Python, the preceding keywords might be changed. Some extras may
be introduced, while others may be deleted. By writing the following statement into the
coding window, we can retrieve the collection of keywords in the version we are working on.
import keyword
print([Link])
or we can get all the keywords by the below command
help(“keywords”)
Python Variables
Python variables are the reserved memory locations used to store values with in a Python
Program. This means that when you create a variable you reserve some space in the memory.
Based on the data type of a variable, Python interpreter allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to Python
variables, you can store integers, decimals or characters in these variables.
Rules for creating variables in Python:
1. A variable must start with a letter or underscore (_).
Example: a, my_variable, _privateVar,
2. A variable name cannot start with a number or any special character like $, (, * % etc.
5
3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
4. Python variable names are case-sensitive which means Name and NAME are two
different variables in Python.
5. Python reserved keywords cannot be used naming the variable.
Creating Python Variables
Python variables do not need explicit declaration to reserve memory space or you can say to
create a variable. A Python variable is created automatically when you assign a value to it.
The equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.
Example to Create Python Variables
This example creates different types (an integer, a float, and a string) of variables.
a = 100 # Creates an integer variable
b = 3.5 # Creates a floating point variable
name = "xyz" # Creates a string variable
Printing Python Variables
Once we create a Python variable and assign a value to it, we can print it
using print() function.
Example:
print(a)
print(b)
print(name)
When running the above Python program, this produces the following result −
100
3.5
xyz
Assigning a single value to multiple variable
Instead of separate assignments, you can do it in a single assignment statement as follows −
a=b=c=10
print (a,b,c)
10 10 10
6
Assigning a different values to multiple variables
These separate assignment statements can be combined in one. You need to give comma
separated variable names on left, and comma separated values on the right of = operator.
a,b,c = 10,20,30
print (a,b,c)
10 20 30
Deleting Python Variables
You can delete the reference to a number object by using the “del” statement. The syntax of
the “del” statement is –
Syntax: del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
Example: del a, del b, name
Getting Type of a Variable
You can get the data type of a Python variable using the python built-in function type() as
follows.
type ( ) Function
type() function in Python programming language is a built-in function which returns the
datatype of any arbitrary object. The object is passed as an argument to the type() function.
Type() function can take anything as an argument and returns its datatype, such as integers,
strings, dictionaries, lists, classes, modules, tuples, functions, etc.+
x = "raju"
y = 10
z = 10.10
print(type(x))
print(type(y))
print(type(z))
This will produce the following result:
<class 'str'>
<class 'int'>
<class 'float'>
Python Comments
Python comments are programmer-readable explanation or annotations in the Python source
code. They are added with the purpose of making the source code easier for humans to
7
understand, and are ignored by Python interpreter. Comments enhance the readability of the
code and help the programmers to understand the code very carefully.
Example:
# This is a comment
print("Hello, World!")
If we execute the code given above, the output produced will simply print "Hello, World!" to
the console, as comments are ignored by the Python interpreter and do not affect the
execution of the program.
Python supports three types of comments as shown below −
Single-line comments
Multi-line comments
Single Line Comments in Python
Single-line comments in Python start with a hash symbol (#) and extend to the end of the line.
If the comment continuous to the next line, add a hashtag(#) to the subsequent line. They are
used to provide short explanations or notes about the code. They can be placed on their own
line above the code they describe, or at the end of a line of code to provide context or
clarification about that specific line.
Example:
# Inline single line comment is placed here.
print("Hello, World!")
The python compiler ignores this line. Everything following the # is omitted
Or we can give the comment like below
print("Hello, World!") # Inline single line comment is placed here.
Multi Line Comments in Python
In Python, multi-line comments are used to provide longer explanations or notes that span
multiple lines. While Python does not have a specific syntax for multi-line comments, there
are two common ways to achieve this: consecutive single-line comments and triple-quoted
strings −
Consecutive Single-Line Comments
Consecutive single-line comments refers to using the hash symbol (#) at the beginning of
each line. This method is often used for longer explanations or to section off parts of the
code.
8
Example
# This is my first Python Program.
# This will print “Hello World” Message as the output.
Multi Line Comment Using Triple Quoted Strings
We can use triple-quoted strings (''' or """) to create multi-line comments. These strings are
technically string literals but can be used as comments if they are not assigned to any variable
or used in expressions.
This pattern is often used for block comments or when documenting sections of code that
require detailed explanations.
Example
Here, the triple-quoted string provides a detailed explanation of the "gcd" function,
describing its purpose and the algorithm used −
"""
This function calculates the greatest common divisor (GCD)
of two numbers using the Euclidean algorithm.."""
Data Types:
The data types are used to define the type of a variable. It represents the type of data we are
going to store in a variable and determines what operations can be done on it.
Each programming language has its own classification of data items. With these datatypes,
we can store different types of data values.
The data stored in the memory can be of many types. For example, a person 's name is stored
as an alphabetic value and his address is stored as an alphanumeric value. Sometimes, we
also need to store answer in terms of only 'yes' or 'no', i.e., true or false. This type of data is
known as Boolean data.
Python has six basic data types which are as follows:
1. Numeric
2. String
3. List
4. Tuple
5. Dictionary
6. Boolean
9
Numeric
Numeric data can be broadly divided into integers and real numbers (i.e., fractional numbers).
Integers can themselves be positive or negative. Unlike many other programming languages,
Python does not have any upper bound on the size of integers. The real numbers or fractional
numbers are called floating point numbers in programming languages. Such floating point
numbers contain a decimal and a fractional part. Let us now look at an example that has an
integer as well as a real number:
>>>num1=2 # Integer Data type
>>>nume2=2.5 # float Data type
Python supports four different numerical types and each of them have built-in classes in
Python library, called int, bool, float and complex respectively,
var1 = 1 # int data type
var2 = True # bool data type
var3 = 10.023 # float data type
var4 = 10+3j # complex data type
String
Besides numbers, strings are another important data type. Single quotes or double
quotes are used to represent strings. A string in Python can be a series or a sequence of
alphabets, numerals and special characters. Similar to C, the first character of a string has an
index O.
Example:
>>>s=”Hello”
In Python, strings are immutable, meaning once a string object is created, it cannot
be changed. Any operation that modifies a string creates a new string object instead of
modifying the original one.
Example:
>>>s=s+”World
A new string "Hello World" is created.
A string is a non-numeric data type. Obviously, we cannot perform arithmetic operations on
it. However, operations such as slicing and concatenation can be done. Subsets of strings can
be taken using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the
string and working their way from -1 at the end.
str = 'Hello World!'
10
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator in Python
print (str + "TEST") # Prints concatenated string
List:
List is the most used data type in Python. A list can contain the same type of items.
Alternatively, a list can also contain different types of items. A list is an ordered and
indexable sequence. To declare a list in Python, we need to separate the items using commas
and enclose them within square brackets([]). The list is somewhat similar to the array in C
language. However, an array can contain only the same type of items while a list can contain
different types of items.
Example:
>>> l=[1,2,3]
>>>l={“a”,”b”,”c”}
>>>l={1,2,”a”,”b”}
The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+)
sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
Example:
List1 = [ 'abcd', 786 , 2.23, 'def', 70.2 ]
List2 = [123, 'xyz']
print (list1) # Prints complete list
print (list1[0]) # Prints first element of the list
print(list1[1:3]) # Prints elements starting from 2nd till 3rd
print(list1[2:]) # Prints elements starting from 3rd element
print(list2 * 2) # Prints list two times
print(list1 +list2) # Prints concatenated lists
Tuple
Similar to a list, a tuple is also used to store sequence of items. Like a list, a tuple consists of
items separated by commas. However, tuples are enclosed within parentheses rather than
11
within square brackets. A tuple is also a sequence, hence each item in the tuple has an index
referring to its position in the collection. The index starts from 0.
Example
Tuple1 = ('abcd', 786 , 2.23, 'abc', 70.2)
tuple 2= (123, 'def')
print(tuple1) # Prints the complete tuple
print(tuple1[0]) # Prints first element of the tuple
print(tuple1[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print(tuple1[2:]) # Prints elements of the tuple starting from 3rd element
print(tuple2 * 2) # Prints the contents of the tuple twice
print(tuple 1+ tuple2) # Prints concatenated tuples
Lists and tuples have the following differences:
In lists, items are enclosed within square brackets [], whereas in tuples, items are
enclosed within parentheses ().
Lists are mutable whereas Tuples are immutable. Tuples are read only lists. Once the
items are stored, the tuple cannot be modified.
Dictionary
Python dictionaries are kind of hash table type. A Python dictionary is an unordered
collection of key-value pairs. When we have the large amount of data, the dictionary data
type is used. Keys and values can be of any type in a dictionary. Items in dictionary are
enclosed in the curly-braces{} and separated by the comma (,). A colon (:) is used to separate
key from value. A key inside the square bracket [ ] is used for accessing the dictionary items.
Example of dictionary:
d={1:’a’,2:’b’,3:’c’}
Adding key-values to dictionary
d[4]=’d’
Printing key-values
print(d) #Print all the key values
print(d[1]) #Prints value assigned to key 1
Printing keys
print([Link]())
print([Link]())
Boolean:
12
In a programming language, mostly data is stored in the form of alphanumeric butsome times
we need to store the data in the form of “Yes” or “No”. In terms of programming language ,
yes is similar to True and No is similar to False. This True and False data is known as
Boolean data and the data types which stores this Boolean data are known as Boolean data
types. Python has two constants, named true and False, which can be used to assign boolean
values.
Example:
>>>size=1
>>>size<0
Output: False
>>>size>0
Output: True
>>>a=True
>>>print(type(a))
>>> a=True
>>> print(type(a))
Ouput: <type ‘bool’>
>>>x=False
>>>print(type(x))
Ouput: <type ‘bool’>
13
Operators:
Python operators are special symbols used to perform specific operations on one or more
operands. For example:
3+4=7
In the above expression, 3 and 4 are operands, whereas + is an operator.
Based on functionality, operands are divided into following types.
1. Arithmetic operator
2. Comparison operator
3. Assignment operator
4. Logical operator
5. Bitwise operator
Arithmetic Operator:
These operators are used to perform arithmetic operations such as addition, subtraction,
multiplication and division
Operato Description Example
r
+ Addition operator to add two operands. 10+20=30
- Subtraction operator to subtract two operands. 10-20--10
* Multiplication operator to multiply two operands. 10*2=20
/ Division operator to divide left hand operator by right hand 5/2=2. 5
Operator.
** Exponential operator to calculate power. 5**2=25
% Modulus operator to find remainder. 5%2=1
// Floor division operator to find the quotient and remove the 5//2=2
fractional part.
Example:
>>>x=10
>>>y=5
>>>z=x+y
output: z=15
>>>z=x-y
output:5
>>>z=x*y
14
output: 50
>>>z=x/y
output:2
>>>z=x//y
output: 2
>>>z=x**y
output:
Comparison Operators
Comparison operators in Python are very important in Python's conditional statements (if,
else and elif) and looping statements (while and for loops). The comparison operators also
called relational operators. Some of the well known operators are "<" stands for less than, and
">" stands for greater than operator.
Python uses two more operators, combining "=" symbol with these two. The "<=" symbol is
for less than or equal to operator and the ">=" symbol is for greater than or equal to operator.
== Is equal to a==b
15
Assignment Operators
Using the assignment operators, the right expression's value is assigned to the left operand.
The = (equal to) symbol is defined as assignment operator in Python. The following provides
a list of assignment operators.
Operato Description Example
r
= Store right side operand in left side operand. a=a+b
+= Add right side operand to left side operand and store the a+=bor a=a+b
result in left side operand.
-= Subtract right side operand from left side operand and store a—=b or a=a-b
the result in left side operand.
*= Multiply right side operand with left side operand and store a*=b or a=a*b
the result in left side operand.
/= Divide left side operand by right side operand and store the a/ b or a=a/b
result in left side operand.
%= Find the modulus and store the remainder in left side operand. a%=b or a=a%b
**= Find the exponential and store the result in left side operand. a**=b or a=a**b
//= Find the floor division and store the result in left side a//=b or a=a// b
operand.
Example:
>>>a=10
>>>b=3
>>>a+=b or a=a+b
>>>print(a)
Output : 13
>>> a-=b or a=a-b
>>>print(a)
Output: 7
>>>a*=b or a=a*b
>>>print(a)
Output: 30
>>>a=a/ or a/=b
>>>print(a)
output : 3.3333
>>>a=a**=b or a=a**b
>>>print(a)
Output: 1000
>>>a=10
>>>b=3
>>>a=a//b or a//=b
>>>print(a)
Output: 3
16
Logical Operators
These operators are used to check two or more conditions. The resultant of this operator is
always a Boolean value. Here, x and y are two operands that store either true or false Boolean
values. There are three logical operators in Python. They are "and", "or" and "not". They
must be in lowercase. The below table presents a list of logical operators. Assume x is true
and y is false.
Operator Description Example
and logical This operator performs AND operation between x and y results
AND operands. When both operands are true, the resultant false
become true.
or logical OR This operator performs OR operation between x or y results
operands. When any operand is true, the resultant true
becomes true.
not logical This operator is used to reverse the operand state. not x results
NOT false
Example:
>>> a=7
“and” operator
>>> print(a>5 and a<7)
False
>>> print(a>=5 and a<=7)
True
“or” operator
>>> print(a>5 or a<7)
True
“not” operator
>>> print(not(a>5 or a<7))
False
17
Bitwise Operators
Bitwise operator is an operator which is always operated on bits. In other words binary digits.
Bits is short form of binary digits. We cannot use bitwise operators on decimal numbers.
When you use integers as the operands, both are converted in equivalent binary, the &
operation is done on corresponding bit from each number
List of Bitwise Operators:
1. Bitwise AND(&)
2. Bitwise OR( | )
3. Bitwise NOT(~)
4. Bitwise XOR(^)
Example:
a=10
b=5
a&b=0
If we want in binary format
bin(a&b)
Output: 0
Bitwise OR Operator ( | )
The "|" symbol (called pipe) is the bitwise OR operator. If any bit operand is 1, the result is 1
otherwise it is 0.
All the combinations are –
0 | 0 is 0
0 | 1 is 1
1 | 0 is 1
18
1 | 1 is 1
a=10
b=5
a | b=0
If we want in binary format
bin(a | b)
Output: 15
Bitwise XOR Operator (^)
The Python Bitwise XOR (^) Operator also known as the exclusive OR operator, is used to
perform the XOR operation on two operands. XOR stands for “exclusive or”, and it returns
true if and only if exactly one of the operands is true. In the context of bitwise operations, it
compares corresponding bits of two operands. If the bits are different, it returns 1; otherwise,
it returns 0.
0 ^ 0 is 0
0 ^ 1 is 1
1 ^ 0 is 1
1 ^ 1 is 0
Example
a=10
b=5
print(a^b)
output: 15
Bitwise NOT Operator (~)
The preceding three bitwise operators (AND, OR, XOR) are binary operators, necessitating
two operands to function. However, unlike the others, this operator operates with only one
operand.
Python Bitwise Not (~) Operator works with a single value and returns its one’s
complement. This means it toggles all bits in the value, transforming 0 bits to 1 and 1 bits to
0, resulting in the one’s complement of the binary number.
Example:
a=10
print(~a)
output: -11
19
Input and Output:
input( ) Function:
The first function for prompting the input from user in Python is through input( ) function.
input( ) function has an optional parameter, which is the prompt string. When the input( )
function is called, in order to take input from the user then the execution of program halts and
waits for the user to provide an input. The input is given by the user through keyboard and it
is ended by the return key.
input( ) function interprets the input provided by the user, i.e. if user provides an integer
value as input then the input function will return this integer value. On the other hand, if the
user has input a String, then the function will return a string.
Example:
>>> name=input() #whenever you press enter key it will ask to enter name
SGAGDC
>>> name
'SGAGDC'
>>> print("My college name is ",name)
My college name is SGAGDC
20
#Using casting function to convert input to integer
>>>Age = int (raw_ input ("What is your age?")
What is your age?
>>>46
>>>type (age)
< type 'int' > # Input is stored as integer
Here only point is that this function was available in Python 2.7, and it has been renamed
to input() in Python 3.6
Output Function:
print(): The print() function is used to display data on the screen. This function allows us
to display text, variables and expressions on the console. Python's print() function is a built-
in function
print ("Hello World")
Any number of Python expressions can be there inside the parenthesis. They must be
separated by comma symbol. Each item in the list may be any Python object, or a valid
Python expression.
Example:
>>>a = "Hello World"
>>>b = 100
>>>c = 25.50
>>>print ("Message:” a)
>>>print (b, c, b-c)
The first call to print() displays a string literal and a string variable. The second prints value
of two variables and their subtraction.
Output:
Message: Hello World
100 25.5 74.5
21
Type Conversion in Python
Type conversion (also called type casting) is the process of converting one data type into
another. In Python there are different data types. There may be a situation where, we have the
available data of one type but we want to use it in another form. For example, the user has
input a string but we want to use it as a number. Python's type casting mechanism let you do
that. Python provides two types of type conversion:
1. Implicit Type Conversion (Automatic)
2. Explicit Type Conversion (Manual)
Implicit Type Conversion: Python automatically converts a smaller data type to a larger data
type to avoid data loss. In implicit type casting, a Python object with lesser byte size is
upgraded to match the bigger byte size of other object in the operation.
Example:
Consider we have an, “int” and one “float” variable
<<< a=10 # int object (4 bytes)
<<< b=10.5 # float object (8 bytes)
To perform their addition, 10 − the integer object is upgraded to 10.0. It is a float, but
equivalent to its earlier numeric value. Now we can perform addition of two floats.
<<< c=a+b
<<< print (c)
Output: 20.5
Python converts int → float → complex automatically.
Example:
>>>a=True;
>>>b=10.5;
>>>c=a+b;
>>>print (c);
This will produce the following result:
11.5
Explicit Type Conversion:
In Explicit Type Conversion in Python, the data type is manually changed by the user as per
their requirement. With explicit type conversion, there is a risk of data loss since we are
forcing an expression to be changed in some specific data type. Python always converts
22
smaller data types to larger data types to avoid the loss of data. We can use Python's built-in
functions int(), float() and str() to perform the explicit conversions such as string to integer.
Python int() Function:
Python's built-in int() function converts an integer literal to an integer object, a float to
integer, and a string to integer if the string itself has a valid integer literal representation.
Example
>>>a=1.0
>>>print(type(a))
Ouput: <class 'float'>
Converting float to int
b = int(y)
print(b)
print(type(b))
Output: <class 'int'>
Python float() Function
The float() is a built-in function in Python. It returns a float object if the argument is a float
literal, integer or a string with valid floating point representation.
#convert from int to float:
x=5
a = float(x)
print(a)
Output: 5.0
print(type(a))
output: <class 'float'>
#convert from int to complex:
a=3
c = complex(a)
print(c)
Output: (3+0j)
print(type(c)
output: <class 'complex'>
String to Integer
The int() function returns an integer from a string object, only if it contains a valid integer
representation.
23
Example:
<<< a = int("100")
<<< a
100
<<< type(a)
<class 'int'>
<<< a = ("10"+"01")
<<< a = int("10"+"01")
<<< a
1001
<<< type(a)
<class 'int'>
However, if the string contains a non-integer representation, Python raises Value Error.
<<< a = int("Hello World") # this will give error
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example:
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:
Example
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, but it has to be at least one.
Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of code, otherwise Python will
give you an error:
24
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Flow of control in Python:
Python program control flow is regulated by various types’ of conditional statements, loops
and function calls. By default, the instructions in a computer program are executed in a
sequential manner, from top to bottom or from start to end. However such sequentially
executing programs can perform only simplistic tasks. We would like the program to have a
decision- making ability, so that it performs different steps depending on different conditions.
Most of the programming languages including Python provide functionality to control the
flow of execution of instructions.
Decision Making statements / Decision Structures / Control Statements:
Decision making statements are used in the Python programs to make them able to decide
which of the alternative group of instructions to be executed, depending on value of a certain
Boolean expression.
Python language supports different types of conditional branching statements which are as
follows:
1. if Statement
2. if-else Statement
3. if-elif-else statement.
4. Nested if statement
if Statement: The if statement is used to test a particular condition and if the condition is
true, it executes a block of code known as if-block. The condition of if statement can be any
valid logical expression which can be either evaluated to true or false.
Syntax:
if expression:
statement
if structure may include 1 or n statements enclosed within if block.
First, test expression is evaluated. If the test expression is true, the statement of if block
(statement 1 to n) are executed, otherwise these statements will be skipped and the
execution will jump to nest statement which is outside of the if block.
25
Flow Chart:
Example:
x=10 # Initialising the value of x
if x>0: # Test the value of x
x=x+1 # Incrementing the value of x if x>0
print(x) # Print the value of x
if-else statement:
The if-else statement in Python is used to execute a block of code when the condition in the if
statement is true, and another block of code when the condition is false.
Syntax:
if condition:
#block of statements
else:
#another block of statements (else-block)
Flow Chart:
26
Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
if-elif-else statement:
The if elif else statement allows you to check multiple expressions for TRUE and
execute a block of code as soon as one of the conditions evaluates to TRUE.
Similar to the else block, the elif block is also optional. However, a program can contains
only one else block whereas there can be an arbitrary number of elif blocks following an if
block.
Syntax:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
27
The keyword elif is a short form of else if. It allows the logic to be arranged in a cascade
of elif statements after the first if statement. If the first if statement evaluates to false,
subsequent elif statements are evaluated one by one and comes out of the cascade if any one
is satisfied.
Last in the cascade is the else block which will come in picture when all preceding if/elif
conditions fails.
Flow Chart:
Example:
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
elif marks >= 60:
print("Grade: D")
else:
print("Grade: F")
28
Nested if statement :
Python supports nested if statements which means we can use a conditional if and if...else
statement inside an existing if statement. There may be a situation when you want to check
for additional conditions after the initial one resolves to true. In such a situation, you can use
the nested if construct. Additionally, within a nested if construct, you can include
an if...elif...else construct inside another if...elif...else construct.
Syntax:
if condition1:
# Code block for condition1
if condition2:
# Code block for condition2 (nested inside condition1)
else:
# Code block if condition2 is false
else:
# Code block if condition1 is false
Flow Chart:
Example:
age = 70
is_member = True
29
if age >= 60:
if is_member:
else:
30
Loops or Iteration Statements:
While Loop:
In python, while loop is useful to execute the block of statements repeatedly until the
specified condition is True. The while loop is useful when you are unsure about the number
of times to execute the block of statements. This loop starts with while keyword followed by
a boolean expression and colon symbol (:). Then, an indented block of statements starts.
Here, statement(s) may be a single statement or a block of statements with uniform indent.
The condition may be any expression. As soon as the expression becomes false, the program
control passes to the line immediately following the loop.
If it fails to turn false, the loop continues to run, and doesn't stop unless forcefully stopped.
Such a loop is called infinite loop, which is undesired in a computer program
In while loop, you can use the break, continue, and pass statements to exit or continue the
execution of statements inside the loop based on your requirements.
While Loop Syntax
In python, we will use the while keyword to define the while loop.
Following is the syntax of defining while loop in python.
while boolean_expression:
statement1
statement2
…
statement
Flowchart of While loop
The following flow diagram illustrates the while loop −
31
If you observe the above while loop flow chart diagram, while loop block statements will
repeatedly execute until the defined condition is True.
While Loop Example
Following is the example of a while loop in python to execute the block of statements
repeatedly until the defined Boolean expression returns True
a=1
while a < 5:
print(a)
a += 1
print("Outside of while loop")
If you observe the above example, we defined while loop with Boolean expression and
followed the required indentation to define the block of statements inside while loop.
When you execute the above python program, you will get the result as shown below.
1
2
3
4
Outside of while loop
Else Block in While Loop
Same as the python if-else statement, you can also use the else block in while loop but
the else block statements will execute only after completion of while loop execution.
a=1
while a < 5:
print(a)
a += 1
else:
print("Else block in while loop")
When you execute the above python program, you will get the result as shown below.
1
2
3
4
Else block in while loop
If you observe the above result, the else block statements have been executed only after
completion of all iterations in a while loop.
Python For Loop
In python, for loop is useful to iterate through the items of any sequence type such
as list, tuple, string, etc., and execute the block of statements repeatedly for each item of the
sequence type.
32
In for loop, you can use the break, continue, and pass statements to pass or continue the
execution of statements inside of the loop based on your requirements.
For Loop Syntax
In python, we will use for keyword to define for loop. Following is the syntax of
defining for loop in python to iterate through the sequence items.
for item in sequence:
statement 1
statement 2
…
Statement n
In the above for loop syntax, the item variable will refer to the values in the sequence starting
from index 0. The statements inside of for loop will repeatedly execute for all the items in the
sequence type.
As discussed in python if and if-else statements, you need to follow the indentation to create
for loop block statements. To know more about specifying the indentation in python, refer to
Python basic syntaxes.
Python For Loop Flow Chart
Following is the flow chart diagram of for loop process flow in python.
If you observe the above for loop flow chart diagram, for loop block statements will
repeatedly execute for every item in the sequence type such as list, tuple, string, etc.
33
For Loop Example
Following is the example of using for loop on the list object to iterate through the items in
python to execute the block of statements repeatedly based on the requirements.
range() Function:
34
The range() function in Python generates a sequence of numbers and is commonly used in
loops. It does not return a list but a range object, which is an iterable.
Syntax
The range() function has the following syntax –
range(start, stop, step)
If you observe the above code, the range() function is useful to generate the sequence of
numbers starting from 0. Here, the range(4) function will generate the numbers from 0 to 3.
for num in range(4):
print(num)
for num in range(10,20):
print(num)
for num in range(1,10,2):
print(num)
When you execute the above python program, you will get the result as shown below.
01234
10 11 12 13 14 15 16 17 18 19
13579
Nested Loops:
Python Nested While Loop
In python, nested while loops can be created by adding one while loop inside another while
loop based on your requirements.
Syntax:
while condition1: # Outer while loop
while condition2: # Inner while loop
# Code block for inner loop
# Code block for outer loop
35
print("a:{}, b: {}".format(a,b))
a += 1
print("Outside of Loop")
When you execute the above python program, you will get the result as shown below.
a:1, b: 1
a:1, b: 2
a:1, b: 3
a:2, b: 1
a:2, b: 2
a:2, b: 3
a:3, b: 1
a:3, b: 2
a:3, b: 3
Outside of Loop
The {} curly brackets are placeholders used in Python's string formatting. The .format()
method is used to insert values into these placeholders dynamically
Break Statement
In python, break statement is useful to stop or terminate the execution of loops such as for,
and while before the iteration of sequence items completed.
If you use a break statement inside the nested loop, it will terminate the inner loop's
execution.
36
Break Statement Syntax
Break
If you observe the above break statement flow chart diagram, the execution of conditional
block statements will be stopped when the break statement is executed.
Following is the example of using a break statement in python for loop to stop the loop's
execution based on the defined condition.
for x in range(5):
if x == 3:
break
print(x)
print("Loop Execution Finished")
When you execute the above python program, you will get the result as shown below.
0
1
2
Loop Execution Finished
37
If you observe the above result, the for loop terminated without looping through all the items
and executed the statements immediately after the body of the loop.
Python Break Statement in While Loop
Like python for loop, you can also use break statement in a while loop to terminate the loop's
execution based on your requirements.
Following is the example of using a break statement in python while loop to stop the loop's
execution based on the defined condition.
a=1
while a < 5:
if a == 3:
break
print(a)
a += 1
print("Outside of Loop")
When you execute the above python program, you will get the result as shown below.
1
2
Outside of Loop
If you observe the above result, the while loop terminated without looping through all the
items and executed the statements outside of the loop.
The main difference between break and continue statements are the break statement will
completely terminate the loop, and the program execution will move to the statements after
the body of the loop, but the continue statement skips the execution of the current iteration of
the loop and continue to the next iteration.
Continue Statement Syntax
Following is the syntax of defining the continue statement in python.
continue
38
If you observe the above continue statement flow chart diagram, the execution of code inside
a loop will be skipped for a particular iteration when the continue statement is executed.
For Loop with Continue Statement
In python, you can use the continue statement in for loop to skip the current iteration of the
loop and continue to the next iteration.
Following is the example of using the continue statement in python for loop to skip the
execution of a particular iteration and pass control to the next iteration of the loop based on
the defined condition
for x in range(5):
if x == 3:
continue
print(x)
print("Outside of the loop")
When you execute the above python program, you will get the result as shown below.
0
1
2
4
Outside of the loop
If you observe the above result, the for loop has skipped the execution for 3rd item iteration
and continued to the next iteration.
While Loop with Continue Statement
Like python for loop, you can also use continue statement in a while loop to skip the
execution of the current iteration of the loop and continue to the next iteration.
Following is the example of using a continue statement in python while loop to skip the
execution of a particular iteration and pass control to the next iteration of the loop based on
the defined condition.
39
a=0
while a < 5:
a += 1
if a == 3:
continue
print(a)
print("Outside of Loop")
When you execute the above python program, you will get the result as shown below.
1
2
4
5
Outside of Loop
If you observe the above result, the while loop has skipped the 3rd item iteration execution
and continued to the next iteration.
for x in range(5):
if x == 3:
pass
print(x)
print("Loop Execution Finished")
When you execute the above python program, you will get the result as shown below.
0
1
2
3
4
Loop Execution Finished
If you observe the above result, even after executing the pass statement inside of for loop, it
continued the statements' execution.
40
Match-Case Statement
A Python match-case statement takes an expression and compares its value to successive
patterns given as one or more case blocks. Only the first pattern that matches gets executed. It
is also possible to extract components (sequence elements or object attributes) from the value
into variables.
With the release of Python 3.10, a pattern matching technique called match-case has been
introduced, which is similar to the switch-case construct available in C/C++/Java etc. Its
basic use is to compare a variable against one or more values.
Syntax
The following is the syntax of match-case statement in Python
match variable_name:
case 'pattern 1' : statement 1
case 'pattern 2' : statement 2
...
case 'pattern n' : statement n
Example
The following code has a function named weekday(). It receives an integer argument,
matches it with all possible weekday number values, and returns the corresponding name of
day.
def weekday(n):
match n:
case 0: return "Monday"
case 1: return "Tuesday"
case 2: return "Wednesday"
case 3: return "Thursday"
case 4: return "Friday"
case 5: return "Saturday"
case 6: return "Sunday"
case _: return "Invalid day number"
print (weekday(3))
print (weekday(6))
41
print (weekday(7))
42
Strings:
Python string is the collection of the characters surrounded by single quotes, double quotes,
or triple quotes. Here the character can be a letter, digit, whitespace or any other symbol. The
computer does not understand the characters; internally, it stores manipulated character as the
combination of the 0's and 1's.
Syntax:
str = "Hi Python !"
if we check the type of the variable str using a Python script
print(type(str)),
then it will print a string (str).
Creating String in Python
We can create a string by enclosing the characters in single-quotes or double- quotes. Python
also provides triple-quotes to represent the string.
s1 = 'Hello'
s2 = "World"
s3 = '''Python is fun'''
print(s1, s2, s3)
Output:
Hello World Python is fun
String Operations:
String Concatenation (+)
String concatenation in Python is the operation of joining two or more strings together. The
result of this operation will be a new string that contains the original strings.
The "+" operator is well-known as an addition operator, returning the sum of two numbers.
However, the "+" symbol acts as string concatenation operator in Python. It works with two
string operands, and results in the concatenation of the two.
The characters of the string on the right of plus symbol are appended to the string on its left.
Result of concatenation is a new string.
Example:
s1 = "Hello"
s2 = "World"
result = s1 + " " + s2
print(result)
43
Output:
Hello World
s = "Hi!"
print(s * 3)
Output:
Hi! Hi! Hi!
Indexing ([])
In Python, a string is an ordered sequence of Unicode characters. Each character in the string
has a unique index in the sequence. The index starts with 0. First character in the string has its
positional index 0. The index keeps incrementing towards the end of string.
If a string variable is declared as var="HELLO PYTHON", index of each character in the
string is as follows –
Python allows you to access any individual character from the string by its index. In this case,
0 is the lower bound and 11 is the upper bound of the string. So, var[0] returns H, var[6]
returns P. If the index in square brackets exceeds the upper bound, Python raises IndexError.
Example:
44
print(var[7])
print(var[11])
print(var[12])
Slicing ([:])
Python String slicing is a way of creating a sub-string from a given string. In this process, we
extract a portion or piece of a string. Usually, we use the slice operator "[ : ]" to perform
slicing on a Python String.
Example:
s = "HelloWorld"
print(s[0:5]) # Hello (From index 0 to 4)
print(s[:5]) # Hello (Start from 0)
print(s[5:]) # World (Till the end)
print(s[::2]) # Hlool (Every 2nd character)
print(s[::-1]) # dlroWolleH (Reverse)
Membership:
Membership operators are used to check whether a value exists with in a sequence such as a string,
list, tuple, or dictionary in python. In python there are two membership operators.
1. ‘In’ operator – Returns “ True” if the specified value is present in the sequence.
2. ‘Not in’ operator – returns “True” if the specified value not present in the sequence.
In python, the len() function is useful to get the number of characters in a string or the length
of a string. Following is the example of len() function in python
45
Example:
s = "Python"
print(len(s))
Traversing a String:
Example:
text = "Hello!"
for char in text:
print(char)
Output:
H
e
l
l
o
!
Example:
s=’hello’
upper() Converts to uppercase
print([Link]())
s=’hello’
lower() Converts to lowercase
print([Link]())
s=’helloworld’
capitalize() Capitalizes first letter of the first word.
print([Link]())
s=’ helloworld’
strip() Removes spaces
print([Link]())
s=’ helloworld’
replace() Replaces substrings
print([Link](‘h’,’w’))
" s=’ helloworld’
split() Splits into a list
Print([Link]())
s=’ helloworld’
join() Joins list into a string
print(''.join(a))
s=’ helloworld’
startswith() Checks start
print([Link]('y'))
s=’ helloworld’
endswith() Checks end
print([Link]('d'))
s=’ helloworld’
find() Finds substring index
print([Link]('worlsd'))
47
Debugging in Python
Debugging is the process of identifying and fixing errors (bugs) in your code. Python
provides several tools and techniques for debugging.
Syntax Errors: Incorrect Python syntax (e.g., missing colons, incorrect indentation).
Runtime Errors: Errors that occur during execution (e.g., division by zero, accessing
undefined variables).
Logical Errors: The code runs without errors but produces incorrect results.
assert is used to check conditions during debugging. That means assert is used to check if b
is not equal to zero before performing the division.
try:
num = int(input("Enter a number: "))
print(10 / num)
except ValueError:
print("Invalid input! Please enter a number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
48
5. Using the Python Debugger (pdb)
Using pdb.set_trace()
import pdb
49