0% found this document useful (0 votes)
2 views98 pages

Python Programming Basics Guide

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)
2 views98 pages

Python Programming Basics Guide

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

Python Programming

ISOEH
Oihik Mitra

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Table of Contents
Introduction to Python Programming Language........................................................................ 3

Basic Python Features ................................................................................................................ 4

If Else ....................................................................................................................................... 22

Loops in Python ....................................................................................................................... 32

List, Tuple, Set , Dictionary ..................................................................................................... 38

Sets ........................................................................................................................................... 46

Functions .................................................................................................................................. 56

OOP Concept ........................................................................................................................... 65

Class and Object ...................................................................................................................... 67

Inheritance................................................................................................................................ 73

File Handling ........................................................................................................................... 87

Different Python Modules........................................................................................................ 92

Assignment .............................................................................................................................. 97

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Introduction to Python Programming Language
Python is a popular programming language. It was created by Guido van Rossum, and released
in 1991.

It is used for:

• web development (server-side),


• software development,
• mathematics,
• system scripting.

Python is also used on a server to create web applications, create workflows, read and modify
files. It is a very powerful language to handle big data and perform complex mathematics.

Why we will use Python?

• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional way.

Why Python is simple and easy to learn?

• Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets for
this purpose.

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Basic Python Features
Python is designed to be easy to read and write. Its syntax emphasizes readability and reduces
the cost of program maintenance. For example, if we want to print “Hello World” in Python,
the syntax will be:

print(“Hello World”)

Comments in Python

