0% found this document useful (0 votes)
23 views138 pages

Introduction to Python Programming Basics

Python is an object-oriented, interpreted, high-level programming language created by Guido van Rossum and first released in 1991. It is known for its simplicity, extensive libraries, and strong community support, making it suitable for various applications such as web development, data science, and machine learning. The document also covers Python's features, installation process, variable assignment, tokens, and operators.

Uploaded by

Giri Babu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views138 pages

Introduction to Python Programming Basics

Python is an object-oriented, interpreted, high-level programming language created by Guido van Rossum and first released in 1991. It is known for its simplicity, extensive libraries, and strong community support, making it suitable for various applications such as web development, data science, and machine learning. The document also covers Python's features, installation process, variable assignment, tokens, and operators.

Uploaded by

Giri Babu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit – I

Introduction to Python

History: Python is an object-oriented, interpreted, high-level programming language. It is general purpose, and
we use it to develop GUI (A graphical user interface (GUI) is a digital interface in which a user interacts with
graphical components such as icons, buttons, and menus.) and web applications. With Python, we can
concentrate on the business logic of our code rather than investing a lot of time in common programming tasks.

Python was created by Guido van Rossum, and first released on February 20, 1991. While we may know the
python as a large snake, the name of the Python programming language comes from an old BBC television
comedy sketch series called Monty Python's Flying Circus.

There are 1000s of languages, so why Python?

1. Python is simple and easy to learn

2. It has libraries for almost everything. Django for web development and Matplotlib for data visualization.

3. It is reliable, efficient and time-saving.

4. It has large, active, and helpful open-source community.

5. It offers career opportunities in various fields.

Where we can use Python

1. Web Application using libraries Django, Flask, and Tornado.

2. Desktop Application using PyGTK and Cocoa.

3. Machine Learning, Data Science and Deep Learning Models using Sklearn, TensorFlow, Theano, and Spark.

4. Cloud and DevOps by using Openstack APIs and Fabric.

5. Hardware Programming by Rasberry Pi.

Features:
1. Free and Open Source
Python language is freely available at the official website. Since it is open-source; this means that source code
is also available to the public. So you can download it, use it as well as share it.

2. Easy to code
Python is a high-level programming language. Python is very easy to learn the language as compared to other
languages like C, C#, Javascript, Java, etc. It is very easy to code in the Python language and anybody can
learn Python basics in a few hours or days. It is also a developer-friendly language.

3. Easy to Read
As you will see, learning Python is quite simple. As was already established, Python’s syntax is really
straightforward. The code block is defined by the indentations rather than by semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports object-oriented language
and concepts of classes, object encapsulation, etc.

5. GUI Programming Support


Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk in Python.
PyQt5 is the most popular option for creating graphical apps with Python.

6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need to remember the system
architecture, nor do we need to manage the memory.

7. Large Community Support


Python has gained popularity over the years. Our questions are constantly answered by the enormous
StackOverflow community. These websites have already provided answers to many questions about Python,
so Python users can consult them as needed.

8. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify and correct the majority of
your program’s issues once you understand how to interpret Python’s error traces. Simply by glancing at the
code, you can determine what it is designed to perform.

9. Python is a Portable language


Python language is also a portable language. For example, if we have Python code for Windows and if we
want to run this code on other platforms such as Linux, Unix, and Mac then we do not need to change it, we
can run this code on any platform.

10. Python is an Integrated language


Python is also an Integrated language because we can easily integrate Python with other languages like
C, C++, etc.

11. Interpreted Language:


Python is an Interpreted Language because Python code is executed line by line at a time. like other
languages C, C++, Java, etc. there is no need to compile Python code this makes it easier to debug our code.
The source code of Python is converted into an immediate form called bytecode.

12. Large Standard Library


Python has a large standard library that provides a rich set of modules and functions so you do not have to
write your own code for every single thing. There are many libraries present in Python such as regular
expressions, unit-testing, web browsers, etc.

13. Dynamically Typed Language


Python is a dynamically-typed language. That means the type (for example- int, double, long, etc.) for a
variable is decided at run time not in advance because of this feature we don’t need to specify the type of
variable.

14. Frontend and backend development


With a new project py script, you can run and write Python codes in HTML with the help of some simple tags
<py-script>, <py-env>, etc. This will help you do frontend development work in Python like javascript.
Backend is the strong forte of Python it’s extensively used for this work cause of its frameworks
like Django and Flask.

15. Allocating Memory Dynamically


In Python, the variable data type does not need to be specified. The memory is automatically allocated to a
variable at runtime when it is given a value. Developers do not need to write int y = 18 if the integer value 15
is set to y. You may just type y=18.

Installing Python & Running Python:


To download Python, we need to visit [Link], which is the official Python website.

This will take you to the page where the different Python releases for Windows can be found. Since we are
using a 64bit system, We will select “Windows x86-64 executable installer”.
Once the executable file download is complete, you can open it to install Python.

Click on Run, which will start the installation process.

If you want to save the installation file in a different location, click on Customize installation; otherwise,
continue with Install Now. Also, select the checkbox at the bottom to Add Python 3.7 to PATH.
Once the installation is complete, the below pop-up box will appear: Setup was successful.

Now that the installation is complete, you need to verify that everything is working fine.

Go to Start and search for Python.


We can see Python 3.7 (64-bit) and IDLE. Let’s open IDLE, which is the short form for Integrated
Development Environment, and run a simple print statement.

As you can see, we have successfully printed “Hello World” in Python Shell. Using the Python Shell, you can
write one line of code and execute it by pressing Enter.

Python also has a command-line interpreter that works similarly to Python IDLE. Let’s print “Hello world” in
the command-line.

Python’s command-line interpreter and IDLE are suitable for any beginner to start with. However, to work in a
developer environment and build large scale projects, you should use other popular IDEs and code editors, such
as PyCharm, Atom, and Sublime Text. You can also try out the Anaconda Distribution of Python, which has
Jupyter Notebook and Spyder.
Most popular IDLE (Integrated Development and Learning Environment) for python:

Python Variables: A variable is a memory location where we can store values. In Python, the data type will be
identified according to the data we provide.

A variable should start with a letter or an underscore and can’t start with numbers. There are two ways of
assigning values to a variable:

 Assigning a Single Value


 Multiple Assignment

1. print("Hello, World!")

Hello, World!

2. name="John"
type(name)

str

3. name=1
type(name)

int

4. name=1.5
type(name)

float

Python is a duck typing language. It means the data types of variables can change as long as the syntax is
compatible. It will look at variable it’s a number so assign class as int, and we can use it.
5. 1+1

6. "abc"+"def"

'abcdef'

7. "abc"+1

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[8], line 1
----> 1 "abc"+1

TypeError: can only concatenate str (not "int") to str

Assigning a Single Value to a Variable:

1. a=10
Name="Victor"
Salary=200000
print(a)
print(Name)
print(Salary)

10
Victor
200000

2. Name="Victor"
print(Name)

Victor

3. 1Name="Victor"
print(Name)

Cell In[13], line 1


1Name="Victor"
^
SyntaxError: invalid decimal literal

4. _Name="Victor"
print(_Name)

Victor

5. Name1="Victor"
print(Name)

Victor
6. $Name="Victor"
print(Name)
Cell In[16], line 1
$Name="Victor"
^
SyntaxError: invalid syntax

7. Name$="Victor"
print(Name)
Cell In[16], line 1
$Name="Victor"
^
SyntaxError: invalid syntax

8. ___Name="Victor"
print(Name)

Victor
Assigning a Multiple Value to a Variable:

a=b=c=10
x,y,z=10,20,30
print(a)
print(b)
print(c)
print(x)
print(y)
print(z)

10
10
10
10
20
30
Python Tokens

Python Tokens: In Python, every logical line of code is broken down into components known as Tokens.

 Keywords
 Identifiers
 Literals
 Operators

Keywords: Python keywords are special reserved words; they convey a special meaning to the
compiler/Interpreter. Each keyword has a special meaning and a specific operation and never uses it as a
variable.
1. ret=7
print(ret)

2. return=7
print(ret)
Cell In[23], line 1
return=7
^
SyntaxError: invalid syntax

Identifiers: Python Identifier is the name we give to identify a variable, function, class, module or other object
Or Identifier is nothing but a name is python.

Rules for naming Identifiers


1. No special character, except underscorer(_), can be used as an identifier.
2. Keywords should not be used as an identifier.
3. Python is case sensitive, i.e., ‘Var’ and ‘var’ are two different identifiers.
4. The first character of an identifier can be a alphabet or underscore (_) but not a digit.
5. Identifier can be a variable.

Valid Identifiers In Python Examples:

 Lowercase letters (a to z)
 Uppercase letters (A to Z)
 Digits (0 to 9)
 Underscore (_)
Invalid Identifiers In Python Examples:

 !var1
 1 var
 1_var
 var#1

1. var=7
Var=8
print(var)
print(Var)

7
8

Literals: A literal is the raw data given to a variable.

 String literals
 Numeric literals
 Boolean literals
 Special literals

String literals: Formed by enclosing a text within quotes. Both single and double quotes can be used.

Name="Victor"
print(Name)

Victor

Numeric literals: Formed by string of digits from 0 to 9, decimal point, and a plus/minus sign.

1. num=-77
print(num)
type(num)

-77
Int
2. num= 7.5
print(num)
type(num)

7.5
Float

3. num= 7.5+5j
print(num)
type(num)

(7.5+5j)
complex

Boolean literals: It can be either true or false

1. password="abcd"
confrimpassword ="abcd"
password == confrimpassword

True

2. password="abcd"
confrimpassword ="abcde"
password == confrimpassword

False

Special literals:
confrimpassword =None
print(confrimpassword)
type (confrimpassword)

None
NoneType
Operators: Operators are special symbols that are used to carry out arithmetic and logical operations.

 Arithmetic
 Assignment
 Comparison
 Logical
 Identity
 Membership
 Bitwise

Arithmetic Operators: Used for common mathematical operations.

a=7
b=2

# addition
print ('Sum: ', a + b)

# subtraction
print ('Subtraction: ', a - b)

# multiplication
print ('Multiplication: ', a * b)

# division
print ('Division: ', a / b)

# modulo
print ('Modulo: ', a % b)
# floor division
print ('Floor Division: ', a // b)

The division operator / in Python returns the exact result of the division operation as a floating-point number,
while the floor division operator // returns the quotient rounded down to the nearest integer.

# a to the power b
print ('Power: ', a ** b)

Assignment Operators: Used to assign values to variables.


Comparison Operators: Compares values and return either True or False.

x=5
y=5
z=5
res = x == y
res2 = x == z
print (res)
print (res2)

True
True

x=5
y = 10
res = x != y
print (res)

True

x=5
y = 10
res = x < y
res1 = y < x
print (res)
print (res1)

True
False

x=5
y = 10
res = x > y
res1 = y > x
print (res)
print (res1)

False
True
x=5
y=5
z = 10
res = x >= y
res2 = x >= z
print (res)
print (res2)

True
False

x=5
y=5
z = 10
res = x <= y
res1 = x <= z
print (res)
print (res1)

True
True

Logical Operators: Used to combine conditional statements.

# logical AND
print(True and True) # True
print(True and False) # False

True
False

# logical OR
print(True or False) # True

True

# logical NOT
print(not True) # False

False
1. x=5
y=16
x==5

True

2. x=5
y=16
y!=16

False

3. x=5
y=16
x==5 and y!=16

False

Identity Operators: Used to check if the objects are same or not

x = ["bread", "cake"]
y = ["bread", "cake"]
z=x

print(x is z)

print(x is not z)

Membership Operators: Used to test if a sequence is present in an object

x = ["apple", "banana"]
print("banana" in x)

x = ["apple", "banana"]
print("pineapple" not in x)
Bitwise Operators: Used to compare binary numbers. In Python, bitwise operators are used to perform
bitwise calculations on integers. The integers are first converted into binary and then operations are
performed on each bit or corresponding pair of bits, hence the name bitwise operators. The result is then
returned in decimal format.
Bitwise AND(&)
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)

a & b = 1010
&
0100
= 0000
= 0 (Decimal)

Bitwise OR(|)
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)

a | b = 1010
|
0100
= 1110
= 14 (Decimal)

Bitwise NOT(~)
Python’s bitwise NOT operator ~x inverts each bit from the binary representation of integer x so that 0

becomes 1 and 1 becomes 0. This is semantically the same as calculating ~x == -x-1 . For example, the

bitwise NOT expression ~0 becomes -1 , ~9 becomes -10 , and ~32 becomes -33 .

Bitwise XOR(^)
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)

a ^ b = 1010
^
0100
= 1110
= 14 (Decimal)

# Python program to show


# bitwise operators

a = 10
b=4

# Print bitwise AND operation


print("a & b =", a & b)
# Print bitwise OR operation
print("a | b =", a | b)

# Print bitwise NOT operation


print("~a =", ~a)

# print bitwise XOR operation


print("a ^ b =", a ^ b)

Output:
a&b=0
a | b = 14
~a = -11
a ^ b = 14

Bitwise right shift (>>)


Bitwise left shift (<<)

# Python program to show


# shift operators

a = 14

# print bitwise right shift operator


print("a >> 1 =", a >> 1)
print("a >> 2 =", a >> 2)

# print bitwise left shift operator


print("a << 1 =", a << 1)
print("a << 1 =", a << 2)

Output:
a >> 1 = 7
a >> 2 = 3
a << 1 = 28
a << 2= 56
Decimal to Binary Examples

Example 1:

Convert 16010 to binary Number

Solution:

Given: Decimal Number = 16010

Divide by 2 Result Remainder Binary Value

160 ÷ 2 80 0 0 (LSB)

80 ÷ 2 40 0 0

40 ÷ 2 20 0 0

20 ÷ 2 10 0 0

10 ÷ 2 5 0 0

5÷2 2 1 1

2÷2 1 0 0

1÷2 0 1 1 (MSB)

Therefore, 16010 = 101000002

Example 2:

Convert 1710 into a binary number

Solution:

Given: Decimal Number = 1710

Divide by 2 Result Remainder Binary Value

17 ÷ 2 8 1 1 (LSB)
8÷2 4 0 0

4÷2 2 0 0

2÷2 1 0 0

1÷2 0 1 1 (MSB)

Therefore, 1710 = 100012

Example of Binary to Decimal Conversion:

Convert the binary number (1101)2 into a decimal number.

Solution:

Given binary number = (1101)2

Now, multiplying each digit from MSB to LSB with reducing the power of the base number 2.

1 × 23 + 1 × 2 2 + 0 × 2 1 + 1 × 2 0

=8+4+0+1

= 13

Indentation in Python
Indentation is a very important concept of Python because without properly indenting the Python code, you
will end up seeing Indentation Error and the code will not get compiled.
Python Indentation
Python indentation refers to adding white space before a statement to a particular block of code. In another
word, all the statements with the same space to the right, belong to the same code block.

Example of Python Indentation


 Statement (line 1), if condition (line 2), and statement (last line) belongs to the same block which means
that after statement 1, if condition will be executed. And suppose the if condition becomes False then the
Python will jump to the last statement for execution.
 The nested if-else belongs to block 2 which means that if nested if becomes False, then Python will
execute the statements inside the else condition.
 Statements inside nested if-else belong to block 3 and only one statement will be executed depending on
the if-else condition.

Python indentation is a way of telling a Python interpreter that the group of statements belongs to a particular
block of code. A block is a combination of all these statements. Block can be regarded as the grouping of
statements for a specific purpose. Most programming languages like C, C++, and Java use braces { } to
define a block of code. Python uses indentation to highlight the blocks of code. Whitespace is used for
indentation in Python. All statements with the same distance to the right belong to the same block of code. If
a block has to be more deeply nested, it is simply indented further to the right.

Statements and Expressions:

Statements: A simple statement is a construct that occupies a single logical line, like an assignment statement.
A compound statement is a construct that occupies multiple logical lines, such as a for loop or
a conditional statement. Statements use key words, it may or may not lead to result. The Python language has
many different types of statements like assignment statements, conditional statements, looping statements, etc.,
that help a programmer get the desired output.

Expressions: A combination of operands and operators is called an expression. The expression in Python
produces some value or result after being interpreted by the Python interpreter. An expression in Python is a
combination of operators and operands.

x = 25 # a statement
x = x + 10 # an expression

print(x)

output: 35

Types of Expression in Python:


1. Constant Expressions: These are the expressions that have constant values only.

x = 10 + 15

# Here both 10 and 15 are constants but x is a variable.


print("The value of x is: ", x)
Output
The value of x is: 25

2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators, and


sometimes parenthesis. The result of this type of expression is also a numeric value. The operators used in
these expressions are arithmetic operators like addition, subtraction, etc. Here are some arithmetic operators
in Python:

Operator Syntax Working


+ x+y Addition or summation of x and y.
- x-y Subtraction of y from x.
* x*y Multiplication or product of x and y.
/ x/y Division of x and y.
// x // y Quotient when x is divided by y.
% x%y Remainder when x is divided by y.
** x ** y Exponent (x to the power of y).

x = 10
y=5

addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y

print("The sum of x and y is: ", addition)


print("The difference between x and y is: ", subtraction)
print("The product of x and y is: ", product)
print("The division of x and y is: ", division)
print("x to the power y is: ", power)
Output
The sum of x and y is: 15
The difference between x and y is: 5
The product of x and y is: 50
The division of x and y is: 2.0
x to the power y is: 100000

3. Integral Expressions: These are the kind of expressions that produce only integer results after all
computations and type conversions.

x = 10 # an integer number
y = 5.0 # a floating point number

# we need to convert the floating-point number into an integer or vice versa for summation.
result = x + int(y)

print("The sum of x and y is: ", result)


Output
The sum of x and y is: 15

4. Floating Expressions: These are the kind of expressions which produce floating point numbers as result
after all computations and type conversions.

x = 10 # an integer number
y = 5.0 # a floating point number

# we need to convert the integer number into a floating-point number or vice versa for summation.
result = float(x) + y

print("The sum of x and y is: ", result)

Output
The sum of x and y is: 15.0

5. Relational Expressions: In these types of expressions, arithmetic expressions are written on both sides of
relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and then compared as per
relational operator and produce a boolean output in the end. These expressions are also called Boolean
expressions.

a = 25
b = 14
c = 48
d = 45

# The expression checks if the sum of (a and b) is the same as the difference of (c and d).
result = (a + b) == (c - d)
print("Type:", type(result))
print("The result of the expression is: ", result)

Output
Type: <class 'bool'>
The result of the expression is: False

6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is
not correct, so it will return False. Studying logical expressions, we also come across some logical operators
which can be seen in logical expressions most often. Here are some logical operators in Python:

Operator Syntax Functioning

and P and Q It returns true if both P and Q are true otherwise returns false

or P or Q It returns true if at least one of P and Q is true

not not P It returns true if condition P is false


P = (10 == 9)
Q = (7 > 5)

# Logical Expressions
R = P and Q
S = P or Q
T = not P

print(R)
print(S)
print(T)

Output
False
True
True

7. Bitwise Expressions: These are the kind of expressions in which computations are performed at bit level.
# Bitwise Expressions
a = 12

x = a >> 2
y = a << 1

print(x, y)

Output
3 24

8. Combinational Expressions: We can also use different types of expressions in a single expression, and
that will be termed as combinational expressions.
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output
22
Control Structures: In the Python programming language, control structures are used to manage the flow of
execution in a program. They enable you to specify the order in which statements are executed based on certain
conditions.

 Conditional Statements
 Loops

Conditional Statements: There are situations in real life when we need to make some decisions and based
on these decisions, we decide what we should do next. Similar situations arise in programming also where we
need to make some decisions and based on these decisions we will execute the next block of code.
Conditional statements in Python languages decide the direction (Control Flow) of the flow of program
execution.
Types of Conditional Statements in Python:
1. The if statement
2. The if-else statement
3. The if-elif-else ladder
4. The nested-if statement

1. The 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
Flowchart:

Example 1
# Simple Python program to understand the if statement
num = int(input("enter the number:"))
# Here, we are taking an integer num and taking input dynamically
if num%2 == 0:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The Given number is an even number")

Output:
enter the number: 10
The Given number is an even number
Example 2 : Program to print the largest of the three numbers.

# Simple Python Program to print the largest of the three numbers.


a = int (input("Enter a: "));
b = int (input("Enter b: "));
c = int (input("Enter c: "));
if a>b and a>c:
# Here, we are checking the condition. If the condition is true, we will enter the block
print ("From the above three numbers given a is largest");
if b>a and b>c:
# Here, we are checking the condition. If the condition is true, we will enter the block
print ("From the above three numbers given b is largest");
if c>a and c>b:
# Here, we are checking the condition. If the condition is true, we will enter the block
print ("From the above three numbers given c is largest");

Output:

Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest

2. The if-else statement: The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition. If the condition is true, then the if-block is executed. Otherwise, the
else-block is executed.

Syntax:

if condition:
#block of statements
else:
#another block of statements (else-block)
Flowchart:

Example 1 : Program to check whether a person is eligible to vote or not.


# Simple Python Program to check whether a person is eligible to vote or not.
age = int (input("Enter your age: "))
# Here, we are taking an integer num and taking input dynamically
if age>=18:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");
Output:

Enter your age: 90


You are eligible to vote !!

Example 2: Program to check whether a number is even or not.


# Simple Python Program to check whether a number is even or not.
num = int(input("enter the number:"))
# Here, we are taking an integer num and taking input dynamically
if num%2 == 0:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The Given number is an even number")
else:
print("The Given Number is an odd number")

Output:

enter the number: 10


The Given number is even number

3. The if-elif-else ladder: An if-elif-else ladder in python is a conditional statement that allows you to execute
different blocks of code based on multiple conditions. It is an extension of the if-else statement, and it is used when
there are more than two possible conditions to check.

Syntax:

if expression 1:
# block of statements

elif expression 2:
# block of statements

elif expression 3:
# block of statements

else:
# block of statements
Flowchart:

Example 1
# Simple Python program to understand elif statement
number = int(input("Enter the number?"))
# Here, we are taking an integer number and taking input dynamically
if number==10:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equals to 10")
elif number==50:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equal to 50");
elif number==100:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equal to 100");
else:
print("The given number is not equal to 10, 50 or 100");

Output:

Enter the number?15


The given number is not equal to 10, 50 or 100

Example 2
# Simple Python program to understand elif statement
marks = int(input("Enter the marks? "))
# Here, we are taking an integer marks and taking input dynamically
if marks > 85 and marks <= 100:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
# Here, we are checking the condition. If the condition is true, we will enter the block
print("You scored grade C ...")
else:
print("Sorry you are fail ?")

Output:

Enter the marks? 89


Congrats ! you scored grade A ...

4. The nested-if statement: We can have an if statement inside another if statement. This is called nesting in
computer programming. Any number of these statements can be nested inside one another. Indentation is the
only way to figure out the level of nesting. This can get confusing, so it must be avoided if we can.

Syntax: if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Flowchart:

Example 1:
# Python program to demonstrate
# nested if statement

num = 15
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Output:
Positive number
Example 2:
# Python program to demonstrate
# nested if statement
i = 13

if (i == 13):
# First if statement
if (i < 15):
print ("i is smaller than 15")

# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 12 and smaller than 15")
Output:
i is smaller than 15
i is greater than 12 and smaller than 15

Loops: Python programming language provides two types of loops 1. For loop 2. While loop to handle
looping requirements.

1. For Loop: In computer programming, loops are used to repeat a block of code.

languages = ['Swift', 'Python', 'Go']

# access items of a list using for loop


for i in languages:
print(i)

Output

Swift
Python
Go

In the above example, we have created a list called languages. As the list has 3 elements, the loop
iterates 3 times.
The value of i is
 Swift in the first iteration.
 Python in the second iteration.
 Go in the third iteration.
for loop Syntax

The syntax of a for loop is:

for val in sequence:


# statement(s)

Here, val accesses each item of the sequence on each iteration. The loop continues until we reach the last item
in the sequence.

Flowchart of Python for Loop


Example: Loop through a String

language = 'Python'

# iterate over each character in language


for x in language:
print(x)
Output

P
y
t
h
o
n

Here, we have printed each character of the string language using a for loop.

For Loop with Python range ()

In Python, the range() function returns a sequence of numbers. For example,

values = range(4)

Here, range(4) returns a sequence of 0, 1, 2 ,and 3.


We can use range() with a for loop to iterate a certain number of times. For example,
# iterate from i = 0 to i = 3
for i in range(4):
print(i)
Output

0
1
2
3

Here, we used the for loop to iterate over a range from 0 to 3.


This is how the above program works.

Iteration Value of i print(i) Last item in sequence?

1st 0 Prints 0 No
2nd 1 Prints 1 No

3rd 2 Prints 2 No

Yes
4th 3 Prints 3
The loop terminates.

Python for loop with else clause

A for loop can have an optional else clause. This else clause executes after the iteration completes.
digits = [0, 1, 5]

for i in digits:
print(i)
else:
print("No items left.")
Output

0
1
5
No items left.

Here, the for loop prints all the items of the digits list. When the loop finishes, it executes the else block and
prints No items left.

Note: The else block will not execute if the for loop is stopped by a break statement.

Using for loop without accessing items

We can also use for loop to repeat an action a certain number of times. For example,
languages = ['Swift', 'Python', 'Go']

# looping to repeat an action without using the list elements


for language in languages:
print('Hi')
Output

Hi
Hi
Hi

Here, we used the list languages to run the loop three times. However, we didn't use any of the elements of the
list.
In such cases, it is clearer to use the _ (underscore) as the loop variable. The _ indicates that a loop variable is a
placeholder and its value is intentionally being ignored.
For example,

languages = ['Swift', 'Python', 'Go']

# using _ for placeholder variable


for _ in languages:
print('Hi')
Here, the loop still runs three times because there are three elements in the languages list. Using _ indicates that
the loop is there for repetition and not for accessing the elements.