Comments are used to explain code and are ignored by the interpreter. They start with a # for
single-line comments or """ for multi-line comments. For example:

# This is a single-line comment

"""
This is a
multi-line comment
"""

Variables
Variables are used to store data values. They are essentially names that reference objects in
memory. For example:

x= 5
y="John"
print(x)
print(y)
Here, x and y are the variables. Variables are case sensitive. For example:
X=10
x=20
print(x)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

The output is 20, because we print ‘x’ and the value of ‘x’ is 20. 10 will not be printed because
the variable is ‘X’.

Type of variables we cannot declare:


a_1var=20
var-id=20
1var=10

We can also declare multiple variables in a single line. For example:


a,b,c = 1,2,3
print(a,b,c)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Data Types

Python supports several built-in data types:

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Dictionary
Set
Boolean Type

Declaring Data Types in python


String
text = "Hello World"

Numeric Types
• int

x=50
print(x)

• float

x = 11.5
print(x)

• complex

x = 1j
print(x)

Sequence Types
• list

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


print(fruits)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


• tuple

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


print(fruits)
• range
x = range(6)
print(x)

Dictionary
cred = {"username" : "john123", "password" : “Password123”}
print(cred)

Set
x = {"apple", "banana", "cherry"}
print(x)

Boolean Type
a = True
b = False
print (a)
print (b)

Checking Datatypes in Python


In python, we can check the data type of a variable. To check datatype in python, we use the
following syntax
a = 50
b = 20.5
c = "Hello"
print(type(a))
print(type(b))
print(type(c))

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

Type casting in python


Type casting in Python refers to converting a variable from one data type to another. Python
provides built-in functions for converting between types. This process is often necessary when
performing operations that require specific data types or when you need to ensure data
compatibility.
Suppose, we want to change a variable from int to float, then the syntax will be:
x = 10
print(x)
print(type(float(x)))

Output:

The datatype of x has been changed to float.

Another way we can do it by creating a new variable. For example:

Let’s change a int variable to string


x=10
y=str(x)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


print(type(y))
print(type(x))

Output:

For y, the datatype is str.


For x, the datatype is int.

User Input in Python


User input refers to the data or commands that a user provides to a program or system. In the
context of programming, user input is the information that a user enters into a program,
typically through an interface like a command line, text box, or graphical user interface (GUI).

In Python, you can get user input using the input() function. This function reads a line from
input (usually from the keyboard) and returns it as a string. Here's a basic example:

name = input("Enter your name: ")


print("The name is",name)

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Note: In python, when we are taking user input, then the default datatype is string. Therefore,
whenever we will use datatype other than string, we need to mention the datatype in the user
input which we are using. Otherwise, python will treat it as string.

For example, we want to take an user input of an integer. Then the syntax will be:

num=int(input("Enter the number:"))


print("The number is",num)

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Operators
Mathematical operators
In Python, mathematical operators are used to perform arithmetic operations on numbers.
There are numerous mathematical operators in python:

Name Sign
Addition +
Subtraction -
Division /
Multiplication *
Reminder %
Exponential **

Addition: It calculates the sum of the numbers.


Subtraction: It calculates the subtraction of the numbers.
Division: It calculates the division of numbers.
Multiplication: It calculates the multiplication of numbers.
Reminder: It calculates the reminder of two numbers.
Exponential: It represents is the power of a number.

a = 10
b=4
c = (a + b)
d = (a - b)
e = (a * b)
f = (a / b)
g = (a % b)
h = (a ** b)
print("The sum is",a)
print("The subtraction is",b)
print("The multiplication is",e)
print("The divition is",d)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


print("The reminder is",g)
print("The exponential is",h)

Output:

Boolean Operators
In Python, boolean operators are used to perform logical operations on boolean values (True
and False). The primary boolean operators are and, or, and not.
• and operator: It will return True, if both conditions are true.

a = True
b = False
c = a and b
print(c)

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


• or: It will return True, if any one of the condition is true.

a = True
b = False
c = a or b
print(c)

Output:

• not: It will return True, if the condition is false.

a = True
b = not a
print(b)

Output:

Boolean operators can also be used in more complex expressions

a = 10
b=5
c=2
d = (a > b) and (b > c)
e = (a < b) or (b > c)
f = not (a == b)
[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091
print(d)
print(e)
print(f)

Logical Operators
In Python, logical operators are used to combine conditional statements. These are primarily
and, or, and not, which are used to perform logical operations.

a = True
b = False

# AND operator
print(a and b)
print(a and not b)

# OR operator
print(a or b)
print(b or b)

# NOT operator

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


print(not a)
print(not b)

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Basic Programs in Python
Now, let’s start with basic programs in Python Programming Language.

1. Adding two numbers

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
sum = num1 + num2
print("Result:",sum)

Output:

2. Calculating the Area of a Circle


radius = float(input("Enter the radius of the circle: "))
pi = 3.141592653589793
area = pi * radius * radius
print("Result:",area)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

3. Simple Calculator

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
sum = num1 + num2
sub = num1 - num2
mul = num1 * num2
div = num1 / num2
rem = num1 % num2
print("Addition:",sum)
print("Subtraction:",sub)
print("Multiplication:",mul)
print("Division:",div)
print("Reminder:",rem)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

String Formatting

String formatting is a method of constructing a string by embedding variable values and


expressions within a string template. It allows you to create dynamic strings that can
incorporate different types of data, such as integers, floating-point numbers, strings, and
more, in a readable and flexible way.

Why Use String Formatting?

• Readability: Makes the code more readable by clearly showing how the string is
constructed.
• Reusability: Templates can be reused with different values.
• Flexibility: Easily format numbers, dates, align text, and more.

String formatting in Python can be done in several ways. The most common methods are:

1. Using the [Link]() Method


name = input("Enter your name: ")
age = int(input("Enter your age: "))
formatted_string = "Hello, {name}. You are {age} years old.".format(name=name,
age=age)
print(formatted_string)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

2. Using f-Strings (Formatted String Literals)

name = input("Enter your name: ")


age = int(input("Enter your age: "))
formatted_string = f"Hello, {name}. You are {age} years old."
print(formatted_string)

Output:

String Slicing

String slicing in Python allows you to extract a portion of a string by specifying a range of
indices. This is useful for accessing and manipulating substrings.

The syntax is:

substring = string[start:stop:step]

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Example 1:

text = "Hello, World!"

substring = text[0:5]

print(substring)

substring = text[7:12]

print(substring)

Output:

In this example:

3. text[0:5] is a slicing operation on the string text.


4. 0 is the starting index (inclusive).
5. 5 is the ending index (exclusive).
6. The slice text[0:5] extracts the substring from index 0 to index 4, which is "Hello".
7. This substring is assigned to the variable substring.
8. print(substring) outputs the value of substring, which is "Hello".
9. text[7:12] is another slicing operation on the string text.
10. 7 is the starting index (inclusive).
11. 12 is the ending index (exclusive).
12. The slice text[7:12] extracts the substring from index 7 to index 11, which is "World".
13. This substring is assigned to the variable substring.
14. print(substring) outputs the value of substring, which is "World".

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Example 2:

str1="Hello World"

print(str1[-1:1:-2])

The slicing notation str1[-1:1:-2] takes a slice of the string str1 starting from the last
character (-1), stopping just before the second character (1), and moving in steps of -2
(i.e., moving backwards by two characters at a time).

Here's the step-by-step process:

1. Start from the last character, which is 'd'.


2. Move two steps backward to 'r'.
3. Move two steps backward to 'o'.
4. Move two steps backward to 'W'.

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


If Else
The if/else statement executes a block of code if a specified condition is true. If the condition
is false, another block of code can be executed. This structure enables the program to make
decisions and respond differently to various inputs or situations, ensuring that specific actions
are taken only when certain criteria are met.

Syntax:

if condition:

true statements

else:

false statements

Example 1: Let’s write a program to check a particular number is even or odd.

var=int(input("Enter number: "))

if var%2==0:

print("The number is even")

else:

print("The number is odd")

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Example 2: Let’s write a program to check a particular number is divisible by 5 or not.

var=int(input("Enter number: "))

if var%5==0:

print("The number is divisible by 5")

else:

print("The number is not divisible by 5")

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Example 3: Let’s write a program to check a particular number is divisible by both 5 and 8
or not.

var=int(input("Enter number: "))

if var%5==0 and var%8==0:

print("The number is divisible by 5 and 8")

else:

print("The number is not divisible by 5 and 8")

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Elif

The elif statement in Python is short for "else if". It is used to check multiple conditions in a
sequence, and it helps to avoid deep nesting of if-else statements. The elif statement allows
you to chain multiple conditions together.

Syntax:

if condition1:

# Block of code to execute if condition1 is true

elif condition2:

# Block of code to execute if condition1 is false and condition2 is true

elif condition3:

# Block of code to execute if condition1 and condition2 are false and condition3 is true

else:

# Block of code to execute if all conditions are false

Example 1:

Let’s make a program determine a person's category based on their age.

age = int(input("Enter your age: "))

if age < 18:

print("Minor")

elif age <= 65:

print("Adult")

else:

print("Senior")

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Example 2: Checking Weekday
var=int(input("Enter character: "))

if var==1:

print ("Sunday")

elif var==2:

print("Monday")

elif var==3:

print("Tuesday")

elif var==4:

print("Wednesday")

elif var==5:

print("Thursday")

elif var==6:

print("Friday")

elif var==7:

print("Saturday")

else:

print("Invalid input")

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

Example 3: Programming a simple calculator


var=int(input("Enter your choice:"))
var1=int(input("Enter 1st number:"))
var2=int(input("Enter 2nd number:"))
if var==1:
print(var1+var2)
elif var==2:
print(var1-var2)
elif var==3:
print(var1*var2)
elif var==4:
print(var1/var2)
else:
print("Invalid Input")

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

Nested IF
A nested if statement is an if statement placed inside another if statement. This allows for
more complex decision-making processes by testing multiple conditions in a hierarchical
manner.

Syntax:
if condition1:
# Block of code to execute if condition1 is true
if condition2:
# Block of code to execute if condition1 and condition2 are true
else:
# Block of code to execute if condition1 is true and condition2 is false
else:
# Block of code to execute if condition1 is false

Example 1
Write a Python program that takes an integer input from the user and determines if the
number is divisible by both 5 and 8, only by 5, only by 8, or by neither.

var=int(input("Enter number:"))

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


if var%5==0:
if var%8==0:
print("The number is divisible by 5 and 8.")
else:
print("The number is divisible by 5 but not 8.")
elif var%8==0:
print("It is only divisible by 8")
else:
print("Not divisible by 5 and 8")

Example 2: Python program to check a particular year is leap year is not.


var=int(input("Enter year:"))
if var%4==0:
if var%100==0:
if var%400==0:
print("Leap year")
else:
print("Not leap year")
else:
print("Leap year")
else:
print("Not leap year")

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Loops in Python
A loop in Python is a construct that allows a block of code to be executed repeatedly. It starts
by initializing a variable or setting up an initial state. Then, it checks a condition to decide
whether the loop should continue. If the condition is met, the code inside the loop runs. After
the code runs, something typically changes, like a variable being updated, which brings the
loop closer to completion. The loop then checks the condition again and repeats this cycle until
the condition is no longer met, at which point the loop stops. This process enables you to
perform repetitive tasks efficiently without writing the same code multiple times.
There are mainly 2 types of loops:

1. For Loop
2. While Loop

For Loop
A for loop in Python is used to iterate over a sequence or any other iterable object, like a list,
tuple, string, or range. It allows you to execute a block of code for each item in the sequence.

When a for loop starts, it picks the first item in the sequence and assigns it to a loop variable.
The code inside the loop is then executed using that variable. After completing the code block,
the loop moves to the next item in the sequence, assigns it to the same loop variable, and the
process repeats. This continues until all items in the sequence have been processed.

For example, if you have a list of numbers, a for loop can go through each number one by one,
allowing you to perform operations on each item in the list. The key idea behind a for loop is
that you know beforehand how many times the loop will run because it's based on the number
of items in the sequence.

Syntax:
for i in range(initialization,end-point,increment/decrement):
statement
Here, i is the loop variable, which will iterate from initialization till end point.
Increment/Decrement means either the loop will go upward(increment) or
backward(decrement).

Note: If we want to end the loop, we have to enter break statement.

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Example 1
Let’s print “Hello World” multiple times using for loop.
Syntax:
for i in range (0,10,1):
print("Hello World")

It will print 10 times, starting from 0, and the increment will be 1.

Output:

Example 2
Counting number backwards till 0
Syntax
num=int(input("Enter number:"))
for var in range(num,0,-1):
print(var)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

Example 3
Counting numbers from 1 till first number divisible by both 5 and 8
Syntax:
for var in range(1,100,1):
print(var)
if var%5==0 and var%8==0:
break

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


While Loop

A while loop is a control flow statement in programming that allows code to be executed
repeatedly based on a given condition. The loop continues to execute as long as the specified
condition remains true. When the condition evaluates to false, the loop stops, and the program
moves on to the next section of code. For example, if you want to perform an action until a
certain condition is met—like counting down from 10 to 1—the while loop is an efficient way
to do this. It keeps looping through the code block until the countdown reaches 1, at which
point the condition becomes false, and the loop ends. This makes the while loop particularly
useful for scenarios where the number of iterations is not predetermined.

Syntax:

while condition:

Code block to execute

Increment/Decrement

Example 1: Counting numbers backwards till 1.

i=int(input("Enter the number: "))

while i>=1:

print(i)

i-=1

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Example 2: Calculate sum of digits, using while loop.

i=int(input("Enter number:"))

sum=0

while i!=0:

r=int(i%10)

sum=sum+r

i=i/10

print(sum)

Output:

Example 3: Find factorization of a given number.

num=int(input("Enter Number: "))

n=1

while num>=1:

n=n*num

num-=1

print(n)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


List, Tuple, Set , Dictionary
List
In Python, a list is an ordered collection of items that can be of different types. Lists are
mutable, meaning you can change their contents after they've been created. Here are some key
points about lists in Python:

1. Creation: Lists are created using square brackets [] with elements separated by commas.
2. Indexing: Elements in a list are indexed, starting from 0 for the first element. You can
access elements using their index.
3. Slicing: You can retrieve a portion of a list using slicing, where you specify a start and
end index.
4. Mutability: Lists are mutable, so you can add, remove, or change elements after the list
has been created.
5. Common Operations:
• Appending: You can add elements to the end of the list.
• Inserting: You can insert elements at a specific position.
• Removing: You can remove elements by value or by index.
• Sorting: Lists can be sorted in place.
• Length: You can find the number of elements in a list using len().
6. Iteration: You can loop through the elements in a list using a for loop.

Lists are versatile and widely used in Python programming for storing and manipulating
collections of items.

Example 1: Let’s display a list of fruits using list in python.

fruits=["apple","mango","watermelon","banana","cherry","apple",1,9.89]

print(fruits)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

Index Slicing in List

fruits=["apple","mango","watermelon","banana","cherry","apple",1,9.89]

print(fruits[0:6:2])

print(fruits[0::-3])

print(fruits[3::-1])

print(fruits[5::-1])

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Changing item in a list.
fruits=["apple","mango","watermelon","banana","cherry","apple",1,9.89]
fruits[5]="graps"
print(fruits)

Output:

List Methods
• .append : Appends an item in the list #list_name.append(“item_name”)
• .insert: Insert an item in any index position #list_name.insert(index,”item_name”)
• .remove: Remove any item from the list # list_name.remove(”item_name”)
• .copy(): Copies items in another list.
• .reverse(): Reverse the order in the list. list_name.reverse()
• .clear(): Clear the values in the list.
• max(): Specifies the maximum number in a list.
• min(): Specifies the minimum number in a list.
• .count(): Specifies the index value of a specific value of a list.
# list_name.count(”item”)
• .isdigit(): that verifies whether all characters in a list are digits or not.

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Print List using For Loop
fruits=["apple","mango","watermelon","banana","cherry","apple",1,9.89]
for i in fruits:
print(i)

Output:

Taking user input in List


fruits=[]
num=int(input("Enter how many elements u wants:"))
for i in range(0,num):
elements=input("Enter elements:")
[Link](elements)
print(fruits)

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Example 2: Copy all the even numbers in another list.
Syntax:
fruits=[]
new_list=[]
num=int(input("Enter how many elements u wants:"))
for i in range(0,num):
elements=input("Enter elements:")
[Link](elements)
print(fruits)
for i in fruits:
if int(i)%2==0:
new_list.append(i)
print(new_list)

Output:

Example 3: Take a list of numbers and determine whether the numbers are prime or not.
Syntax:
list=[]
num = int(input("Enter your limit:-----"))
for i in range(0,num):
elements=input("Enter your numbers:-----")
[Link](elements)
print(list)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


for j in list:
c=0
for k in range(1,int(j)+1):
if int(j)%k==0:
c+=1
if c==2:
print(f"{j}-->prime")
else:
print(f"{j}-->Not prime")

Output:

Example 4: List within a list.


new_list=[]
for i in range(0,2):
new_list.append([])
for j in range(0,3):
new_list[i].append(j)
print(new_list)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

List Comprehension
List comprehension in Python is a concise way to create lists. It allows you to generate a new
list by applying an expression to each item in an existing iterable (like a list or range) and
optionally filtering items based on a condition.
Syntax:
[new_item for item in iterable] #Without Condition
[new_item for item in iterable if condition] #With Condition

Example 5: Write a Python program that allows the user to input a list of elements. Then,
using list comprehension, create a new list containing only those elements from the original
list that are purely numeric (consist only of digits).

li=[]

num=int(input("Enter how many elements u wants:"))

for i in range(0,num):

elements=input("Enter elements:")

[Link](elements)

print(li)

new_list=[var for var in li if [Link]()]

print(new_list)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Sets
In Python, a set is a collection type that is unordered, mutable, and does not allow duplicate
elements. Here's a breakdown of the key features and operations related to sets in Python:

Key Features of Sets

• Unordered: The elements in a set do not have a specific order. When you print a set,
the items may appear in a different order than how they were added.
• Unique Elements: A set cannot have duplicate elements. If you try to add a duplicate
element, it will be ignored.
• Mutable: You can add or remove elements from a set after it is created.
• Heterogeneous: A set can contain elements of different types, such as integers, strings,
or tuples.

You can create a set using curly braces {} or the set() function

Difference between sets and list.

Feature Set List

Order Unordered Ordered

Duplicates No duplicates allowed Duplicates allowed

Mutable Yes Yes

Indexing Not supported Supported

Creation Created using {} or set() Created using [] or list()

Common Union, Intersection, Slicing, Concatenation, Repetition


Operations Difference

Use Case Ideal for unique collections Ideal for ordered collections

Performance Faster for membership Faster for accessing elements by


testing index

Data Types Can store only hashable Can store any type of data
types

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Basic Example:
my_set={1,7,56,34,7,7,45,56}
print(my_set)

Output:

Print set using For loop.


my_set={1,7,56,34,7,7,45,56}
for i in my_set:
print(i)

Output:

Adding an item in a set


my_set={1,7,56,34,7,7,45,56}
my_set.add(99)
print(my_set)

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Checking Maximum and minimum number from a set
my_set={23,45,86,14,2,15,3,4}
print(max(my_set))
print(min(my_set))

Output:

Creating set by user input.


user_set = set()
num_elements = int(input("How many elements do you want to add to the set? "))
for i in range(num_elements):
element = input(f"Enter element {i + 1}: ")
user_set.add(element)
print("The set is:", user_set)

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Removing item from a list.
my_set={20,28,32,45,23,15}
my_set.remove(int(input("Enter Number: ")))
print(my_set)

Output:

Tuple
A tuple in Python is an immutable, ordered collection of elements. Unlike lists, once a tuple is
created, its elements cannot be modified, added, or removed. Tuples are defined using
parentheses () and can contain elements of different data types. They are commonly used when
you want to store a collection of items that should not change throughout the program. Tuples
support indexing, allowing access to elements by their position, and can also be used for
packing and unpacking multiple values. Because of their immutability, tuples are often used as
keys in dictionaries or elements in sets.

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Difference between Set, Tuple and List.

List Tuple Set Dictionary


A list is a non- The set data
A Tuple is also a
homogeneous structure is also A dictionary is
non-homogeneous
data structure a non- also a non-
data structure that
that stores the homogeneous homogeneous data
stores elements in
elements in data structure structure that
columns of a single
columns of a but stores the stores key-value
row or multiple
single row or elements in a pairs.
rows.
multiple rows. single row.
The list can be The set can be The dictionary can
Tuple can be
represented by [ represented by { be represented by
represented by ( )
] } {}
The list allows The Set will not The dictionary
Tuple allows
duplicate allow duplicate doesn’t allow
duplicate elements
elements elements duplicate keys.
The dictionary can
The list can use Tuple can use The set can use
use nested among
nested among all nested among all nested among all
all
Example: {1: “a”,
Example: [1, 2, Example: (1, 2, 3, Example: {1, 2,
2: “b”, 3: “c”, 4:
3, 4, 5] 4, 5) 3, 4, 5}
“d”, 5: “e”}
A list can be Tuple can be A set can be A dictionary can
created using created using created using be created using
the list() function the tuple() function. the set() function the dict() function.
A set is mutable
A tuple is
A list is mutable i.e we can make
immutable i.e we A dictionary is
i.e we can make any changes in
can not make any mutable, its Keys
any changes in the set, its
changes in the are not duplicated.
the list. elements are not
tuple.
duplicated.
Dictionary is
List is ordered Tuple is ordered Set is unordered ordered (Python
3.7 and above)
Creating an Creating an empty Creating an empty
Creating a set
empty list Tuple dictionary
l=[] t=() a=set() d={}
b=set(a)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Basic Syntax

tup=(5,6,7,8,9)

print(tup)

Output:

Example 2: Determine the length of a tuple in python.


tup=(5,6,7,8,9)
print(f"length={len(tup)}")

Output:

Example 3: How to see the value of a specific index number.


my_number=(3,6,7,90,45,23)
print(my_number[5])

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


If we want to use the functions of a list in a tuple. Then we can use type casting.
Let’s say we want to append a value in a tuple. But we can’t do it directly because we can’t
append anything in a tuple. Hence we convert the tuple into a list.
my_number=(3,6,7,90,45,23)
print(my_number)
con=list(my_number)
[Link](900)
my_number=tuple(con)
print(my_number)

Output:

Example 4: Taking user input in a tuple.


my_num=[]
c=0
num=int(input("Enter Limit: "))
for i in range(0,num):
elements=int(input("Enter the elements: "))
my_num.append(elements)
con=tuple((my_num))
print(con)

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Dictionary
A dictionary in Python is a data structure that stores data in key-value pairs, where each unique
key is associated with a specific value. Keys are used to access and manipulate the data.
Dictionaries are defined using curly braces {}, with each key-value pair separated by a colon
‘:’. They are unordered, mutable, and optimized for fast retrieval of values based on their keys.

Example:

my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}

print(my_dict)

Output:

Accessing Values: You can access the value associated with a key using square brackets [].

my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}

print(my_dict['name'])

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Adding/Updating: You can add a new key-value pair or update an existing one by
assigning a value to a key.

my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}

my_dict['job'] = 'Engineer'

my_dict['age'] = 31

print(my_dict)

Output:

Deleting: You can remove a key-value pair using the del keyword.

my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}

del my_dict['city']

print(my_dict)

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Iteration: Print Dictionary using Loop.

my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}

for key in my_dict:

print(key, my_dict[key])

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Functions
In Python, a function is a reusable block of code that performs a specific task. Functions allow
you to organize your code, make it more readable, and avoid repetition.

A function is defined using the def keyword, followed by the function name and parentheses
(). Inside the parentheses, you can specify parameters (inputs) that the function will take. The
function body is indented, and it contains the code that runs when the function is called.

Example

def show():

print("Hello Everyone...!")

show()

Output:

The code defines a function named show using the def keyword. Inside the function, the
print("Hello Everyone...!") statement outputs the string "Hello Everyone...!" when the function
is called. The line show() calls the function, executing the print statement and displaying the
message to the console. This function takes no arguments and simply prints a message every
time it's called.

Example 2: Let’s make a simple calculator using Functions

Syntax:

def addition():

var1=int(input("Enter the 1st number: "))

var2=int(input("Enter the 2nd number: "))

print(var1+var2)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


def subtraction():

var1 = int(input("Enter the 1st number: "))

var2 = int(input("Enter the 2nd number: "))

print(var1 - var2)

def division():

var1 = int(input("Enter the 1st number: "))

var2 = int(input("Enter the 2nd number: "))

print(var1 / var2)

def multiplication():

var1 = int(input("Enter the 1st number: "))

var2 = int(input("Enter the 2nd number: "))

print(var1 * var2)

def reminder():

var1 = int(input("Enter the 1st number: "))

var2 = int(input("Enter the 2nd number"))

print(var1 % var2)

def square():

var1 = int(input("Enter the number: "))

print(var1*var1)

while True:

print("1. Addition")

print("2. Subtraction")

print("3. Division")

print("4. Multiplication")

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


print("5. Reminder")

print("6. Square")

print("Press 0 to exit\n")

num=int(input("Enter your choice:"))

if num==1:

addition()

elif num==2:

subtraction()

elif num==3:

division()

elif num==4:

multiplication()

elif num==5:

reminder()

elif num==6:

square()

elif num==0:

break

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Outputs:

Function Parameter

In Python, function parameters are variables defined in the function signature that allow the
function to accept inputs when called. They enable the function to work with different values
each time it's invoked. Parameters can be positional (passed in order), default (with preset
values), keyword (explicitly named during the call), or variable-length (*args for multiple
positional arguments and **kwargs for multiple keyword arguments). These parameters
provide flexibility, allowing functions to handle various inputs and perform different tasks
based on the arguments passed.

Let’s make the calculator using Function parameter.

Syntax:

def addition(x,y):

print(x+y)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


def subtraction(x,y):

print(x-y)

def division(x,y):

print(x/y)

def multiplication(x,y):

print(x*y)

def reminder(x,y):

print(x%y)

def square(x):

print(x*x)

while True:

print("1. Addition")

print("2. Subtraction")

print("3. Division")

print("4. Multiplication")

print("5. Reminder")

print("6. Square")

num=int(input("Enter your choice:"))

if(num==0):

break

var1=int(input("Enter first number:"))

var2=int(input("Enter second number:"))

if num==1:

addition(var1,var2)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


elif num==2:

subtraction(var1,var2)

elif num==3:

division(var1,var2)

elif num==4:

multiplication(var1,var2)

elif num==5:

reminder(var1,var2)

Output:

Recursive Functions

A recursive function is a function in Python that calls itself in order to solve a problem. It works
by breaking down a complex problem into smaller, more manageable sub-problems, with each
recursive call handling one of those sub-problems. Recursive functions typically have a base
case, which is a condition that stops the recursion, preventing an infinite loop, and a recursive
case, which reduces the problem and calls the function again. Recursion is often used in
problems involving tasks that can be divided into similar sub-tasks, such as calculating
factorials or traversing data structures like trees.

Example 1: Write a Python program to calculate the sum of all natural numbers from 1 to a
given number using recursion. The user should input the number, and the program should
output the sum of numbers from 1 to that input number.

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Syntax:

def sumOfnumber(x):

if x==0:

return 0;

else:

return x+sumOfnumber(x-1)

num=int(input("Enter your range:"))

result=sumOfnumber(num)

print(result)

Output:

Example 2: Find factorial of a number

Syntax:

def factOfnumber(x):

if x==0:

return 1;

else:

return x*factOfnumber(x-1)

num=int(input("Enter the number:"))

result=factOfnumber(num)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


print(result)

Output:

Example 3: Passing a list through function.

Syntax:

def showList(li):

for i in li:

print(i)

my_list=[3,8,9,12,65,"hello"]

showList(my_list)

Output:

Example 2: Find maximum, minimum number and sum of all the numbers in a list.

Syntax:

def maximum(li):

print(f"Maximum number is {max(li)}")

def minimum(li):

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


print(f"Minimum number is {min(li)}")

def sumofnumbers(li):

print(f"Sum is {sum(li)}")

my_list=[]

num=int(input("Enter your range:"))

for i in range(0,num):

elements=int(input("Enter elements:"))

my_list.append(elements)

maximum(my_list)

minimum(my_list)

sumofnumbers(my_list)

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


OOP Concept
Object-Oriented Programming (OOP) in Python is a programming paradigm that organizes
data and behavior into reusable structures called objects. It emphasizes the concepts of classes,
objects, and inheritance. Here’s a detailed explanation of the core OOP concepts in Python:

1. Classes: A class is a blueprint for creating objects. It defines a set of attributes (data)
and methods (functions) that its objects will have. Classes encapsulate data and
functions into a single entity, facilitating code organization and reuse.

2. Objects: An object is an instance of a class. It is created based on the class blueprint


and contains specific data and functionality. Objects represent real-world entities or
abstract concepts in a program, allowing you to work with data and functions in a
modular way.

3. Attributes: Attributes are variables defined within a class. They represent the state or
properties of an object. Attributes can be accessed and modified through methods
defined in the class.

4. Methods: Methods are functions defined within a class that describe the behaviors or
actions that objects of the class can perform. Methods can operate on the attributes of
the object and can be called to perform operations or manipulate the object's state.

5. Inheritance: Inheritance allows one class to inherit attributes and methods from
another class, enabling code reuse and creating a hierarchical relationship between
classes. The class that inherits is called the derived or subclass, and the class being
inherited from is called the base or superclass. Inheritance promotes modularity and
extensibility.

6. Encapsulation: Encapsulation is the concept of bundling data (attributes) and methods


(functions) that operate on the data into a single unit (class). It also involves restricting
access to some of the object's components to protect the integrity of the data. This is
often achieved through access control mechanisms, like public, protected, and private
attributes and methods.

7. Polymorphism: Polymorphism allows different classes to be treated as instances of the


same class through a common interface. It enables methods to be used interchangeably

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


across different classes, even if they are implemented differently. This supports method
overriding and method overloading, allowing flexibility in how methods are called.

8. Abstraction: Abstraction is the concept of hiding the complex implementation details


of an object and exposing only the necessary features. It allows users to interact with
objects through simplified interfaces, making it easier to work with complex systems.

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Class and Object
In Python, classes and objects are fundamental concepts of object-oriented programming
(OOP). A class is like a blueprint for creating objects. It defines a set of attributes and methods
that the created objects (instances) will have. Think of it as a template or a structure. __init__
is the constructor method. It is automatically called when an object is created and is used to
initialize the object's attributes. self refers to the current instance of the class, used to access
attributes and methods. An object is an instance of a class. Once a class is defined, you can
create multiple objects from that class. Each object can have its own attributes, but the methods
are shared.

Syntax:

class Person:

# Constructor method

def __init__(self, name, age):

[Link] = name # Attribute

[Link] = age # Attribute

# Method

def greet(self):

print(f"Hello, my name is {[Link]} and I am {[Link]} years old.")

# Creating an (object) instance of the Person class

person1 = Person("Alice", 30)

# Accessing attributes and methods

print([Link])

print([Link])

[Link]()

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

Here, person1 is an object (instance) of the Person class. The object has its own values for the
name and age attributes but shares the greet method with all other instances of the Person class.

Example 1: Addition of two numbers using class and object.

Syntax:

class addition:

def add_info(self,var1,var2):

[Link]=var1+var2

print(f"The addition is {[Link]}")

obj=addition()

num=int(input("Enter the 1st number:"))

num1=int(input("Enter the 2nd number:"))

obj.add_info(num,num1)

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Method Overloading

Method overloading in Object-Oriented Programming (OOP) refers to the ability to define


multiple methods with the same name but different signatures (i.e., different types or numbers
of parameters). This allows a method to perform different tasks based on the arguments passed
to it. Python does not directly support method overloading like some other languages (such as
Java or C++). However, you can achieve a similar effect using default arguments or by handling
different argument types inside a single method.

Example 1: Addition of numbers using method overloading.

Syntax:
class AddNumbers:

def addition(self, a, b, c=0):

if c == 0:

print(f"Sum of two numbers: {a + b}")

else:

print(f"Sum of three numbers: {a + b + c}")

obj = AddNumbers()

# Test cases

[Link](10, 20)

[Link](10, 20, 30)

Output:

The method addition has three parameters: a, b, and c. The parameter c has a default value of
0. When the method is called with two arguments ([Link](10, 20)), c remains at its default
value of 0, and the program adds a and b. When the method is called with three arguments

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


([Link](10, 20, 30)), the provided value for c overrides the default, and the program adds
a, b, and c.

Example 2: Write a Python class named checkNumbers that includes a method called check.
The check method should be able to compare two or three numbers. If two numbers are passed
to the method, it should print the maximum and minimum of those two numbers. If three
numbers are passed to the method, it should print the maximum and minimum of all three
numbers.

Syntax:

class checkNumbers:

def check(self,a,b,c=0):

if c>0:

print(f" Maximum is {max(a,b,c)}")

print(f" Minimum is {min(a, b, c)}")

else:

print(f" Maximum is {max(a,b)}")

print(f" Minimum is {min(a, b)}")

obj=checkNumbers()

var1 = int(input("Enter first number:"))

var2 = int(input("Enter second number:"))

var3 = int(input("Enter third number:"))

[Link](var1,var2)

[Link](var1,var2,var3)

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

Encapsulation

Encapsulation in Object-Oriented Programming (OOP) is the concept of bundling the data


(attributes) and methods (functions) that operate on the data into a single unit or class.
Encapsulation also restricts direct access to some of the object's components, which can prevent
the accidental modification of data.

Encapsulation helps in:

• Data Protection: By restricting access to the internal representation of an object and


only allowing modification through well-defined methods.
• Control: It ensures that the object's internal data is not accidentally altered, and changes
can only be made in controlled ways.
• Ease of Maintenance: Changes to internal implementation can be made without
affecting how users of the object interact with it.
• Access Modifiers in Python:
• Public: All members of a class (attributes and methods) are public by default and can
be accessed from outside the class.
• Private: By convention, members prefixed with a double underscore (__) are considered
private and cannot be accessed directly from outside the class.
• Protected: Members prefixed with a single underscore (_) are treated as protected. They
are not strictly private but are intended to be used within the class and its subclasses.

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Example:

class Person:

def __init__(self, name, age):

[Link] = name

self.__age = age

def get_age(self):

return self.__age

def set_age(self, age):

if age > 0:

self.__age = age

else:

print("Invalid age!")

person = Person("John", 25)

print([Link])

print(person.get_age())

person.set_age(30)

print(person.get_age())

person.set_age(-5)

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Inheritance
In Python, inheritance is a mechanism where a new class (called a subclass or child class)
derives properties and behaviours (methods and attributes) from an existing class (called a
superclass or parent class). The main idea behind inheritance is code reuse. Instead of writing
code from scratch, a subclass can inherit the functionality of a parent class and extend or modify
it.

In Python, the super() function is used in inheritance to call a method from the parent class in
the child class. It provides a way to access and invoke methods or constructors from a parent
class without referring directly to the parent class by name. This is particularly useful when
working with method overriding or in cases of multiple inheritance.

Types of Inheritance

Single Inheritance: Single-level inheritance in Python refers to a type of inheritance where


a single subclass (child class) inherits properties and behaviours from a single superclass
(parent class). This is the simplest form of inheritance and is mainly used for code reuse and to
add or extend the functionality of the parent class in the child class.

Characteristics:

• There is only one parent class and one child class.


• The child class inherits all the attributes and methods of the parent class.
• The child class can override or extend the methods of the parent class if needed.

Syntax:

class Parent:

def method(self):

print("This is a parent method.")

class Child(Parent):

pass

obj = Child()

[Link]()

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Example 1:

class A:

var=10

def display(self):

print("Hello every one")

class B(A):

def show(self):

print("Kolkata")

obj=B()

[Link]()

[Link]()

print([Link])

Example 2: Addition of two numbers

Syntax:

class A:

def addition(self):

[Link] = int(input("Enter 1st no:"))

self.var1 = int(input("Enter 2nd no:"))

class B(A):

def show(self):

[Link]=[Link]+self.var1

print([Link])

obj=B()

[Link]()

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


[Link]()

Output:

Multilevel Inheritance

Multilevel inheritance in Python is a type of inheritance where a child class inherits from a
parent class, and then another class (grandchild class) inherits from that child class. In this way,
the inheritance chain forms multiple levels, where each class can pass on its attributes and
methods to the next class in the hierarchy.

Characteristics:

Multiple Levels: There are at least three classes involved: a base class, a derived class (child),
and a derived class of that derived class (grandchild).

Inheritance Chain: The grandchild class inherits from the child class, which in turn inherits
from the parent class.

Code Reusability: Each class in the chain can reuse the code from its parent class.

Method Overriding: Any class in the chain can override methods of its parent class.

Example 1: Addition of three numbers

Syntax:

class A:

def userinput(self):

self.var1 = int(input("Enter number:"))

self.var2 = int(input("Enter number:"))

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


class B(A):

def __init__(self):

[Link]()

def display(self):

print(self.var1+self.var2)

class C(B):

def __init__(self):

self.var3=int(input("Enter number:"))

super().__init__()

def show(self):

print(self.var1+self.var2+self.var3)

obj=C()

[Link]()

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Example 2: Multiplication of three numbers

Syntax:

class A:

def __init__(self):

self.var1 = int(input("Enter number:"))

class B(A):

def __init__(self):

self.var2=int(input("Enter number:"))

super().__init__()

class C(B):

def __init__(self):

self.var3=int(input("Enter number:"))

super().__init__()

def show(self):

print(self.var1*self.var2*self.var3)

obj=C()

[Link]()

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Hierarchical inheritance

Hierarchical inheritance in Python occurs when multiple child classes inherit from the same
parent class. This means that one parent class serves as the base for several subclasses, allowing
them to share common functionality while each child class can also have its own unique
methods or attributes.

Characteristics:

1. One Parent Class, Multiple Child Classes: The same parent class is inherited by
multiple subclasses.

2. Code Reusability: The common behaviour is defined in the parent class and shared by
all child classes.

3. Method Overriding: Each child class can override the methods from the parent class, if
necessary.

4. No Inheritance Among Sibling Classes: Child classes inherit only from the parent class,
not from each other.

Example 1: Make a simple calculator using hierarchical inheritance.

Syntax 1:

class A:

def userInput(self):

self.var1=int(input("Enter first number:"))

self.var2=int(input("enter second number:"))

class B(A):

def perform_add(self):

print(f"the addition of {self.var1} and {self.var2} is {self.var1+self.var2}")

class C(A):

def perform_mul(self):

print(f"the multiplication of {self.var1} and {self.var2} is {self.var1*self.var2}")

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


obj1=C()

obj2=B()

while(True):

print("[Link]")

print("[Link]")

print("[Link]")

ch=int(input("Enter your choice:" ))

if ch==1:

[Link]()

obj2.perform_add()

elif ch==2:

[Link]()

obj1.perform_mul()

elif ch==3:

break

else:

print("Invalid input")

Syntax 2:

class A:

def userInput(self):

self.var1=int(input("Enter first number:"))

self.var2=int(input("enter second number:"))

def userinputforsub(self):

self.var1 = int(input("Enter first number:"))

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


self.var2 = int(input("enter second number:"))

return self.var2,self.var1

class B(A):

def perform_add(self):

print(f"the addition of {self.var1} and {self.var2} is {self.var1+self.var2}")

class C(A):

def perform_mul(self):

print(f"the multiplication of {self.var1} and {self.var2} is {self.var1*self.var2}")

class D:

def perform_sub(self):

[Link](self)

print(f"the substraction of {self.var1} and {self.var2} is {self.var1 - self.var2}")

obj3=D()

obj1=C()

obj2=B()

while(True):

print("[Link]")

print("[Link]")

print("[Link]")

print("[Link]")

ch=int(input("Enter your choice:" ))

if ch==1:

[Link]()

obj2.perform_add()

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


elif ch==2:

[Link]()

obj1.perform_mul()

elif ch==3:

obj3.perform_sub()

elif ch==4:

break

else:

print("Invalid input")

Output:

Multiple Inheritance

Multiple inheritance in Python refers to a situation where a class (child class) inherits from
more than one parent class. This allows the child class to inherit attributes and methods from
all of the parent classes. It is different from single inheritance, where a child class can inherit
only from one parent class.

Characteristics:

1. Multiple Parent Classes: A child class can inherit features from more than one parent
class.

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


2. Code Reusability: It enables a class to reuse code from multiple parent classes, which
can help in building complex systems efficiently.

3. Method Resolution Order (MRO): When there are multiple parent classes, Python uses
a system called MRO to determine the order in which methods are inherited. MRO
ensures that the method from the correct class is called when there are methods with
the same name in different parent classes.

Example: We will perform addition by multiple inheritance.

Syntax:

class A:

def userInputvar1(self):

self.var1=int(input("Enter number:"))

class B:

def userInputvar2(self):

A.userInputvar1(self)

self.var2=int(input("Enter number"))

class C(A,B):

def calculateAdd(self):

self.userInputvar2()

print(self.var1+self.var2)

obj=C()

[Link]()

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

Example 2: Make a simple calculator using Multiple Inheritance

Syntax:

class A:

def userInput(self):

self.var1=int(input("Enter first number:"))

self.var2=int(input("enter second number:"))

class B(A):

def perform_add(self):

print(f"the addition of {self.var1} and {self.var2} is {self.var1+self.var2}")

class C(A):

def perform_mul(self):

print(f"the multiplication of {self.var1} and {self.var2} is {self.var1*self.var2}")

class D(B,C):

def perform_sub(self):

[Link]()

print(f"the subtraction of {self.var1} and {self.var2} is {self.var1 - self.var2}")

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


obj1=B()

obj2=C()

obj3=D()

while(True):

print("[Link]")

print("[Link]")

print("[Link]")

print("[Link]")

ch=int(input("Enter your choice:" ))

if ch==1:

[Link]()

obj1.perform_add()

elif ch==2:

[Link]()

obj2.perform_mul()

elif ch==3:

obj3.perform_sub()

elif ch==4:

break

else:

print("Invalid Input")

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Output:

Method Overriding

Method overriding in Python is a feature that allows a subclass (child class) to provide a
specific implementation of a method that is already defined in its superclass (parent class).
When the method in the child class has the same name and parameters as in the parent class,
the child class's method overrides the one in the parent class

Characteristics:

• Same Method Name: The method in the child class must have the same name as the
one in the parent class.
• Same Parameters: The method signature (number and types of parameters) must match
between the parent and child classes.
• New Implementation: The child class provides a new definition for the method,
allowing it to behave differently from the one in the parent class.
• Dynamic Dispatch: At runtime, Python determines which version of the method (parent
or child) to call, based on the type of the object that is calling the method.

Example:

# Parent class

class Animal:

def speak(self):

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


print("Animal makes a sound")

# Child class

class Dog(Animal):

def speak(self): # Overriding the 'speak' method

print("Dog barks")

# Child class

class Cat(Animal):

def speak(self): # Overriding the 'speak' method

print("Cat meows")

# Create objects

dog = Dog()

cat = Cat()

# Call the overridden methods

[Link]() # Output: Dog barks

[Link]() # Output: Cat meows

Parent Class (Animal): Has a method speak() that outputs a generic message "Animal makes a
sound."

Child Classes (Dog and Cat): Both override the speak() method with their own
implementations:

The Dog class provides its own version of speak() that prints "Dog barks." The Cat class
provides its own version of speak() that prints "Cat meows." When calling speak() on dog and
cat objects, the respective overridden methods are executed, even though the parent class
(Animal) also has a speak() method. This allows subclasses to tailor or modify the behavior of
inherited methods to fit their specific needs.

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


File Handling
File handling in Python allows you to perform operations such as creating, opening, reading,
writing, and closing files.

Reading from a file is done using methods like read() (reads the entire file), readline() (reads a
single line), or readlines() (reads all lines into a list). Writing to a file uses write() for single
strings and writelines() for lists of strings. When writing or appending, if the file doesn’t exist,
it is created.

It’s important to close files after operations using close() to free resources. However, the with
statement is recommended as it automatically handles the closing of the file, even in case of
exceptions.

Basic modes of file

'r': Read (default mode). It opens a file for reading. Raises an error if the file doesn’t exist.

'w': Write. Creates a new file or truncates an existing one.

'a': Append. Adds content to the end of the file without truncating it.

In Python, file reading methods like .read(), .readline(), and .readlines() allow you to extract
data from a file in different ways. Here’s an explanation of each:

• read() : Reads the entire file (or a specified number of characters) as a single string.
When you want to read the whole content of a file at once.
• readline(): Reads a single line from the file each time it is called. Useful when
reading files line by line, especially when you don’t want to load the entire file into
memory at once.
• readlines(): Reads all the lines in the file and returns them as a list of strings, where
each string is a line from the file. Ideal for reading all lines of a file and working with
them as a list, where you can iterate or access lines by index.

Example 1: Let’s create a normal file from python

var=open('My_info.txt','w')

[Link]("John Doe\n")

[Link]("I am a student\n")

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


[Link]("I stay at USA")

[Link]()

var=open('My_info.txt','r')

print([Link]())

print([Link]())

print([Link]())

Output:

Example 2: Create a text file which will consist of student’s details

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Syntax:

var=open('Stu_Info.txt','w')

if var:

print("File is successfully opened")

num=int(input("Enter number of student:"))

for i in range(1,num+1):

name=input("Enter Student name:")

marks=input("Enter Student marks:")

[Link](name+"\t"+marks+"\n")

[Link]()

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Example 3: Create a marksheet by python and store it in a file.

Syntax:

var = open('[Link]', 'a')

if var:

print("File is successfully opened")

[Link]("ROLL" + "\t" + "NAME" + "\t" + "MARKS" + "\t" + "GRADE\n")

num = int(input("Enter number of students:"))

def addition():

for i in range(num):

roll = int(input("Enter roll number:"))

name = input("Enter Student name:")

marks1 = int(input("Enter marks1:"))

marks2 = int(input("Enter marks2:"))

tm = marks1 + marks2

avg = tm / 2

if avg >= 90:

grade = "A"

elif avg >= 80:

grade = "B"

elif avg >= 70:

grade = "C"

else:

grade = "Fail"

[Link](f"{roll}\t{name}\t{tm}\t{grade}\n")

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


addition()

[Link]()

print("Data successfully written to file.")

Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Different Python Modules
In Python, a module is a file containing Python code, including functions, classes, or variables,
that can be reused across different programs. Modules help in organizing and structuring code
by breaking it into separate components. There are two main types: built-in modules like math,
os, and random, which come with Python and offer standard functionalities, and external
modules, which can be installed using package managers like pip, such as requests for making
HTTP requests. Modules are imported using the import statement, enabling code reuse and
making programs more modular and maintainable.

Some examples of modules are:

1. Numpy: NumPy is a powerful Python library used for numerical computing,


particularly for working with arrays and matrices. It provides a high-performance
multidimensional array object, ndarray, and a wide range of functions for performing
operations on these arrays efficiently. NumPy is widely used in data science, machine
learning, and scientific computing due to its ability to handle large datasets and perform
mathematical operations like linear algebra, Fourier transforms, and random number
generation. It also offers functionality for integrating with C/C++ and Fortran code,
making it ideal for performance-critical applications.
Example:
import numpy
arr = [Link]([1, 2, 3, 4, 5])
print("Original array:", arr)
print("Array multiplied by 2:", arr * 2)
print("Sum of array elements:", [Link](arr))
print("Mean of array:", [Link](arr))
Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


2. Matplotlib: Matplotlib is a powerful Python library used for creating a variety of
static, interactive, and animated visualizations, especially 2D plots. It is commonly used
for line plots, bar charts, histograms, scatter plots, and more, with the pyplot module
providing an easy-to-use interface. Highly customizable, Matplotlib allows users to
modify plot elements like titles, axis labels, legends, and colors. It's often used in
conjunction with libraries like NumPy and pandas, making it an essential tool for data
visualization in fields such as data science, machine learning, and scientific research.
Example:
import [Link] as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y, marker='o', linestyle='-', color='b', label="Line 1")
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Simple Line Plot")
[Link]()
[Link]()
Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


3. Scipy: SciPy is a Python library that extends the capabilities of NumPy by providing
advanced functions for scientific and technical computing. It offers a range of tools for
optimization, integration, interpolation, signal processing, and statistical analysis.
SciPy includes modules such as [Link] for optimization problems,
[Link] for numerical integration, [Link] for data interpolation,
[Link] for signal processing, and [Link] for statistical operations. It is widely
used in scientific research and data analysis to perform complex mathematical
computations efficiently.
Example:
import numpy as np
from [Link] import minimize
from [Link] import quad
def objective_function(x):
return x**2 + 5*x + 6
result = minimize(objective_function, x0=0) # x0 is the initial guess
print("Optimization result:")
print(f"Optimal value: {[Link]}")
print(f"Optimal point: {result.x}")
def integrand(x):
return x**2
integral, error = quad(integrand, 0, 1)
print("\nIntegration result:")
print(f"Integral value: {integral}")
print(f"Integration error estimate: {error}")
Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


4. Sympy: SymPy is a Python library for symbolic mathematics, enabling algebraic
manipulation, equation solving, and calculus operations with exact, symbolic results
rather than numerical approximations. It provides tools for expanding, factoring, and
simplifying mathematical expressions, solving equations and systems symbolically,
performing differentiation and integration, and handling symbolic linear algebra.
Additionally, SymPy offers plotting capabilities for visualizing mathematical functions.
It is particularly valuable for theoretical mathematics, educational purposes, and
situations where precise, symbolic solutions are required.
Example:
import sympy as sp
x = [Link]('x')
expr = x**2 + 2*x + 1
simplified_expr = [Link](expr)
print("Simplified expression:")
print(simplified_expr)
equation = [Link](x**2 + 2*x + 1, 0)
solution = [Link](equation, x)
print("\nSolutions to the equation:")
print(solution)
derivative = [Link](expr, x)
print("\nDerivative of the expression:")
print(derivative)
integral = [Link](expr, x)
print("\nIntegral of the expression:")
print(integral)
Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


5. Random: random is a Python module that provides functions for generating random
numbers and performing random operations. It includes tools for producing random
integers, floating-point numbers, and sequences, as well as shuffling and sampling data.
Key functions include [Link]() for random integers, [Link]() for
floating-point numbers within a range, [Link]() for selecting random elements
from a sequence, and [Link]() for randomly rearranging elements in a list. The
module is useful for simulations, statistical sampling, and other applications where
randomization is required.
Example:
import random
num=[Link](1,5)
var = int(input("Enter number: "))
i=0
while i<6:
if num<var:
print("You have entered larger number")
var = int(input("Enter number: "))
elif num>var:
print("you have entered lower number")
var = int(input("Enter number: "))
else:
print("You Win...!")
break
i+=1
Output:

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


Assignment
1. Write a program that uses an if-else statement to check whether a number entered by
the user is even or odd.
2. Create a program that takes a number from the user and prints whether it is positive,
negative, or zero using if-else statements.
3. Write a program that checks if a number is divisible by both 3 and 5 using nested if-
else statements.
4. Extend the previous program to check if a number is divisible by 2, 3, and 5 using
nested if-else statements and print appropriate messages.
5. Write a program that prints the first 10 numbers of the Fibonacci sequence using a for
loop.
6. Create a program that iterates through a list of numbers and prints each number and its
square using a for loop.
7. Write a program that prints numbers from 10 to 1 in descending order using a while
loop.
8. Create a program that continues to prompt the user for a password until the correct
password is entered using a while loop.
9. Write a program that creates a list of 5 numbers, adds 5 to each number, and prints the
modified list.
10. Write a program that finds the largest number in a list of integers and prints it.
11. Write a program that creates a tuple with five elements and prints the number of
elements in the tuple.
12. Create a program that demonstrates set operations: union, intersection, and difference
using two sets of integers.
13. Write a program that creates a dictionary with five key-value pairs and prints the
dictionary's items in key-order.
14. Write a program that creates a 2D array (list of lists) and prints each row and column
of the array.
15. Write a function that takes two numbers as arguments and returns their sum. Test the
function with different values.
16. Create a module with a function that checks if a given number is prime. Import this
module and use the function in another script.

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091


17. Write a program that accepts a sequence of whitespace separated words as input and
prints the words after removing all duplicate words and sorting them alphanumerically.
Suppose the following input is supplied to the program:
hello world and practice makes perfect and hello world again Then, the output should
be: again and hello makes perfect practice world.
18. Write a Python program to create a calculator class. Include methods for basic
arithmetic operations (addition, subtraction, multiplication, division).
19. Use NumPy to create an array of 10 random integers between 1 and 50, and then
calculate and print the array's mean and standard deviation.
20. Use SymPy to differentiate the function f(x)=x3+3x2+2x+1f(x) = x^3 + 3x^2 + 2x +
1f(x)=x3+3x2+2x+1 and print the derivative.

[Link] 9830310550 4th floor, Kariwala towers, sector 5, Kolkata-700091

You might also like