A for loop can also have another for loop inside it. For each cycle of the outer loop, the inner loop completes its
entire sequence of iterations. For example,
# outer loop
for i in range(2):
# inner loop
for j in range(2):
print(i,j)
Output

00
01
10
11

In this example, we have used a nested for loop. This is how the above code executes.

Outer Loop Iteration(i) Inner Loop Iteration( j) Action: print(i,j)

1st Iteration (i=0) 1st Iteration (j=0) 0,0

1st Iteration (i=0) 2nd Iteration (j=1) 0,1

2nd Iteration (i=1) 1st Iteration (j=0) 1,0

2nd Iteration (i=1) 2nd Iteration (j=1) 1,1


2. While Loop

Python while loop is used to run a block code until a certain condition is met.

The syntax of while loop is:

while condition:
# body of while loop

Here,

1. A while loop evaluates the condition


2. If the condition evaluates to True, the code inside the while loop is executed.
3. condition is evaluated again.
4. This process continues until the condition is False.
5. When condition evaluates to False, the loop stops.

Flowchart of Python while Loop


Example: Python while Loop

# program to display numbers from 1 to 5

# initialize the variable


i=1
n=5

# while loop from i = 1 to 5


while i <= n:
print(i)
i=i+1
Output

1
2
3
4
5

Here's how the program works:

Variable Condition: i <= n Action

i = 1
True 1 is printed. i is increased to 2.
n=5

i = 2
True 2 is printed. i is increased to 3.
n=5

i = 3
True 3 is printed. i is increased to 4.
n=5

i = 4
True 4 is printed. i is increased to 5.
n=5

i = 5
True 5 is printed. i is increased to 6.
n=5
i = 6
False The loop is terminated.
n=5

Example 2: Python while Loop

# program to calculate the sum of numbers


# until the user enters zero

total = 0

number = int(input('Enter a number: '))

# add numbers until number is zero


while number != 0:
total += number # total = total + number

# take integer input again


number = int(input('Enter a number: '))

print('total =', total)


Output

Enter a number: 12
Enter a number: 4
Enter a number: -5
Enter a number: 0
total = 11

In the above example, the while iterates until the user enters zero. When the user enters zero, the test condition
evaluates to False and the loop ends.

Infinite while Loop in Python

If the condition of a loop is always True, the loop runs for infinite times (until the memory is full). For
example,
age = 32

# the test condition is always True


while age > 18:
print('You can vote')
In the above example, the condition always evaluates to True. Hence, the loop body will run for infinite times.
Python While loop with else

In Python, a while loop may have an optional else block.


Here, the else part is executed after the condition of the loop evaluates to False.
counter = 0

while counter < 3:


print('Inside loop')
counter = counter + 1
else:
print('Inside else')
Output

Inside loop
Inside loop
Inside loop
Inside else

Note: The else block will not execute if the while loop is terminated by a break statement.

counter = 0

while counter < 3:


# loop ends because of break
# the else part is not executed
if counter == 1:
break

print('Inside loop')
counter = counter + 1
else:
print('Inside else')
Output

Inside loop

Python for Vs while loops

The for loop is usually used when the number of iterations is known. For example,
# this loop is iterated 4 times (0 to 3)
for i in range(4):
print(i)
The while loop is usually used when the number of iterations is unknown. For example,

while condition:
# run code until the condition evaluates to False

Python break and continue

In programming, the break and continue statements are used to alter the flow of loops:
 break exits the loop entirely
 continue skips the current iteration and proceeds to the next one.

Python break Statement

The break statement terminates the loop completely.


Syntax

break

Working of Python break Statement

The above image shows the working of break statements in for and while loops.

Note: The break statement is usually used with decision-making statements such as if...else.
Example: break Statement with for Loop

We can use the break statement with the for loop to terminate the loop when a certain condition is met. For
example,
for i in range(5):
if i == 3:
break
print(i)
Output

0
1
2

In the above example,

if i == 3:
break

terminates the loop when i is equal to 3. Hence, the output doesn't include values after 2.

Note: We can also terminate the while loop using break statement

break Statement with while Loop

We can also terminate the while loop using the break statement. For example,
i=0

while i < 5:
if i == 3:
break
print(i)
i += 1
Output

0
1
2

In the above example,

if i == 3:
break
terminates the loop when i is equal to 3.

Python continue Statement

The continue statement skips the current iteration of the loop and the control flow of the program goes to the
next iteration.
Syntax

continue

Working of continue Statement in Python

Example: continue Statement with for Loop

We can use the continue statement with the for loop to skip the current iteration of the loop and jump to the
next iteration. For example,
for i in range(5):
if i == 3:
continue
print(i)
Output

0
1
2
4

In the above example,


if i == 3:
continue

skips the current iteration when i is equal to 3, and continues the next iteration. Hence, the output has all the
values except 3.

Note: We can also use the continue statement with a while loop.

continue Statement with while Loop

We can skip the current iteration of the while loop using the continue statement. For example,
# program to print odd numbers from 1 to 10

num = 0

while num < 10:


num += 1

if (num % 2) == 0:
continue

print(num)
Output

1
3
5
7
9

In the above example, we have used the while loop to print the odd numbers between 1 and 10. Here,

if (num % 2) == 0:
continue

skips the current iteration when the number is even and starts the next iteration.
UNIT-II
Data Types

Mutable vs immutable data type: Mutable or immutable is the fancy word for explaining the property of
data types of being able to get updated after being initialized. The basic explanation is thus: A mutable object is
one whose internal state is changeable. On the contrary, once an immutable object in Python has been created,
we cannot change it in any way.

What are Mutable Data Types?

Anything is said to be mutable when anything can be modified or changed. The term "mutable" in Python refers
to an object's capacity to modify its values. These are frequently the things that hold a data collection.

What are Immutable Data Types?

Immutable refers to a state in which no change can occur over time. A Python object is referred to as immutable
if we cannot change its value over time. The value of these Python objects is fixed once they are made.

Numbers - Introduction to Numbers: Numbers in Python refer to the numeric data types in Python
programming. Python supports three kinds of numeric data types: int, float, and complex.

Integers:
In Python, integers are zero, positive or negative whole numbers without a fractional part and having
unlimited precision, e.g. 0, 100, -10. The followings are valid integer literals in Python.
#integer variables
x=0
print(x)

x = 100
print(x)

x = -10
print(x)

x = 1234567890
print(x)

x = 5000000000000000000000000000000000000000000000000000000
print(x)

Output

0
100
-10
1234567890
5000000000000000000000000000000000000000000000000000000

Float:
In Python, floating point numbers (float) are positive and negative real numbers with a fractional part
denoted by the decimal symbol. e.g. 1234.56, 3.142, -1.55, 0.23.

f = 1.2
print(f) #output: 1.2
print(type(f)) #output: <class 'float'>

f=123_42.222_013 #output: 12342.222013


print(f)

Complex Numbers: A complex number is a number with real and imaginary components. For
example, 5 + 6j is a complex number where 5 is the real component and 6 multiplied by j is an imaginary
component.

a = 5+2j
print(a)
print(type(a))

(5+2j)
<class 'complex'>
Built-in Functions: Python provides a lot of built-in functions that ease the writing of code.
Function Name Description

Python abs() Function Return the absolute value of a number

It takes an asynchronous iterable as an argument and returns an asynchronous


Python aiter() Function iterator for that iterable

Return true if all the elements of a given iterable( List, Dictionary, Tuple, set,
Python all() Function etc) are True else it returns False

Returns true if any of the elements of a given iterable( List, Dictionary, Tuple,
Python any() Function set, etc) are True else it returns False

Python anext() Function used for getting the next item from an asynchronous iterator

Python ascii() Function Returns a string containing a printable representation of an object

Python bin() Function Convert integer to a binary string

Python bool() Function Return or convert a value to a Boolean value i.e., True or False

Python breakpoint() It is used for dropping into the debugger at the call site during runtime for
Function debugging purposes

Python bytearray() Returns a byte array object which is an array of given bytes
Function

Converts an object to an immutable byte-represented object of a given size and


Python bytes() Function data

Python callable() Returns True if the object passed appears to be callable


Function

Python chr() Function Returns a string representing a character whose Unicode code point is an integer
Function Name Description

Python classmethod() Returns a class method for a given function


Function

Python compile() Returns a Python code object


Function

Python complex() Creates Complex Number


Function

Python delattr() Function Delete the named attribute from the object

Python dict() Function Creates a Python Dictionary

Python dir() Function Returns a list of the attributes and methods of any object

Python divmod() Takes two numbers and returns a pair of numbers consisting of their quotient
Function and remainder

Python enumerate() Adds a counter to an iterable and returns it in a form of enumerating object
Function

Parses the expression passed to it and runs Python expression(code) within the
Python eval() Function program

Python exec() Function Used for the dynamic execution of the program

Filters the given sequence with the help of a function that tests each element in
Python filter() Function the sequence to be true or not

Python float() Function Return a floating-point number from a number or a string

Python format() Formats a specified value


Function
Function Name Description

Python frozenset() Returns immutable frozenset


Function

Python getattr() Function Access the attribute value of an object

Python globals() Returns the dictionary of the current global symbol table
Function

Python hasattr() Check if an object has the given named attribute and return true if present
Function

Python hash() Function Encode the data into an unrecognizable value

Python help() Function Display the documentation of modules, functions, classes, keywords, etc

Python hex() Function Convert an integer number into its corresponding hexadecimal form

Python id() Function Return the identity of an object

Python input() Function Take input from the user as a string

Python int() Function Converts a number in a given base to decimal

Python isinstance() Checks if the objects belong to a certain class or not


Function

Python issubclass() Check if a class is a subclass of another class or not


Function

Python iter() Function Convert an iterable to an iterator

Python len() Function Returns the length of the object


Function Name Description

Python list() Function Creates a list in Python

Python locals() Function Returns the dictionary of the current local symbol table

Returns a map object(which is an iterator) of the results after applying the given
Python map() Function function to each item of a given iterable

Python max() Function Returns the largest item in an iterable or the largest of two or more arguments

Python memoryview() Returns memory view of an argument


Function

Python min() Function Returns the smallest item in an iterable or the smallest of two or more arguments

Python next() Function Receives the next item from the iterator

Python object() Function Returns a new object

Python oct() Function returns an octal representation of an integer in a string format.

Python open() Function Open a file and return its object

Python ord() Function Returns the Unicode equivalence of the passed argument

Python pow() Function Compute the power of a number

Python print() Function Print output to the console

Python property() Create a property of a class


Function
Function Name Description

Python range() Function Generate a sequence of numbers

Python repr() Function Return the printable version of the object

Python reversed() Returns an iterator that accesses the given sequence in the reverse order
Function

Python round() Function Rounds off to the given number of digits and returns the floating-point number

Convert any of the iterable to a sequence of iterable elements with distinct


Python set() Function elements

Python setattr() Function Assign the object attribute its value

Python slice() Function Returns a slice object

Returns a list with the elements in a sorted manner, without modifying the
Python sorted() Function original sequence

Python staticmethod() Converts a message into the static message


Function

Python str() Function Returns the string version of the object

Python sum() Function Sums up the numbers in the list

Python super() Function Returns a temporary object of the superclass

Python tuple() Function Creates a tuple in Python

Python type() Function Returns the type of the object


Function Name Description

Python vars() Function Returns the __dict__ attribute for a module, class, instance, or any other object

Python zip() Function Maps the similar index of multiple containers

Python __import__() Imports the module during runtime


Function

Related Modules: Python Module is a file that contains built-in functions, classes, its and variables. There
are many Python modules, each with its specific work.

help("modules")------------ to know available list of modules.

Syntax to Import Module in Python


import module

# importing sqrt() and factorial from the


# module math
from math import sqrt, factorial

# if we simply do "import math", then


# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))

Output:
4.0
720

Import all Names


The * symbol used with the import statement is used to import all the names from a module to a current
namespace.

Syntax:
from module_name import *

# importing sqrt() and factorial from the


# module math
from math import *

# if we simply do "import math", then


# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))

Output:
4.0
720

Sequences: Sequences are an object type in Python that allows the user to store data one after each other.
Operations can be performed on a sequence, to examine and manipulated the stored items. There are several
different types of sequence objects in Python; those are 1. Strings 2. Lists 3. Tuples 4. Dictionaries 5. Set
Types.

1. Strings: A String is a data structure in Python that represents a sequence of characters. It is an immutable
data type, meaning that once we have created a string, we cannot change it. Strings are used widely in many
different applications, such as storing and manipulating text data, representing names, addresses, and other
types of data that can be represented as text.

Creating a String in Python


Strings in Python can be created using single quotes or double quotes or even triple quotes. Let us see how we
can define a string in Python.

Example:
In this example, we will demonstrate different ways to create a Python String. We will create a string using
single quotes (‘ ‘), double quotes (” “), and triple double quotes (“”” “””). The triple quotes can be used to
declare multiline strings in Python.

Index and Slice Strings in Python


Indexing means referring to an element of an iterable by its position within the iterable. Each of a string’s
characters corresponds to an index number and each character can be accessed using its index number. We can
access characters in a String in Two ways :
1. Accessing Characters by Positive Index Number
2. Accessing Characters by Negative Index Number

1. Accessing Characters by Positive Index Number: In this type of Indexing, we pass a Positive index(which
we want to access) in square brackets. The index number starts from index number 0 (which denotes the first
character of a string).

2. Accessing Characters by Negative Index Number: In this type of Indexing, we pass the Negative
index(which we want to access) in square brackets. Here the index number starts from index number -1 (which
denotes the last character of a string)
# declaring the string
str = "GEEKSFORGEEKS"

# accessing the character of str at 0th index


print(str[0])

# accessing the character of str at 6th index


print(str[6])

# accessing the character of str at 10th index


print(str[10])

Output

# declaring the string


str = "GEEKSFORGEEKS"

# accessing the character of str at last index


print(str[-1])

# # accessing the character of str at 5th index from the last


print(str[-5])

# # accessing the character of str at 10th index from the last


print(str[-13])

Output

Slicing

Slicing in Python is a feature that enables accessing parts of the sequence.

Syntax :
string[start : end : step]
start : We provide the starting index.
end : We provide the end index(this is not included in substring).
step : It is an optional argument that determines the increment between each index for slicing.
# declaring the string
str ="GEEKSFORGEEKS"

# slicing using indexing sequence


print(str[: 3])
print(str[1 : 5 : 2])
print(str[-1 : -12 : -2])

Output

GEE

EK

SEGOSE

# declaring the string


str ="GEEKSFORGEEKS"

print("GEEKSFORGEEKS:-")
print(str)

# reversing the string using slicing


print("Reverse String :-")
print(str[: : -1])

Output

GEEKSFORGEEKS:-
GEEKSFORGEEKS
Reverse String :-
SKEEGROFSKEEG

1. string="abcdefgh"
len(string)

2. string[0]
'a'

3. string[7]
'h'

4. string[8]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[46], line 1
----> 1 string[8]

IndexError: string index out of range

5. string[0:4]
'abcd'

6. string[3:4]
'd'

7. string[:4]
'abcd'

8. string[5:4]
''

9. string[5:]
'fgh'

10. string[:-1]
'abcdefg'

11. string[:-4]
'abcd'

12. [Link] ('f','g') ------------- it will not replace original string.


'abcdeggh'

Modify Strings:
Upper Case
a = "Hello, World!"
print([Link]())----------------HELLO, WORLD!

Lower Case
a = "Hello, World!"
print([Link]())----------------hello, world!

Remove Whitespace

Whitespace is the space before and/or after the actual text, and very often we want to remove this space.

Example

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


print([Link]()) # returns "Hello, World!"
Replace String
Example

The replace() method replaces a string with another string:

a = "Hello, World!"
print([Link]("H", "J"))--------------------- Jello, World!

Split String

The split() method returns a list where the text between the specified separator becomes the list items.

Example

The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']

String Concatenation

To concatenate, or combine, two strings we can use the + operator.

Example

Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c=a+b
print(c)----------- HelloWorld

Example

To add a space between them, add a " ":

a = "Hello"
b = "World"
c=a+""+b
print(c)------------ Hello World

Format – Strings
we cannot combine strings and numbers like this:

age = 36
txt = "My name is John, I am " + age
print(txt)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[12], line 2
1 age = 36
----> 2 txt = "My name is John, I am " + age
3 print(txt)

TypeError: can only concatenate str (not "int") to str

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places them in the string where the
placeholders {} are:

Example

Use the format() method to insert numbers into strings:

age = 36
txt = "My name is John, and I am {}"
print([Link](age))---------------------------- My name is John, and I am 36

2. Lists: Python Lists are just like dynamically sized arrays, declared in other languages .list is a collection
of things, enclosed in [ ] and separated by commas. Simply a sequence of mutable objects.
Lists are used to store multiple items in a single variable.
# Create a List:

thislist = ["apple", "banana", "cherry"]

print(thislist)--------------- ['apple', 'banana', 'cherry']

List Items

List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order will not change.
If we add new items to a list, the new items will be placed at the end of the list.

Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example

Lists allow duplicate values:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)------------------- ['apple', 'banana', 'cherry', 'apple', 'cherry']

List Length

To determine how many items a list has, use the len() function:

Example

Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))-----------3

List Items - Data Types

A list can contain different data types:

Example

A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]


list1----------------- ['abc', 34, True, 40, 'male']

Access Items

List items are indexed and we can access them by referring to the index number:

Example

Print the second item of the list:

thislist = ["apple", "banana", "cherry"]


print(thislist[1])----------- banana

Range of Indexes
We can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example

Return the third, fourth, and fifth item:

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[2:5])--------------- ['cherry', 'orange', 'kiwi']

By leaving out the start value, the range will start at the first item:

Example

This example returns the items from the beginning to, but NOT including, "kiwi":

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]


print(thislist[:4])------------- ['apple', 'banana', 'cherry', 'orange']

Check if Item Exists

To determine if a specified item is present in a list use the in keyword:

Example

Check if "apple" is present in the list:

thislist = ["apple", "banana", "cherry"]


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")------------- Yes, 'apple' is in the fruits list

Change Item Value

To change the value of a specific item, refer to the index number:

Example

Change the second item:

thislist = ["apple", "banana", "cherry"]


thislist[1] = "blackcurrant"
print(thislist)-------------- ['apple', 'blackcurrant', 'cherry']

Change a Range of Item Values

To change the value of items within a specific range, define a list with the new values, and refer to the range of
index numbers where we want to insert the new values:

Example

Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)-------------- ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']

If we insert more items than we replace, the new items will be inserted where we specified, and the remaining
items will move accordingly:

Example

Change the second value by replacing it with two new values:

thislist = ["apple", "banana", "cherry"]


thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)------------------------ ['apple', 'blackcurrant', 'watermelon', 'cherry']

If we insert less items than we replace, the new items will be inserted where we specified, and the remaining
items will move accordingly:

Example

Change the second and third value by replacing it with one value:

thislist = ["apple", "banana", "cherry"]


thislist[1:3] = ["watermelon"]
print(thislist)---------- ['apple', 'watermelon']

Insert Items
To insert a new list item, without replacing any of the existing values, we can use the insert() method.
The insert() method inserts an item at the specified index:

Example

Insert "watermelon" as the third item:

thislist = ["apple", "banana", "cherry"]


[Link](2, "watermelon")
print(thislist)------------- ['apple', 'banana', 'watermelon', 'cherry']

Append Items
To add an item to the end of the list, use the append() method:
Example

Using the append() method to append an item:

thislist = ["apple", "banana", "cherry"]


[Link]("orange")
print(thislist)------------- ['apple', 'banana', 'cherry', 'orange']
insert Items
To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index:

Example

Insert an item as the second position:

thislist = ["apple", "banana", "cherry"]


[Link](1, "orange")
print(thislist)-------------- ['apple', 'orange', 'banana', 'cherry']

Remove Specified Item

The remove() method removes the specified item.

Example

Remove "banana":

thislist = ["apple", "banana", "cherry"]


[Link]("banana")
print(thislist)---------------- ['apple', 'cherry']

If there are more than one item with the specified value, the remove() method removes the first occurance:

Example

Remove the first occurance of "banana":

thislist = ["apple", "banana", "cherry", "banana", "kiwi"]


[Link]("banana")
print(thislist)----------------- ['apple', 'cherry', 'banana', 'kiwi']

Remove Specified Index

The pop() method removes the specified index.

Example

Remove the second item:

thislist = ["apple", "banana", "cherry"]


[Link](1)
print(thislist)-------------- ['apple', 'cherry']
If we do not specify the index, the pop() method removes the last item.

Example

Remove the last item:

thislist = ["apple", "banana", "cherry"]


[Link]()
print(thislist)-------- ['apple', 'banana']

3. Tuples: Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered
and unchangeable. Tuples are written with round brackets.

thistuple = ("apple", "banana", "cherry")


print(thistuple)-------------------------- ('apple', 'banana', 'cherry')

Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that order will not
change.

Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.

Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example

Tuples allow duplicate values:

thistuple = ("apple", "banana", "cherry", "apple", "cherry")


print(thistuple)-------------- ('apple', 'banana', 'cherry', 'apple', 'cherry')

Tuple Length
To determine how many items a tuple has, use the len() function:
Example

Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))------3
Tuple Items - Data Types
Tuple items can be of any data type:
Example

String, int and boolean data types:

tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

('apple', 'banana', 'cherry')


(1, 5, 7, 9, 3)
(True, False, False)

Access Tuple Items


We can access tuple items by referring to the index number, inside square brackets:
Example

Print the second item in the tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1])------------ banana

Range of Indexes
We can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example

Return the third, fourth, and fifth item:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[2:5])------------- ('cherry', 'orange', 'kiwi')

Example

This example returns the items from the beginning to, but NOT included, "kiwi":

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[:4])-------------- ('apple', 'banana', 'cherry', 'orange')

By leaving out the end value, the range will go on to the end of the tuple:

Example

This example returns the items from "cherry" and to the end:

thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")


print(thistuple[2:])------------------ ('cherry', 'orange', 'kiwi', 'melon', 'mango')
Check if Item Exists
To determine if a specified item is present in a tuple use the in keyword:
Example

Check if "apple" is present in the tuple:

thistuple = ("apple", "banana", "cherry")


if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")----------- Yes, 'apple' is in the fruits tuple

Change Tuple Values


Once a tuple is created, we cannot change its values. Tuples are unchangeable, or immutable as it also is
called.
But there is a workaround. We can convert the tuple into a list, change the list, and convert the list back into a
tuple.
Example

Convert the tuple into a list to be able to change it:

x = ("apple", "banana", "cherry")


y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)-------------------- ('apple', 'kiwi', 'cherry')

Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are other ways to add items
to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, we can convert it into a list, add wer
item(s), and convert it back into a tuple.
Example

Convert the tuple into a list, add "orange", and convert it back into a tuple:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
[Link]("orange")
thistuple = tuple(y)--------- ('apple', 'banana', 'cherry', 'orange')

2. Add tuple to a tuple. We are allowed to add tuples to tuples, so if we want to add one item, (or many), create
a new tuple with the item(s), and add it to the existing tuple:
Example

Create a new tuple with the value "orange", and add that tuple:

thistuple = ("apple", "banana", "cherry")


y = ("orange",)
thistuple += y

print(thistuple)--------------- ('apple', 'banana', 'cherry', 'orange')

Remove Items

Note: We cannot remove items in a tuple.

Tuples are unchangeable, so we cannot remove items from it, but we can use the same workaround as we used
for changing and adding tuple items:

Example

Convert the tuple into a list, remove "apple", and convert it back into a tuple:

thistuple = ("apple", "banana", "cherry")


y = list(thistuple)
[Link]("apple")
thistuple = tuple(y)------------ ('banana', 'cherry')

Or we can delete the tuple completely:

Example

The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[19], line 3
1 thistuple = ("apple", "banana", "cherry")
2 del thistuple
----> 3 print(thistuple) #this will raise an error because the tuple no longer exists

NameError: name 'thistuple' is not defined


Using Asterisk*

If the number of variables is less than the number of values, we can add an * to the variable name and the values
will be assigned to the variable as a list:

Example

Assign the rest of the values as a list called "red":

fruits = ("apple", "banana", "cherry", "strawberry", "raspberry")

(green, yellow, *red) = fruits

print(green)
print(yellow)
print(red)

apple
banana
['cherry', 'strawberry', 'raspberry']

If the asterisk is added to another variable name than the last, Python will assign values to the variable until the
number of values left matches the number of variables left.

Example

Add a list of values the "tropic" variable:

fruits = ("apple", "mango", "papaya", "pineapple", "cherry")

(green, *tropic, red) = fruits

print(green)
print(tropic)
print(red)

apple
['mango', 'papaya', 'pineapple']
cherry

Join Two Tuples

To join two or more tuples we can use the + operator:

Example

Join two tuples:


tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)---------- ('a', 'b', 'c', 1, 2, 3)

4. Dictionaries: Dictionaries are used to store data values in key: value pairs. A dictionary is a collection
which is ordered, changeable and do not allow duplicates. Dictionaries are mutable objects.

Dictionaries are written with curly brackets, and have keys and values:

Example

Create and print a dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)----------- {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Dictionary Items

Dictionary items are ordered, changeable, and does not allow duplicates.

Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

Example

Print the "brand" value of the dictionary:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])--------- Ford

Ordered
When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not
change.

Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been
created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
Example

Duplicate values will overwrite existing values:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)---------------- {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Dictionary Items - Data Types


The values in dictionary items can be of any data type:
Example

String, int, boolean, and list data types:

thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

{'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}

Accessing Items
We can access the items of a dictionary by referring to its key name, inside square brackets:
Example

Get the value of the "model" key:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]------------- 'Mustang'

There is also a method called get() that will give we the same result:

Example

Get the value of the "model" key:

x = [Link]("model")------------ 'Mustang'
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example

Get a list of the keys:

x = [Link]()----------dict_keys(['brand', 'model', 'year'])

Change Values
We can change the value of a specific item by referring to its key name:
Example

Change the "year" to 2018:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018--------------- {'brand': 'Ford', 'model': 'Mustang', 'year': 2018}

Update Dictionary
The update() method will update the dictionary with the items from the given [Link] argument must be a
dictionary, or an iterable object with key:value pairs.
Example

Update the "year" of the car by using the update() method:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"year": 2020})----------------- {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}

Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)---------------- {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Removing Items
There are several methods to remove items from a dictionary:
Example

The pop() method removes the item with the specified key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)-------------------- {'brand': 'Ford', 'year': 1964}

Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
Example
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}

{'child1': {'name': 'Emil', 'year': 2004},


'child2': {'name': 'Tobias', 'year': 2007},
'child3': {'name': 'Linus', 'year': 2011}}

5. Set Types: Sets are used to store multiple items in a single variable.

Set items are unchangeable, but we can remove items and add new items.

Sets are written with curly brackets.

ExampleCreate a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)-------------------------- {'apple', 'cherry', 'banana'}
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered
Unordered means that the items in a set do not have a defined order. Set items can appear in a different order
every time we use them, and cannot be referred to by index or key.

Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been created. Once a set
is created, we cannot change its items, but we can remove items and add new items.

Duplicates Not Allowed


Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)-------------------------------- {'apple', 'cherry', 'banana'}

The values True and 1 are considered the same value in sets, and are treated as duplicates:

Example
True and 1 is considered the same value:

thisset = {"apple", "banana", "cherry", True, 1, 2}


print(thisset)------------------------------- {True, 2, 'apple', 'cherry', 'banana'}

The values False and 0 are considered the same value in sets, and are treated as duplicates:
Example
False and 0 is considered the same value:

thisset = {"apple", "banana", "cherry", False, True, 0}


print(thisset)---------------------------- {False, True, 'apple', 'cherry', 'banana'}

Set Items - Data Types


Set items can be of any data type:

Example
String, int and boolean data types:

set1 = {"apple", "banana", "cherry"}------------------ {'apple', 'cherry', 'banana'}


set2 = {1, 5, 7, 9, 3}-------------------------------------- {1, 3, 5, 7, 9}
set3 = {True, False, False}------------------------------ {False, True}

Access Items
We cannot access items in a set by referring to an index or a key.
But we can loop through the set items using a for loop, or ask if a specified value is present in a set, by using
the in keyword.
Example
Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}


for x in thisset:
print(x)

apple
cherry
banana

Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)---------------- True

Add Items
Once a set is created, we cannot change its items, but we can add new [Link] add one item to a set use
the add() method.
Example

Add an item to a set, using the add() method:

thisset = {"apple", "banana", "cherry"}


[Link]("orange")
print(thisset)----------------------- {'apple', 'cherry', 'banana', 'orange'}

Add Sets
To add items from another set into the current set, use the update() method.

Example
Add elements from tropical into thisset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
[Link](tropical)
print(thisset)------------------------- {'papaya', 'apple', 'cherry', 'banana', 'pineapple', 'mango'}

Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example
Remove "banana" by using the remove() method:

thisset = {"apple", "banana", "cherry"}


[Link]("banana")
print(thisset)---------------------------- {'apple', 'cherry'}

We can also use the pop() method to remove an item, but this method will remove a random item, so we cannot
be sure what item that gets removed.

The return value of the pop() method is the removed item.


Example
Remove a random item by using the pop() method:
thisset = {"apple", "banana", "cherry"}
x = [Link]()
print(x)------------------------- apple
print(thisset)------------------ {'cherry', 'banana'}

Sets are unordered, so when using the pop() method, we do not know which item that gets removed.

Example
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)---------------------- set()

Example
The del keyword will delete the set completely:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[24], line 3
1 thisset = {"apple", "banana", "cherry"}
2 del thisset
----> 3 print(thisset)

NameError: name 'thisset' is not defined

Join Two Sets


There are several ways to join two or more sets in Python. We can use the union() method that returns a new set
containing all items from both sets, or the update() method that inserts all the items from one set into another:

Example
The union() method returns a new set with all items from both sets:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}
set3 = [Link](set2)
print(set3)-------------------------- {'a', 1, 2, 3, 'c', 'b'}
UNIT-III
Functions
Python Functions: A function is a block of code that performs a specific task. Suppose we need to create a
program to make a circle and color it. We can create two functions to solve this problem:
1. function to create a circle
2. function to color the shape
Dividing a complex problem into smaller chunks makes our program easy to understand and reuse.
Some Benefits of Using Functions
 Increase Code Readability
 Increase Code Reusability

Python Function Declaration:


Create a Function
Let's create our first function.

def greet():
print('Hello World!')

Here are the different parts of the program:

Here, we have created a simple function named greet() that prints Hello World!

Note: When writing a function, pay attention to indentation, which are the spaces at the start of a code line.
In the above code, the print() statement is indented to show it's part of the function body, distinguishing the
function's definition from its body.

Calling a Function:
In the above example, we have declared a function named greet().
def greet():
print('Hello World!')

If we run the above code, we won't get an output. It’s because creating a function doesn't mean we are executing
the code inside it. It means the code is there for us to use if we want to. To use this function, we need to call the
function.

Function Call

greet()

Example: Python Function Call


def greet():
print('Hello World!')

# call the function


greet()

print('Outside function')
Output

Hello World!
Outside function

In the above example, we have created a function named greet(). Here's how the control of the program flows:

Here,
1. When the function greet() is called, the program's control transfers to the function definition.
2. All the code inside the function is executed.
3. The control of the program jumps to the next statement after the function call.

Types of Functions in Python:


 Built-in library function: These are Standard functions in Python that are available to use.
 User-defined function: We can create our own functions based on our requirements.
Python Function with Parameters
Parameters or Arguments are inputs given to the function.
def greet(name):
print("Hello", name)

# pass argument
greet("John")

Sample Output 1

Hello John

Here, we passed 'John' as an argument to the greet() function. We can pass different arguments in each call,
making the function re-usable and dynamic. Let's call the function with a different argument.

greet("David")

Sample Output 2

Hello David

Example: Function to Add Two Numbers


# function with two arguments
def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ", sum)

# function call with two values


add_numbers(5, 4)

Output

Sum: 9

In the above example, we have created a function named add_numbers() with arguments: num1 and num2.
The return Statement

We return a value from the function using the return statement.


# function definition
def find_square(num):
result = num * num
return result

# function call
square = find_square(3)

print('Square:', square)
Output

Square: 9

In the above example, we have created a function named find_square(). The function accepts a number and
returns the square of the number.

Note: The return statement also denotes that the function has ended. Any code after return is not executed.

Function Argument with Default Values

In Python, we can provide default values to function arguments.


We use the = operator to provide default values. For example,
def add_numbers( a = 7, b = 8):
sum = a + b
print('Sum:', sum)

# function call with two arguments


add_numbers(2, 3)

# function call with one argument


add_numbers(a = 2)

# function call with no arguments


add_numbers()
Run Code

Output

Sum: 5
Sum: 10
Sum: 15

In the above example, notice the function definition

def add_numbers(a = 7, b = 8):


...

Here, we have provided default values 7 and 8 for parameters a and b respectively. Here's how this program
works

1. add_number(2, 3)
Both values are passed during the function call. Hence, these values are used instead of the default values.

2. add_number(2)
Only one value is passed during the function call. So, according to the positional argument 2 is assigned to
argument a, and the default value is used for parameter b.

3. add_number()
No value is passed during the function call. Hence, default value is used for both parameters a and b.

Python Function with Arbitrary Arguments


Sometimes, we do not know in advance the number of arguments that will be passed into a function. To handle
this kind of situation, we can use arbitrary arguments in Python. Arbitrary arguments allow us to pass a varying
number of values during a function call. We use an asterisk (*) before the parameter name to denote this kind of
argument. For example,
# program to find sum of multiple numbers

def find_sum(*numbers):
result = 0

for num in numbers:


result = result + num

print("Sum = ", result)


# function call with 3 arguments
find_sum(1, 2, 3)

# function call with 2 arguments


find_sum(4, 9)

Output

Sum = 6
Sum = 13

In the above example, we have created the function find_sum() that accepts arbitrary arguments. Notice the
lines,

find_sum(1, 2, 3)

find_sum(4, 9)

Here, we are able to call the same function with different arguments.

Note: After getting multiple values, numbers behave as an array so we are able to use the for loop to access
each value.

Python Recursion
Recursion is the process of defining something in terms of itself. A physical world example would be to place
two parallel mirrors facing each other. Any object in between them would be reflected recursively.

Python Recursive Function


In Python, we know that a function can call other functions. It is even possible for the function to call itself.
These types of construct are termed as recursive functions. The following image shows the working of a
recursive function called recurse.

Following is an example of a recursive function to find the factorial of an integer. Factorial of a number is the
product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!)
is 1*2*3*4*5*6 = 720.

Example of a recursive function


def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))
Run Code
Output

The factorial of 3 is 6

In the above example, factorial() is a recursive function as it calls itself. When we call this function with a
positive integer, it will recursively call itself by decreasing the number. Each function multiplies the number
with the factorial of the number below it until it is equal to one. This recursive call can be explained in the
following steps.

factorial(3) # 1st call with 3


3 * factorial(2) # 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call
6 # return from 1st call

Let's look at an image that shows a step-by-step process of what is going on:
Our recursion ends when the number reduces to 1. This is called the base condition. Every recursive function
must have a base condition that stops the recursion or else the function calls itself infinitely. The Python
interpreter limits the depths of recursion to help avoid infinite recursions, resulting in stack overflows.

Python Lambda/Anonymous Function


A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.

lambda : print('Hello World')

Here, we have created a lambda function that prints 'Hello World'.

Python Lambda Function Declaration


We use the lambda keyword instead of def to create a lambda function. Here's the syntax to declare the lambda
function:

lambda argument(s) : expression

Here,
 argument(s) - any value passed to the lambda function
 expression - expression is executed and returned
Let's see an example,

greet = lambda : print('Hello World')

Here, we have defined a lambda function and assigned it to the variable named greet.
To execute this lambda function, we need to call it. Here's how we can call the lambda function

# call the lambda


greet()

The lambda function above simply prints the text 'Hello World'.

Note: This lambda function doesn't have any arguments.

Example: Python Lambda Function


# declare a lambda function
greet = lambda : print('Hello World')

# call lambda function


greet()
# Output: Hello World
In the above example, we have defined a lambda function and assigned it to the greet variable.
When we call the lambda function, the print() statement inside the lambda function is executed.

Python lambda Function with an Argument


Similar to normal functions, a lambda function can also accept arguments. For example,
# lambda that accepts one argument
greet_user = lambda name : print('Hey there,', name)

# lambda call
greet_user('Delilah')

# Output: Hey there, Delilah


In the above example, we have assigned a lambda function to the greet_user variable.
Here, name after the lambda keyword specifies that the lambda function accepts the argument named name.
Notice the call of the lambda function,

greet_user('Delilah')

Here, we have passed a string value 'Delilah' to our lambda function.


Finally, the statement inside the lambda function is executed.

File Handling: Files are named locations on disk to store related information. They are used to permanently
store data in a non-volatile memory (e.g. hard disk). Since Random Access Memory (RAM) is volatile (which
loses its data when the computer is turned off), we use files for future use of the data by permanently storing
them. When we want to read from or write to a file, we need to open it first. When we are done, it needs to be
closed so that the resources that are tied with the file are freed. Hence, in Python, a file operation takes place in
the following order:

1) Open a file

2) Read or write (perform operation)

3) Close the file

Opening a file: The key function for working with files in Python is the open() function. The open() function
takes two parameters; filename, and mode.
Syntax:-file object = open(<file-name>, <access-mode>)

There are four different methods (modes) for opening a file:


"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
To open a file for reading it is enough to specify the name of the file:
f = open("[Link]")

The code above is the same as:


f = open("[Link]", "rt")

Because "r" for read, and "t" for text are the default values, you do not need to specify them.

Note: Make sure the file exists, or else you will get an error.

Modes of file:

1) r : It opens the file to read-only mode. The file pointer exists at the beginning. The file is by default open in
this mode if no access mode is passed.

2) rb: It opens the file to read-only in binary format. The file pointer exists at the beginning of the file.

3) r+ : It opens the file to read and write both. The file pointer exists at the beginning of the file.

4) rb+: It opens the file to read and write both in binary format. The file pointer exists at the beginning of the
file.

5) w: It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file
exists with the same name. The file pointer exists at the beginning of the file.

6) wb: It opens the file to write only in binary format. It overwrites the file if it exists previously or creates a
new one if no file exists. The file pointer exists at the beginning of the file.

7) w+: It opens the file to write and read both. It is different from r+ in the sense that it overwrites the previous
file if one exists where as r+ doesn't overwrite the previously written file. It creates a new file if no file exists.
The file pointer exists at the beginning of the file.

8) wb+: It opens the file to write and read both in binary format. The file pointer exists at the beginning of the
file.

9) a: It opens the file in the append mode. The file pointer exists at the end of the previously written file if exists
any. It creates a new file if no file exists with the same name.

10) ab: It opens the file in the append mode in binary format. The pointer exists at the end of the previously
written file. It creates a new file in binary format if no file exists with the same name.

11) a+: It opens a file to append and read both. The file pointer remains at the end of the file if a file exists. It
creates a new file if no file exists with the same name.

12) ab+: It opens a file to append and read both in binary format. The file pointer remains at the end of the file.

Open a File on the Server

Assume we have the following file, located in the same folder as Python:

[Link]
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!

To open the file, use the built-in open() function.

The open() function returns a file object, which has a read() method for reading the content of the file:

Example
f = open("[Link]", "r")
print([Link]())

If the file is located in a different location, you will have to specify the file path, like this:

Example

Open a file on a different location:

f = open("D:\\myfiles\[Link]", "r")
print([Link]())

Read Only Parts of the File

By default the read() method returns the whole text, but you can also specify how many characters you want to
return:

Example

Return the 5 first characters of the file:

f = open("[Link]", "r")
print([Link](5))

Read Lines

You can return one line by using the readline() method:

Example
Read one line of the file:
f = open("[Link]", "r")
print([Link]())

By calling readline() two times, you can read the two first lines:

Example

Read two lines of the file:


f = open("[Link]", "r")
print([Link]())
print([Link]())

By looping through the lines of the file, you can read the whole file, line by line:

Example

Loop through the file line by line:

f = open("[Link]", "r")
for x in f:
print(x)

Close Files

It is a good practice to always close the file when you are done with it.

Example

Close the file when you are finish with it:

f = open("[Link]", "r")
print([Link]())
[Link]()

Writing to Files in Python:-


Write to an Existing File

To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content

Example
Open the file "[Link]" and append content to the file:
f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()

#open and read the file after the appending:


f = open("[Link]", "r")
print([Link]())

Example
Open the file "[Link]" and overwrite the content:
f = open("[Link]", "w")
[Link]("Woops! I have deleted the content!")
[Link]()
#open and read the file after the overwriting:
f = open("[Link]", "r")
print([Link]())

Note: the "w" method will overwrite the entire file.

Create a New File


To create a new file in Python, use the open() method, with one of the following parameters:

"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist

Example
Create a file called "[Link]":

f = open("[Link]", "x")
Result: a new empty file is created!

Example
Create a new file if it does not exist:
f = open("[Link]", "w")
Unit – IV
Modules

Modules and Files: In Python, modules are simply files with a .py extension that contain Python code. They
can be imported into other Python programs using the import statement.

For example, the following code imports the math module:


import math
This allows us to use the functions defined in the math module, such as sqrt() and sin().
Modules can also contain variables and classes.

There are two types of modules in Python:

 Built-in modules: These modules are included with the Python interpreter. They provide a variety of functions
and classes that we can use in our programs.
 User-defined modules: These modules are created by Python programmers. They can be used to share code
with other Python programmers or to organize our own code.

We can import built-in modules using the import statement. For example, the following code imports the math
module:
import math

We can import user-defined modules using the import statement. For example, the following code imports the
my_module module:
import my_module

We can also import specific functions and classes from modules using the from statement. For example, the
following code imports the sqrt() function from the math module:
from math import sqrt

This allows us to use the sqrt() function without having to prefix it with the math module name.
We can also import all of the functions and classes from a module using the import * statement. However, this
is not recommended, as it can make our code difficult to read and maintain.
Modules are a powerful tool that can help us to write more organized and reusable Python code.

Namespaces: A namespace is a system that has a unique name for each and every object in Python. An
object might be a variable or a method. Python itself maintains a namespace in the form of a Python
dictionary.
Types of namespaces: When Python interpreter runs solely without any user-defined modules, methods,
classes, etc. Some functions like print(), id() are always present, these are built-in namespaces. When a user
creates a module, a global namespace gets created, later the creation of local functions creates the local
namespace. The built-in namespace encompasses the global namespace and the global namespace
encompasses the local namespace.
A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends; the lifetime of
that namespace comes to an end. Hence, it is not possible to access the inner namespace’s objects from an
outer namespace.

Built-in namespace

• The built-in namespace contains the names of all of Python’s built-in objects. These are available at all
times when Python is running.

• You can list the objects in the built-in namespace with the following command

Ex:

>>> dir(__builtins__)

The Python interpreter creates the built-in namespace when it starts up. This namespace remains in existence
until the interpreter terminates.

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException','BlockingIOError', 'BrokenPipeError',


'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis',
'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError',
'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError',
'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError',
'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration',
'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True',
'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError',
'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_',
'__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__',
'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex',
'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format',
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len',
'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
'type', 'vars', 'zip']

Global namespace

• The global namespace contains any names defined at the level of the main program. Python creates the
global namespace when the main program body starts, and it remains in existence until the interpreter
terminates.

• Strictly speaking, this may not be the only global namespace that exists. The interpreter also creates a
global namespace for any module that your program loads with the import statement.

The Local and Enclosing Namespaces

• The interpreter creates a new namespace whenever a function executes. That namespace is local to the
function and remains in existence until the function terminates.
• Functions don’t exist independently from one another only at the level of the main program. You can
also define one function inside another

Importing Modules: To make use of the functions in a module, we need to import the module with
an import statement. An import statement is made up of the import keyword along with the name of the module.

import random

When we import a module, we are making it available to us in our current program as a separate namespace.
This means that we will have to refer to the function in dot notation, as in [module].[function].

In practice, with the example of the random module, this may look like a function such as:

 [Link]() which calls the function to return a random integer, or


 [Link]() which calls the function to return a random element from a specified range.

Let’s create a for loop to show how we will call a function of the random module within program:
import random

for i in range(10):
print([Link](1, 25))

This small program first imports the random module on the first line, then moves into a for loop which will be
working with 10 elements. Within the loop, the program will print a random integer within the range of 1
through 25 (inclusive). The integers 1 and 25 are passed to [Link]() as its parameters.

When we run the program, we’ll receive 10 random integers as output. Because these are random you’ll likely
get different integers each time you run the program, but they’ll generate something like this:
Output
6
9
1
14
3
22
10
1
15
9

The integers should never go below 1 or above 25.

If you would like to use functions from more than one module, you can do so by adding
multiple import statements:
import random
import math
To make use of our additional module, we can add the constant pi from math to our program, and decrease the
number of random integers printed out:
import random
import math

for i in range(5):
print([Link](1, 25))
print([Link])

Now, when we run our program, we’ll receive output that looks like this, with an approximation of pi as our last
line of output:

Output
18
10
7
13
10
3.141592653589793

The import statement allows you to import one or more modules into your Python program, letting you make
use of the definitions constructed in those modules.

Using from … import


To refer to items from a module within your program’s namespace, you can use the from … import statement.
When you import modules this way, you can refer to the functions by name rather than through dot notation

In this construction, you can specify which definitions to reference directly.

In other programs, you may see the import statement take in references to everything defined within the module
by using an asterisk (*) as a wildcard, but this is discouraged. Let’s first review at importing one specific
function, randint() from the random module:

from random import randint

Here, we first call the from keyword, then random for the module. Next, we use the import keyword and call the
specific function we would like to use.

Now, when we implement this function within our program, we will no longer write the function in dot notation
as [Link]() but instead will only write randint():

from random import randint

for i in range(10):
print(randint(1, 25))

When you run the program, you’ll receive output similar to what we received earlier.

Using the from … import construction allows us to reference the defined elements of a module within our
program’s namespace, letting us avoid dot notation.
Python Module Attributes: name, doc, file, dict
Python module has its attributes that describes it. Attributes perform some tasks or contain some information
about the module. Some of the important attributes are explained below:

__name__ Attribute
The __name__ attribute returns the name of the module. By default, the name of the file (excluding the
extension .py) is the value of __name__attribute.

Example: __name__ Attribute


import math
print(math.__name__) #'math'

In the same way, it gives the name of your custom module e.g. calc module will return 'calc'.

Example: __name__ Attribute


import calc
print(calc.__name__) #'calc'

However, this can be modified by assigning different strings to this attribute. Change [Link] as shown
below.

Example: Set __name__


def SayHello(name):
print ("Hi {}! How are you?".format(name))
__name__="SayHello"
And check the __name__ attribute now.

Example: Set __name__


import hello
print(hello.__name__) #'SayHello'

Module Built-in Functions:


As we know that the Python interactive shell has a number of built-in functions. As a shell start, these functions
are loaded automatically and are always available, such as, print() and input() for I/O, Number conversion
functions such as int(), float(), complex(), Data type conversions such as list(), tuple(), set(), etc.

• In addition to these many built-in functions, there are also a large number of pre-defined functions
available as a part of libraries bundled with Python distributions. These functions are defined in modules
which are known as built-in modules.
• These built-in modules are written in C language and integrated with the Python shell.
• To display a list of all of the available modules in Python Programming Language, we can use the
following command in the Python console:
help('modules')
• Math Module
• Statistics Module

Working with Math Module of Python: most popular mathematical functions that are defined in the math
module include,

 Trigonometric functions
 Representation functions
 Logarithmic functions
 Angle conversion functions, etc.

In addition, two mathematical constants- pi and e are also defined in this module.

In Mathematics, Pi is a well-known mathematical constant. Its value is 3.141592653589793.

>>> import math

>>>[Link]

3.141592653589793

Another well-known mathematical constant is e, which is known as Euler’s number. Its value
equals 2.718281828459045.

Ex:

>>> import math

>>>math.e

2.718281828459045

Trigonometric Ratios For calculating various trigonometric ratios for a given angle, the math module contains
several functions. The trigonometric functions such as sin, cos, tan, etc. take the angle argument in radians,
While we are used to express the angle in degrees.

In the math module, we have two angle conversion functions that help us to convert the angle from degrees to
radians and vice versa.

degrees()

radians()

For Example,

In this example, we will be converting the angle of 30 degrees to radians and then back again to the degree.

>>> import math

>>>[Link](30)

0.5235987755982988
>>>[Link](8.90)

509.9324376664327

In this example, we will find the value of sin, cos, and tan ratios for the angle of 30 degrees which in radians is
equal to 0.5235987755982988 radians.

>>> import math

>>>[Link](0.5235987755982988)

0.49999999999999994

>>>[Link](0.5235987755982988)

0.8660254037844387

>>>[Link](0.5235987755982988)

0.5773502691896257

Many more functions of the math module such as

[Link](),

math.log10()

[Link]()

[Link]()

[Link]()

[Link]()

[Link]() etc.

Working with Statistics Module of Python: The statistics module provides functions to mathematical
statistics of numeric data. Some of the popular statistical functions are defined in this module are as follows:

 Mean
 Median
 Mode
 Standard Deviation
Mean

The mean() method returns the arithmetic mean of the numbers present in a list.

For Example,

>>> import statistics

>>>statistics . mean([2,5,6,9])

5.5

Median

The median() method returns the middle value of numeric data present in a list.

For Example,

>>> import statistics

>>>[Link]([1,2,3,7,8,9])

5.0

>>>[Link]([1,2,3,8,9])

3.0

Mode

The mode() method returns the most common data point present in the list.

For Example,

>>> import statistics

>>>statistics . mode([2,5,3,2,8,3,9,4,2,5,6])

Standard Deviation

The stdev() method returns the standard deviation on a given sample in the form of a list.

For Example,

>>> import statistics

>>>statistics . stdev ([1,1.5,2,2.5,3,3.5,4,4.5,5])

1.3693063937629153
Packages: We usually organize our files in different folders and subfolders based on some criteria, so that
they can be managed easily and efficiently. For example, we keep all our games in a Games folder and we
can even subcategorize according to the genre of the game or something like this. The same analogy is
followed by the packages in Python.

What is a Python Package?


Python modules may contain several classes, functions, variables, etc. whereas Python packages contain
several modules. In simpler terms, Package in Python is a folder that contains various modules as files.

Every package in Python must contain an __init__.py file since it identifies the folder as a package. It generally
contains the initialization code but may also be left empty. A possible hierarchical representation of the shifting
items package in the first example can be given below. Here, shifting items is our main package. We further
divide this into three sub packages: books, CDs and toys. Each package and subpackage contains the
mandatory __init__.py file. Further, the sub packages contain files based on their utility. Books contain two
files [Link] and non_fiction.py, the package CDs contain [Link] and [Link], and the package toys contain
soft_toys.py and [Link].
Below is the folder structure of the python package.

calculator

|
|
|------ __init__.py
|
|
|------ [Link]
| |
| |---------- add()
|
|
|------ [Link]
| |
| |---------- sub()
|
|
|------ [Link]
| |
| |---------- mul()
|
|
|------ [Link]
|
|---------- div()

How to Create a Python Package?


Following the below simple steps you can create your own python packages.
 Choose a name for your package and create a directory with that name.
 Create an [Link] file in the package directory. This file can be empty, but it signals to Python that this directory
should be considered a package.
 Create one or more Python modules (i.e., .py files) in the package directory, containing the functions and
classes you want to include in your package.

Now, let’s see how we can create a python package using the above steps. We will create a calculator package
with modules addition, subtraction, multiplication, and division. Now, let’s create all these modules.

[Link]
def add(a,b):
return a+b

[Link]
def sub(a,b):
return a-b

[Link]
def mul(a,b):
return a*b

[Link]
def div(a,b):
return a/b
How to Import Modules from the Python Packages.
We can import modules from the python packages using import and from keyword and using . operator. The
syntax to import the module from the python packages is given below.

Syntax:
Import package_name.mudule_name

Example: Program to import modules from the package


In this example, we will import the module from the package, and then we will use the functions of that python
package.

Code:
from calculator import addition
from calculator import subtraction
from calculator import multiplication
from calculator import division

print("Addition of 8 and 4 is:", [Link](8, 4))


print("Subtraction of 7 and 2 is:", [Link](7, 2))
print("Multiplication of 3 and 4 is:", [Link](3, 4))
print("Division of 12 and 3 is:", [Link](12, 3))

Output:
Addition of 8 and 4 is: 12
Subtraction of 7 and 2 is: 5
Multiplication of 3 and 4 is: 12
Division of 12 and 3 is: 4.0

Other Features of Modules:


Some of the advantages while working with modules in Python is as follows:

Reusability
Working with modules makes the code reusable.

Simplicity
The module focuses on a small proportion of the problem, rather than focusing on the entire problem.

Scoping
A separate namespace is defined by a module that helps to avoid collisions between identifiers.
Unit – V
Classes in Python

Principles of Object Orientation: In Python, object-oriented Programming (OOPs) is a programming


paradigm that uses objects and classes in programming. It aims to implement real-world entities like
inheritance, polymorphisms, encapsulation, etc. in the programming. The main concept of OOPs is to bind the
data and the functions that work on that together as a single unit so that no other part of the code can access
this data.
Inheritance
Creating Classes:
A class is a collection of objects or you can say it is a blueprint of objects defining the common attributes and
behavior. Now the question arises, how do you do that?
Class is defined under a “Class” Keyword

Class Definition Syntax:


class ClassName:
# Statement-1
.
.
.
# Statement-N

class computer:
def config(self):
print("i5, 12 gb Ram, 1 Tb")

# Creating instances (objects)


com1=computer()
com2=computer()

# Accessing attributes and calling methods


[Link]()------------------------------------------ i5, 12 gb Ram, 1 Tb
[Link]()------------------------------------------ i5, 12 gb Ram, 1 Tb
The Init_Method: The init() function is used to initialize the [Link] init() function is called
automatically every time whenever object is created. This is called as constructor.

class computer:
def __init__(self):
print("KKR")

def config(self):
print("i5, 12 gb Ram, 1 Tb")

# Creating instances (objects)


com1=computer()-------------------------------------KKR
com2=computer()-------------------------------------KKR

# Accessing attributes and calling methods


[Link]()------------------------------------------ i5, 12 gb Ram, 1 Tb
[Link]()------------------------------------------ i5, 12 gb Ram, 1 Tb

class computer:
def __init__(self,cpu,ram):
[Link]=cpu
[Link]=ram

def config(self):
print("config is ", [Link],[Link])

# Creating instances (objects)


com1=computer("I5","16")
com2=computer("I7","8")

# Accessing attributes and calling methods


[Link]()-------------------------------------config is I5 16
[Link]()-----------------------------------config is I7 8

class Dog:
def __init__(self, name, breed):
[Link] = name
[Link] = breed

def bark(self):
print("Dog name & breed is ", [Link],[Link])

# Creating objects (instances) of the Dog class


dog1 = Dog("Buddy", "Golden Retriever")
dog2 = Dog("Max", "German Shepherd")

# Accessing attributes and calling methods


[Link]()----------Dog name & breed is Buddy Golden Retriever
[Link]()----------Dog name & breed is Max German Shepherd
Constructor and self in Python:

class Dog:
def __init__(self):
[Link] = "Buddy Golden"
[Link] = "Max"

# Creating objects (instances) of the Dog class


dog1 = Dog()
dog2 = Dog()

# Accessing attributes and calling methods


print([Link])------------------------------------ Buddy Golden
print([Link]) ----------------------------------- Buddy Golden

class Dog:
def __init__(self):
[Link] = "Buddy Golden"
[Link] = "Max"

# Creating objects (instances) of the Dog class


dog1 = Dog()
dog2 = Dog()
[Link]="Tom"

# Accessing attributes and calling methods


print([Link]) ----------------------------------- Tom
print([Link]) ----------------------------------- Buddy Golden

Types of Python Variables: In oops there are two variables


1. Class Variable
2. Instance Variable

class Dog:
def __init__(self):
[Link] = "Buddy Golden"
[Link] = "Max"

# Creating objects (instances) of the Dog class


dog1 = Dog()
dog2 = Dog()

# Accessing attributes and calling methods


print([Link],[Link]) ------------------------------------ Buddy Golden Max
print([Link],[Link]) ------------------------------------ Buddy Golden Max
class Dog:
def __init__(self):
[Link] = "Buddy Golden"
[Link] = "Max"

# Creating objects (instances) of the Dog class


dog1 = Dog()
dog2 = Dog()
[Link]="Tom"

# # Accessing attributes and calling methods


print([Link],[Link]) ------------------------------------ Tom Max
print([Link],[Link]) ------------------------------------ Buddy Golden Max

Class and Instance Variables:

class Dog:
bark="Woof" # Class Variable
def __init__(self):
[Link] = "Buddy Golden" # Instance Variable
[Link] = "Max" # Instance Variable

# Creating objects (instances) of the Dog class


dog1 = Dog()
dog2 = Dog()
[Link]="Tom"

# # Accessing attributes and calling methods


print([Link],[Link],[Link])-------------- Tom Max Woof
print([Link],[Link],[Link])-------------- Buddy Golden Max Woof

class Dog:
bark="Woof" # Class Variable
def __init__(self):
[Link] = "Buddy Golden" # Instance Variable
[Link] = "Max" # Instance Variable

# Creating objects (instances) of the Dog class


dog1 = Dog()
dog2 = Dog()
[Link]="Tom"
[Link]="Bow Bow"

# # Accessing attributes and calling methods


print([Link],[Link],[Link])----------------------------- Tom Max Bow Bow
print([Link],[Link],[Link])----------------------------- Buddy Golden Max Woof
Types of Methods: Three methods 1. Instance Methods 2. Class Methods 3. Statics Methods

1. Instance Methods
class student:
College="AITAM"
def __init__(self, m1,m2,m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3

def avg(self):# Avg is called as insatnce methods because it's working with instance variables
return (self.m1+self.m2+self.m3)/3

s1=student(10,20,10)
s2=student(20,20,30)

print(s1.m1)
print([Link]())
print([Link]())

Output

10
13.333333333333334
23.333333333333332

2. Class Methods

class Student: # Class names are typically capitalized


College = "AITAM"

def __init__(self, m1, m2, m3):


self.m1 = m1
self.m2 = m2
self.m3 = m3

def avg(self): # This is an instance method


return (self.m1 + self.m2 + self.m3) / 3

@classmethod #In Python, decorators are a powerful and flexible way to modify
# or enhance the behavior of functions or methods without changing their source code

def info(cls):
return [Link]

s1 = Student(10, 20, 30)


s2 = Student(20, 20, 30)

print([Link]())
print([Link]())
print([Link]())
Output

20.0
23.333333333333332
AITAM

3. Statics Methods

class Student:
College = "AITAM" # Class variable

def __init__(self, m1, m2, m3):


self.m1 = m1 # Instance variable
self.m2 = m2 # Instance variable
self.m3 = m3 # Instance variable

def avg(self): # Instance method


return (self.m1 + self.m2 + self.m3) / 3

@classmethod
def college_info(cls): # Class method
return [Link]

@staticmethod
def display_info(): # Static method
print("Aitam Student")

# Create instances of the Student class


s1 = Student(10, 20, 30)
s2 = Student(20, 20, 30)

# Calculate and print the average for s1 and s2


print([Link]())
print([Link]())

# Call the class method college_info() to get the college name


print(Student.college_info())

# Call the static method display_info() directly


Student.display_info()

Output

20.0
23.333333333333332
AITAM
Aitam Student
Inner Class: Inner classes are classes that are defined inside other classes.

class Human:
def __init__(self):
[Link] = 'John'
[Link] = [Link]()

class Head:
def talk(self):
return 'talking...'

# Create an instance of the Human class


Inst = Human()

# Access and print the attributes of the instance


print([Link]) # Output: John
print([Link]()) # Output: talking...

Inheritance: Inheritance it allows us to create a new class by inheriting attributes and methods from an existing
class.
1. Single Inheritance:

class A:
def case1(self):
print("case 1 is working")

def case2(self):
print("case 2 is working")

class B(A):
def case3(self):
print("case 3 is working")

def case4(self):
print("case 4 is working")

# Create instances of the classes


s1 = A()
s2 = B()
# Call methods on s1 (an instance of class A)
s1.case1() # Calls the method from class A
s1.case2() # Calls the method from class A

# Call methods on s2 (an instance of class B)


s2.case1() # Calls the method from class A (inherited by class B)
s2.case2() # Calls the method from class A (inherited by class B)
s2.case3() # Calls the method from class B

Output
case 1 is working
case 2 is working
case 1 is working
case 2 is working
case 3 is working

2. Multiple Inheritances:

class A:
def case1(self):
print("case 1 is working")

def case2(self):
print("case 2 is working")

class B:
def case3(self):
print("case 3 is working")

def case4(self):
print("case 4 is working")
class C(A,B):
def case5(self):
print("case 5 is working")

def case6(self):
print("case 6 is working")

# Create instances of the classes


s1 = A()
s2 = B()
s3 = C()

# Call methods on s1 (an instance of class A)


s1.case1() # Calls the method from class A
s1.case2() # Calls the method from class A

# Call methods on s2 (an instance of class B)


s2.case3() # Calls the method from class B
s2.case4() # Calls the method from class B

# Call methods on s3 (an instance of class C)


s3.case5() # Calls the method from class C
s3.case3() # Calls the method from class B
s3.case2() # Calls the method from class A (inherited by class C)

Output

case 1 is working
case 2 is working
case 3 is working
case 4 is working
case 5 is working
case 3 is working
case 2 is working

3. Multilevel Inheritance:
class A:
def case1(self):
print("case 1 is working")

def case2(self):
print("case 2 is working")

class B(A):
def case3(self):
print("case 3 is working")

def case4(self):
print("case 4 is working")

class C(B):
def case5(self):
print("case 5 is working")

def case6(self):
print("case 6 is working")

# Create instances of the classes


s1 = A()
s2 = B()
s3 = C()

# Call methods on s1 (an instance of class A)


s1.case1() # Calls the method from class A
s1.case2() # Calls the method from class A

# Call methods on s2 (an instance of class B)


s2.case1() # Calls the method from class A (inherited by class B)
s2.case3() # Calls the method from class B

# Call methods on s3 (an instance of class C)


s3.case5() # Calls the method from class C
s3.case3() # Calls the method from class B
s3.case2() # Calls the method from class A (inherited by class C)

Output

case 1 is working
case 2 is working
case 1 is working
case 3 is working
case 5 is working
case 3 is working
case 2 is working
4. Hierarchal Inheritance:

class A:
def case1(self):
print("case 1 is working")

def case2(self):
print("case 2 is working")

class B(A):
def case3(self):
print("case 3 is working")

def case4(self):
print("case 4 is working")

class C(A):
def case5(self):
print("case 5 is working")

def case6(self):
print("case 6 is working")

class D(A):
def case7(self):
print("case 7 is working")

def case8(self):
print("case 8 is working")

# Create instances of the classes


s1 = A()
s2 = B()
s3 = C()
s4= D()
# Call methods on s1 (an instance of class A)
s1.case1() # Calls the method from class A
s1.case2() # Calls the method from class A

# Call methods on s2 (an instance of class B)


s2.case1() # Calls the method from class A (inherited by class B)
s2.case3() # Calls the method from class B

# Call methods on s3 (an instance of class C)


s3.case5() # Calls the method from class C
s3.case2() # Calls the method from class A (inherited by class C)

# Call methods on s4 (an instance of class D)


s4.case7() # Calls the method from class D
s4.case2() # Calls the method from class A (inherited by class D)

Output

case 1 is working
case 2 is working
case 1 is working
case 3 is working
case 5 is working
case 2 is working
case 7 is working
case 2 is working

5. Hybrid Inheritance:
class A:
def case1(self):
print("case 1 is working")

def case2(self):
print("case 2 is working")

class B(A):
def case3(self):
print("case 3 is working")

def case4(self):
print("case 4 is working")

class C(A):
def case5(self):
print("case 5 is working")

def case6(self):
print("case 6 is working")

class D(A):
def case7(self):
print("case 7 is working")

def case8(self):
print("case 8 is working")

class E(B,D):
def case9(self):
print("case 9 is working")

def case10(self):
print("case 10 is working")
# Create instances of the classes
s1 = A()
s2 = B()
s3 = C()
s4= D()
s5= E()

# Call methods on s1 (an instance of class A)


s1.case1() # Calls the method from class A
s1.case2() # Calls the method from class A

# Call methods on s2 (an instance of class B)


s2.case1() # Calls the method from class A (inherited by class B)
s2.case3() # Calls the method from class B

# Call methods on s3 (an instance of class C)


s3.case5() # Calls the method from class C
s3.case2() # Calls the method from class A (inherited by class C)
# Call methods on s4 (an instance of class D)
s4.case7() # Calls the method from class D
s4.case2() # Calls the method from class A (inherited by class D)

# Call methods on s5 (an instance of class E)


s5.case9() # Calls the method from class E
s5.case2() # Calls the method from class A (inherited by class E)
s5.case3() # Calls the method from class B (inherited by class E)
s5.case7() # Calls the method from class D (inherited by class E)

Output
case 1 is working
case 2 is working
case 1 is working
case 3 is working
case 5 is working
case 2 is working
case 7 is working
case 2 is working
case 9 is working
case 2 is working
case 3 is working
case 7 is working

Inheritance Super Function:

class A:

def __init__(self):
print("I am init from A")

def case1(self):
print("case 1 is working")

def case2(self):
print("case 2 is working")

class B(A):

def __init__(self):
super().__init__()
print("I am init from B")

def case3(self):
print("case 3 is working")

def case4(self):
print("case 4 is working")

# Create instances of the classes


s2 = B()

Output

I am init from A
I am init from B

Polymorphism:

We know that the + operator is used extensively in Python programs. But, it does not have a single usage.

For integer data types, + operator is used to perform arithmetic addition operation.

num1 = 1
num2 = 2
print(num1+num2)----------------3

Similarly, for string data types, + operator is used to perform concatenation.

str1 = "Python"
str2 = "Programming"
print(str1+" "+str2)-------------- Python Programming
There are some functions in Python which are compatible to run with multiple data types.
One such function is the len() function. It can run with many data types in Python. Let's look at some example
use cases of the function.

print(len("Programiz"))------------------------------------------------9
print(len(["Python", "Java", "C"]))-----------------------------------3
print(len({"Name": "Luke", "Address": "Nepal"}))----------------2

Here, we can see that many data types such as string, list, tuple, set, and dictionary can work with
the len() function. However, we can see that it returns specific information about specific data types.

class Animal:
def speak(self):
pass

class Dog(Animal):
def speak(self):
return "Woof!"

class Cat(Animal):
def speak(self):
return "Meow!"

def animal_sound(animal):
return [Link]()

dog = Dog()
cat = Cat()

print(animal_sound(dog)) # Output: "Woof!"


print(animal_sound(cat)) # Output: "Meow!"

Polymorphism is the ability of different classes to be treated as objects of a common super class. In this case,
both Dog and Cat are subclasses of Animal. They each override the speak() method defined in the Animal class
with their own implementation. When you call the animal_sound() function with instances of Dog and Cat,
polymorphism allows the correct speak() method associated with each specific subclass to be called, producing
the appropriate sound for each animal.

So, the code exhibits polymorphism because objects of different classes (Dog and Cat) are treated as objects of
their common superclass (Animal) and can be operated on in a uniform manner (animal_sound() function), yet
the specific behavior associated with each subclass is executed.

Overriding and Overloading:

Overriding occurs when two methods have the same method name and parameters. One of the methods is in
the parent class, and the other is in the child class. Overriding allows a child class to provide the specific
implementation of a method that is already present in its parent class.

Overloading occurs when two or more methods in one class have the same method name but different
parameters. Python does not support method overloading .
Overriding

class A:

def case1(self):
print('case 1 is working')

def case2(self):
print('case 2 is working')

class B(A):
# Modified function that is
# already exist in class A
def case1(self):
print('Modified case 1 of class A by class B')

def case3(self):
print('feature_3 of class B')

# Create instance
s1 = B()
# Call the override function
s1.case1()

Output
Modified case 1 of class A by class B

Encapsulation: Encapsulation is used to restrict access of data members and functions in a class.

Access Modifiers in Python encapsulation


Sometimes there might be a need to restrict or limit access to certain variables or functions while programming.
That is where access modifiers come into the picture.

Now when we are talking about access, 3 kinds of access specifiers can be used while performing Encapsulation
in Python. They are as follows :
1. Public Members
2. Private Members
3. Protected Members

Encapsulation in Python using public members

As the name suggests, the public modifier allows variables and functions to be accessible from anywhere within
the class and from any part of the program. All member variables have the access modifier as public by default.

# illustrating public members & public access modifier


class pub_mod:
def __init__(self, name, age):
[Link] = name;
[Link] = age;

def Age(self):
print("name:",[Link],"age:",[Link],)

obj = pub_mod("Jason", 35);


[Link]()

Evidently, from the above code, you can make out that we declared two variables and two methods of the class
pub_mod. We were able to access the variables and methods wherever we wanted with ease as the access
modifier for them was public, which means they should be accessible everywhere.

Encapsulation in Python using private members

The private access modifier allows member methods and variables to be accessed only within the class. To
specify a private access modifier for a member, we make use of the double underscore __.
# illustrating private members & private access modifier
class Rectangle:
__length = 0 #private variable
__breadth = 0#private variable
def __init__(self):
self.__length = 5
self.__breadth = 3
#printing values of the private variable within the class
print(self.__length)
print(self.__breadth)

rect = Rectangle() #object created


#printing values of the private variable outside the class
print([Link])
print([Link])

Output
5
3
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[7], line 14
12 rect = Rectangle() #object created
13 #printing values of the private variable outside the class
---> 14 print([Link])
15 print([Link])

AttributeError: 'Rectangle' object has no attribute 'length'

We can see that we have received an Attribute Error in the output. Well, your thoughts should wander towards
the private access modifier! Since len is a private member and we have tried to access it outside the class that is
why we received the above error.

Encapsulation in Python using protected members

What sets protected members apart from private members is that they allow the members to be accessed within
the class and allow them to be accessed by the sub-classes involved. In Python, we demonstrate a protected
member by prefixing with an underscore _ before its name.

As we know, if the members have a protected access specifier, it can also be referenced then within the class
and the subsequent sub-clas

# illustrating protected members & protected access modifier


class details:
_name="Jason"
_age=35
_job="Developer"
class pro_mod(details):
def __init__(self):
print(self._name)
print(self._age)
print(self._job)

# creating object of the class


obj = pro_mod()
# direct access of protected member
print("Name:",[Link])
print("Age:",[Link])

Output
Jason
35
Developer
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[8], line 15
13 obj = pro_mod()
14 # direct access of protected member
---> 15 print("Name:",[Link])
16 print("Age:",[Link])

AttributeError: 'pro_mod' object has no attribute 'name'

it is quite clear from the output that the class pro_mod was successfully able to inherit the variables from the
class details and print them to the console, although they were protected variables. And when we tried to refer
to them outside of their parent class and the sub-class, we got an Attribute Error for the same.
Regular Expressions

Regular Expressions(Reg Ex): A RegEx, or Regular Expression, is a sequence of characters that forms a
search pattern.
RegEx can be used to check if a string contains the specified search pattern.

RegEx Module
Python has a built-in package called re, which can be used to work with Regular Expressions.

Import the re module:

RegEx in Python

When we have imported the re module, we can start using regular expressions:

Example
Search the string to see if it starts with "The" and ends with "Spain":

Import re

#Check if the string starts with "The" and ends with "Spain":

txt = "The rain in Spain"


x = [Link]("^The.*Spain$", txt)

if x:
print("YES! We have a match!")
else:
print("No match")

YES! We have a match!-------------------------output

RegEx Functions:
The re module offers a set of functions that allows us to search a string for a match:

Function Description

findall Returns a list containing all matches

search Returns a Match object if there is a match anywhere in the string

split Returns a list where the string has been split at each match

sub Replaces one or many matches with a string


Metacharacters:

Metacharacters are characters with a special meaning:


Character Description Example

[] A set of characters "[a-m]"

\ Signals a special sequence (can also be used to escape special characters) "\d"

. Any character (except newline character) "he..o"

^ Starts with "^hello"

$ Ends with "planet$"

* Zero or more occurrences "he.*o"

+ One or more occurrences "he.+o"

? Zero or one occurrences "he.?o"

{} Exactly the specified number of occurrences "he.{2}o"

| Either or "falls|stays"

() Capture and group

Special Sequences:

A special sequence is a \ followed by one of the characters in the list below, and has a special meaning:
Character Description Example

\A Returns a match if the specified characters are at the beginning of the string "\AThe"

\b Returns a match where the specified characters are at the beginning or at the end of a r"\bain"
word
(the "r" in the beginning is making sure that the string is being treated as a "raw r"ain\b"
string")

\B Returns a match where the specified characters are present, but NOT at the beginning r"\Bain"
(or at the end) of a word
(the "r" in the beginning is making sure that the string is being treated as a "raw r"ain\B"
string")

\d Returns a match where the string contains digits (numbers from 0-9) "\d"
\D Returns a match where the string DOES NOT contain digits "\D"

\s Returns a match where the string contains a white space character "\s"

\S Returns a match where the string DOES NOT contain a white space character "\S"

\w Returns a match where the string contains any word characters (characters from a to "\w"
Z, digits from 0-9, and the underscore _ character)

\W Returns a match where the string DOES NOT contain any word characters "\W"

\Z Returns a match if the specified characters are at the end of the string "Spain\Z"

Sets:

A set is a set of characters inside a pair of square brackets [] with a special meaning:
Set Description

[arn] Returns a match where one of the specified characters (a, r, or n) is present

[a-n] Returns a match for any lower case character, alphabetically between a and n

[^arn] Returns a match for any character EXCEPT a, r, and n

[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present

[0-9] Returns a match for any digit between 0 and 9

[0-5][0- Returns a match for any two-digit numbers from 00 and 59


9]

[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR upper case

[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any + character in
the string

The findall() Function:

The findall() function returns a list containing all matches.

Example
Print a list of all matches:

import re
txt = "The rain in Spain"
x = [Link]("ai", txt)
print(x)------------------------------------------------- ['ai', 'ai']

The list contains the matches in the order they are found.
If no matches are found, an empty list is returned:
Example
Return an empty list if no match was found:

import re
txt = "The rain in Spain"
x = [Link]("Portugal", txt)
print(x) )------------------------------------------------- [ ]

The search() Function:


The search() function searches the string for a match, and returns a Match object if there is a match. If there is
more than one match, only the first occurrence of the match will be returned:

Example
Search for the first white-space character in the string:

import re
txt = "The rain in Spain"
x = [Link]("\s", txt)
print("The first white-space character is located in position:", [Link]())-------------The first white-space
character is located in position: 3

If no matches are found, the value None is returned:


Example
Make a search that returns no match:

import re
txt = "The rain in Spain"
x = [Link]("Portugal", txt)
print(x)-------------------------------------------None

The split() Function:


The split() function returns a list where the string has been split at each match:

Example
Split at each white-space character:

import re
txt = "The rain in Spain"
x = [Link]("\s", txt)
print(x)---------------------------- ['The', 'rain', 'in', 'Spain']

We can control the number of occurrences by specifying the maxsplit parameter:


Example
Split the string only at the first occurrence:

import re
txt = "The rain in Spain"
x = [Link]("\s", txt, 1)
print(x)----------------------------- ['The', 'rain in Spain']
The sub() Function:
The sub() function replaces the matches with the text of we choice:

Example
Replace every white-space character with the number 9:
import re

txt = "The rain in Spain"


x = [Link]("\s", "9", txt)
print(x)----------------------------- The9rain9in9Spain

We can control the number of replacements by specifying the count parameter:


Example
Replace the first 2 occurrences:

import re
txt = "The rain in Spain"
x = [Link]("\s", "9", txt, 2)
print(x)-------------------------------- The9rain9in Spain

Match Object:
A Match Object is an object containing information about the search and the result.

Note: If there is no match, the value None will be returned, instead of the Match Object.
Example
Do a search that will return a Match Object:

import re
txt = "The rain in Spain"
x = [Link]("ai", txt)
print(x) #this will print an object--------------------- <[Link] object; span=(5, 7), match='ai'>

The Match object has properties and methods used to retrieve information about the search, and the result:
.span() returns a tuple containing the start-, and end positions of the match.
.string returns the string passed into the function
.group() returns the part of the string where there was a match

Example
Print the position (start- and end-position) of the first match occurrence.
The regular expression looks for any words that starts with an upper case "S":

import re
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link]())------------------------------------(12, 17)

Example
Print the string passed into the function:
import re
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link])----------------------------------- The rain in Spain

Example
Print the part of the string where there was a match.
The regular expression looks for any words that starts with an upper case "S":

import re
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link]())------------------------------------Spain

Note: If there is no match, the value None will be returned, instead of the Match Object.

You might also like