0% found this document useful (0 votes)
12 views102 pages

Python Full Notes

Python is a high-level, interpreted programming language known for its readability and productivity, created by Guido van Rossum. It is widely used in various fields such as web development, data science, machine learning, and automation, and features a simple syntax, dynamic typing, and extensive libraries. Key characteristics include object-oriented programming, automatic memory management, cross-platform compatibility, and robust error handling.

Uploaded by

nagasekhar2006
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)
12 views102 pages

Python Full Notes

Python is a high-level, interpreted programming language known for its readability and productivity, created by Guido van Rossum. It is widely used in various fields such as web development, data science, machine learning, and automation, and features a simple syntax, dynamic typing, and extensive libraries. Key characteristics include object-oriented programming, automatic memory management, cross-platform compatibility, and robust error handling.

Uploaded by

nagasekhar2006
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 introduction

Python is a powerful, interpreted, high-level, and object-oriented programming language


created by Guido van Rossum in the late 1980s and officially released in 1991. Python
emphasizes code readability and productivity, making it ideal for rapid application
development.

Python Use Cases (Real-World Applications)

Area Example

Web Development Django, Flask, FastAPI

Data Science Pandas, NumPy, Matplotlib

Machine Learning Scikit-learn, TensorFlow, PyTorch

Automation & Scripting File renaming, auto-emailing

Game Development Pygame

Desktop GUI Tkinter, PyQt

Networking Paramiko, sockets

Cybersecurity Scripting, penetration testing

IoT/Robotics Raspberry Pi, MicroPython


Key Features

1. Simple and Readable Syntax

Python's syntax is designed to be easily understandable. It emphasizes code readability, which


makes Python easy to learn and use for both beginners and experienced developers.

Example:

You write print("Hello") and it just shows “Hello”.

No brackets, semicolons, or confusing code.

​ Like writing instructions in your notebook.

Program:

Python uses the print() function to output data, which is straightforward.

print("Hello, World!") # Output: Hello, World!

[Link] Language

Python is an interpreted language, meaning the Python code is executed line-by-line by the
Python interpreter. This allows for faster testing and debugging since you don’t need to
compile code before running it.

Example:
You can test and run your code step by step.
​ Like checking your answer after every math step.

Program:
x = 10
y = 20
print(x + y) # Output: 30

3. Dynamically Typed

In Python, you don’t need to specify the type of a variable. The Python interpreter
automatically detects the variable’s type during runtime.

Example:You can write x = 10 and later x = "Apple" — no problem.

​ Like writing in pencil and erasing it to change the answer.


Program:
x=5 # integer
x = "hello" # now x is a string
print(x) # Output: hello

[Link]-Oriented Programming (OOP)

Python supports object-oriented programming, which means you can define classes and
create objects to model real-world scenarios. OOP allows for code reuse,
modularity(breaking your code into separate, independent, and reusable pieces, such as
functions, classes, and modules), and the ability to model complex relationships between
objects.

Example:​
An online food delivery app like Swiggy or Zomato:

1.​ A Restaurant has many items, each with its own name, price, and category.​

2.​ A Customer places multiple orders.​

3.​ A DeliveryBoy picks up and delivers food.​

●​ Each role behaves differently but follows the same structure.


●​ Like using templates to handle thousands of restaurants and orders with one system.

5. Memory Management (Garbage Collection)

Python automatically manages memory allocation and deallocation through garbage


collection. This means you don’t need to manually allocate or free memory, as Python
handles it in the background.

Example:​
On your phone, when you close unused apps, the system automatically clears them from
memory to save space.

​ Python does the same — it removes unused variables and objects from memory.
​ Like a housemaid cleaning unused stuff from your room.

Program:

When you create a variable and assign it a value, Python automatically manages memory for
that variable.

x = 10 # memory allocated to x
y = 20 # memory allocated to y

6. Extensive Standard Library

Python comes with a rich standard library that includes modules and functions to perform a
wide variety of [Link] standard library provides an extensive set of built-in functions and
modules, reducing the need for third-party libraries for common tasks.

Example:

It's like needing to bake a cake and Python already gives you flour, sugar, milk, and utensils
inside the kitchen.

​ You don’t need to install anything extra for basic tasks — Python's standard library
has it all ready.

7. Cross-Platform Compatibility

Python is cross-platform, meaning Python code can run on Windows, macOS, Linux, and
even on mobile devices and microcontrollers (like Raspberry Pi).

Example:​
You save a Word document on your laptop, and your friend opens it on their Mac — same
file, same result.

​ Python code written on one computer runs the same on another, without changes.
​ Like wearing the same shoes on different roads — still fits.

8. Error Handling and Exceptions


Python provides an elegant way to handle errors through exception handling. It uses try,
except, else, and finally blocks to catch and handle exceptions.

Example:​
In an ATM machine, if you try to withdraw more than your balance, it shows a message:
“Insufficient funds” — it doesn't shut down.

​ Python handles errors like dividing by zero or file not found with warnings, not
crashes.
​ Like warning signs on the road instead of crashing the car.
Keywords

1.​ Keywords are reserved words in Python with special meaning.​

2.​ Cannot be used as variable names, function names, class names, etc.​

3.​ Keywords are case-sensitive


○​ True is valid​

○​ true is not a keyword​

4.​ Keywords are built-in — no need to import anything to use them.​

5.​ Keywords control Python syntax and structure​


(e.g., if, for, def, return, class)​

6.​ Keyword meanings cannot be changed or reassigned


7.​ Use import keyword and [Link] to get the current list of keywords.​

8.​ You cannot assign values to keywords ​


Example: if = 10 → Error​

9.​ Some keywords relate to modules and scope:​


import, from, as, global, nonlocal​

10.​ New keywords may be added in newer Python versions (e.g., match, case in Python
3.10+)​

False,None,True,and,as,assert,async,await,break,class,continue,def,del,elif,else

,except,finally,for,from,global,if,import,in,is,lambda,nonlocal,not,or,pass,raise,return

,try,while,with,yield

Note: In Python 3.10+, two new keywords were added: match and case (used in structural
pattern matching). So with those, total becomes 37.

Match,case
Identifiers in Python

In Python, an identifier is the name given to a variable,function, class, object, or module.​


It is used to uniquely identify each item in a Python program.

Examples of identifiers: name, age, total_sum, calculate_area(), Student, etc.

1: Only Letters, Digits, and Underscore Allowed

●​ Identifiers can only contain:​

○​ Letters (A–Z or a–z)​

○​ Digits (0–9)​

○​ Underscore _​

Symbols like @, #, $, %, *, - are not allowed in identifiers.

2: Must Start with a Letter or Underscore

●​ Identifiers cannot begin with a digit.​

●​ Valid starting characters:​

○​ A–Z​

○​ a–z​

○​ _ (underscore)​

Examples of invalid identifiers:

●​ 2name → Invalid (starts with digit)​

●​ @value → Invalid (contains special character)

3: Cannot Use Python Keywords

Python keywords (like if, class, def, return) are reserved words and cannot be used as
identifiers.
Example:

def = 5 # Invalid because 'def' is a keyword

4: Case-Sensitive

●​ Identifiers in Python are case-sensitive.​

●​ Example: Age, AGE, and age are all different identifiers.​

5: No Length Limit

●​ Python does not restrict the length of an identifier.​

●​ However, it is recommended to keep names short and meaningful.


Indentation

In Python, indentation means adding spaces at the beginning of a line to indicate a block of
[Link] many other languages that use {} to define code blocks, Python uses indentation
to define scope (inside loops, functions, if statements, etc.). Python requires indentation — it
is not optional!

Why Indentation is Important

●​ Without proper indentation, Python will show an error.​

●​ It makes the code organized and readable.


COMMENTS:
``
Python Operators

Operators in Python are special symbols used to perform operations on variables and values.
Let's break them down into categories with examples.

1. Arithmetic Operators

Used for basic mathematical operations.

Operator Description Example Result

+ Addition 5+3 8

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division(float) 5/2 2.5

// Floor Division(int) 5 // 2 2

% Modulus(remainder) 5%2 1

** Exponentiation 2 ** 3 8

2. Comparison Operators

Used to compare two values. Returns True or False.

Operator Description Example Result

== Equal to 5 == 5 True

!= Not equal to 5 != 3 True

> Greater than 5>3 True

< Less than 3<5 True

>= Greater than or equal 5 >= 5 True

<= Less than or equal 3 <= 5 True


3. Assignment Operators
Used to assign values to variables.

Operator Example Same As

= x=5 Assign 5 to x

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

//= x //= 3 x = x // 3

%= x %= 3 x=x%3

**= x **= 2 x = x ** 2

4. Logical Operators

Used to combine conditional statements.

Operator Description Example Result

and True if both are true True and False False

or True if at least one is True or False True


true

not Inverts the result not True False

5. Identity Operators

Used to compare memory locations of two objects.

Operator Description Example

is True if same x is y
object

is not True if not same x is not y


6. Membership Operators

Used to test if a value is in a sequence (like list, string, etc.).

Operator Description Example

in True if 'a' in 'apple' → True


present

not in True if absent 'z' not in 'apple' → True

7. Bitwise Operators

Used for binary operations on numbers.

x=10(0000 1010) ,y=4(0000 0100) [0-false,1-true]

0*27+0*26+0*25+0*24+1*23+0*22+1*21+0*20

8+2

0*27+0*26+0*25+0*24+0*23+1*22+0*21+0*20

Operator Description Example

& AND x & y=0(0000 0000)

| OR x|y = 14(0000 1110)

^ XOR x^y=14(0000 1110)

<< Left Shift x << 2 =40(0010 1000)

>> Right Shift x >> 2 = 2(0000 0010)


Decision making statements
1)SIMPLE IF

1)num = 10
if num > 0:
print("The number is positive.")

2)age = 68
if age >= 18:
print("You are eligible to vote.")

3)a = 5
b=5
if a == b:
print("Both numbers are equal.")

4)num = 8
if num % 2 == 0:
print("The number is even.")

5)sentence = "aeiou"
if "a" in sentence:
print("vowel")
2)IF-ELSE

1)num = -5
if num > 0:
print("The number is positive.")
else:
print("The number is negative.")
2)age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
3)num = 7
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")

4)password = "admin123"
if password == "admin123":
print("Access granted.")
else:
print("Access denied.")
3)if….elif….else

1)marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 80:
print("Grade: B")
elif marks >= 70:
print("Grade: C")
else:
print("Grade: Fail")
2)num = 0
if num > 0:
print("Positive number")
elif num < 0:
print("Negative number")
else:
print("Zero")
3)day = 3
if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
elif day == 4:
print("Thursday")
elif day == 5:
print("Friday")
elif day == 6:
print("Saturday")
elif day == 7:
print("Sunday")
else:
print("Invalid day number")
4)age = 15
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
elif age < 60:
print("Adult")
else:
print("Senior Citizen")
5)a = 10
b=5
operation = "divide"
if operation == "add":
print("Result:", a + b)
elif operation == "subtract":
print("Result:", a - b)
elif operation == "multiply":
print("Result:", a * b)
elif operation == "divide":
print("Result:", a / b)
else:
print("Invalid operation")
4)multiple if:
Multiple if statements means more than one if condition is checked independently, not using
elif or [Link] if block runs separately — even if one condition is true, the others are still
checked.
Syntax:
if condition1:

# do something

if condition2:

# do something else

if condition3:

#do something else

Examples:

1)num = 30

if num % 2 == 0:

print("Divisible by 2")

if num % 3 == 0:

print("Divisible by 3")

if num % 5 == 0

print("Divisible by 5")

2)marks = 65

attendance = 80

if marks >= 50:

print("Student has passed.")

if attendance >= 75:

print("Good attendance.")

if marks > 60:

print("Above average performance.")


3)balance = 120

min _balance = 100

max_balance = 1000

if balance < min_balance:

print("Warning: Low balance.")

if balance > max_balance:

print("Warning: Balance exceeds maximum limit.")

if balance == 0:

print("Account is empty.")
5)Nested if statement

1)balance = 1000
withdraw_amount = 500

if withdraw_amount <= balance:


if withdraw_amount % 100 == 0:
print("Withdrawal successful!")
else:
print("Amount must be in multiples of 100.")
else:
print("Insufficient balance.")
2)username = "admin"
password = "admin123"
if username == "admin":
if password == "admin123":
print("Login successful.")
else:
print("Incorrect password.")
else:
print("Username not found.")

3)marks = 85
if marks >= 50:
print("You passed.")

if marks >= 75:


print("You got distinction!")
else:
print("You failed.")
4)is_open = False
food_in_stock =False
if is_open:
if food_in_stock:
print("Order placed!")
else:
print("Sorry, item out of stock.")
else:
print("Restaurant is closed.")
5)age = 20
has_license = True
if age >= 18:
if has_license:
print("You can drive.")
else:
print("Get your license first.")
else:
print("You are too young to drive.")
6)conditional expression

A conditional expression is a shorter way to write an if-else statement.


It's also called a ternary operator.

1)num = 5
result = "Even" if num % 2 == 0 else "Odd"
print(result)

2)age = 17
message = "Eligible to vote" if age >= 18 else "Not eligible"
print(message)

3)a = 10
b = 20
max_value = a if a > b else b
print("Maximum:", max_value)

4)marks = 45
result = "Pass" if marks >= 35 else "Fail"
print(result)

a=int(input())
c=0
for i in range(2,100):
if a%i==0:
c+=1
if c==1:
print("p")
else:
print("np")

Nested for loop:


A nested for loop is a loop within a loop. The inner loop will iterate through its entire range
for each iteration of the outer loop.

for i in range(1,10):
for j in range(1,5):
print(i,j)

for i in range(1,11):
for j in range(i):
print(i,end=" ")
print()
for i in range(1,11):
for j in range(i):
print("*",end=" ")
print()

for i in range(2,11):
for j in range(2,i):
if i%j==0:
break
else:
print(i,end=" ")
Data types
Numerical —int,float,complex
Sequence—list—[1,2,”hi”],
tuple—(1,2,”hi”),
string—”hello”
Set—-{1,2,”hi”}
frozenset—frozenset({1,2,”hi”})
Dictionary—--{1:”hi”,2:”how”,3:”are”}
Boolean
Numerical data types
Integers (int):
- Whole numbers, e.g., 1, 2, 3, etc.
- Can be positive, negative, or zero
- Used for counting, indexing, and arithmetic operations

Floating Point Numbers (float):


- Decimal numbers, e.g., 3.14, -0.5, etc.
- Can be positive, negative, or zero
- Used for calculations requiring precision, such as scientific simulations

Complex Numbers (complex):


- Numbers with real and imaginary parts, e.g., 3+4j, 2-5j, etc.
- Used for calculations involving complex arithmetic, such as signal processing
Sequence:
Strings:
Python string is the collection of the characters surrounded by single quotes,double quotes or
triple quotes.
Python does not have a character data type,a single character is simply a string with length of
1.
Eg: string=”welcome to python”

str=”HELLO”
str[0]=’H’
str[1]=’E’
str[2]=’L’
str[3]=’L’
str[4]=’O’
str[-2]=’L’

H E L L O
0 1 2 3 4
-5 -4 -3 -2 -1

String slicing:
The slice operator [ ] is used to access the individual characters of the [Link],we
can use the :(colon) operator in python to access the substring from the given string.
Syntax: string[a:b]
Eg: str[:]=’hello’
str[:3]=’hel’
str[1:]=’ello’
str[1:4]=’ell’
str[:-1]=’hell’

Looping through a string:


Since strings are arrays,we can loop through the characters in a string,with a for loop
Eg:
for x in “hello”:
print(x)

Change or update a string:


Strings are [Link] means that elements of a string cannot be changed once they
have been assigned.

Deleting the string:


Strings are immutable. We cannot delete or remove the characters from the string.
But we can delete the entire string using the del keyword.
Syntax: del string_object
del str

String operators:
concatenation(+):
You can join or concatenate two strings by using the concatenation operator(+).
Eg:s1=’welcome’
s2=’python’
s3=s1+s2
Repetition(*):
Repetition is like adding a string to itself a number of times
Eg: s1=’python’
s2=s1*2
Membership operator(in/not in):
You can use the in and not in operators to test whether a string is in another string
s1=’welcome’
‘come’ in s1 #return True
‘come’ not in s1 #return False

raw String (r/R):


In Python, when you prefix a string with the letter r or R such as r'string' and R' string, that
string becomes a raw string. The interpreter does not implement the escape sequence in raw
strings but rather considers them as normal characters.

Example: r'lang tver\nPython\t3'

String Methods

1) capitalize()
Python capitalize() method converts the first character of the string into uppercase without
altering the whole string.

Syntax: [Link]()

Example: str = "hello"


str2=[Link]() #output: Hello

2) title()
The title() method returns a string where the first character in every word is upper case. If the
word contains a number or a symbol, the first letter after that will be converted to upper case.

Syntax: [Link]()
Example: str="hello how are you"
str2= [Link]() #output: Hello How Are You

3) lower()
This method converts all uppercase characters in a string into lowercase characters and
returns it.

Syntax: [Link]()

Example:str = "HELLO"
str2=[Link]() #output: hello

4) upper()
This method converts all lowercase characters in a string into uppercase characters and
returns it.
Symbols and Numbers are ignored.

Syntax:[Link]()

Example: str = "hello"


str2 = [Link]() #output: HELLO

5) count()
The count() method returns the number of occurrences of a substring in the given string.

Syntax: [Link](substring |, startIndex, endIndex])

Example: message='python is popular programming language


[Link](‘p’) #output:4

6) find()
The find() method returns the index of the first occurrence of the substring (if found). If not
found, it returns-1.

Syntax: [Link](substring |, startIndex, endIndex])

Example:message= 'python is popular programming language'


[Link]('la')) Output: 14

7) strip()
The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the
end) characters (space is the default leading character to remove)
Syntax [Link](characters)

Example:txt=” banana “
x=[Link]() #Output: banana

8) split()
The split() method splits a string into a list. You can specify the separator, default separator is
whitespace.
Syntax:[Link](separator, maxsplit)

Example:. txt "hello my name is Ram'


x=[Link]() Output: ['hello,', 'my', 'name', 'is', 'Ram']
[Link](‘ ‘,3) Output: ['hello', 'my’,’ name', 'is Ram']

9) replace()
The replace() method replaces each matching occurrence of the old character/text in the
string with the new character/text.
Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.

Syntax [Link](oldvalue, newvalue, count)

Example:str="Good Day"
[Link]("Day", "Luck") Output: Good Luck

10) format()
The format() method formats the specified value(s) and inserts them inside the string's
placeholder. The placeholder is defined using curly brackets: {}

Syntax: [Link](value_l, value_2...)

Example:
txt1="My name is {f_name}. I'm {age}".format(f_name= "Ram", age=36)
txt2="My name is {0}, I'm {1}".format("Ram",36)
txt3="My name is {}. I'm {}".format("Ram",36)

Output
My name is Ram, I'm 36
My name is Ram, I'm 36
My name is Ram, I'm 36
List:
A list in python is used to store the sequence of various types of [Link] lists are mutable
types it means we can modify its elements after it is created.
List items are ordered,changeable,and allow duplicate values.
Eg: l1=[]
l2=[1,2,3,4]
l3=[‘abc’,43,True,40,’male’]

Accessing elements from the list:


An element in a list can be accessed through the index operator[].In Python, index starts at 0,
Index ranges from 0 to len(list)-1 . Trying to access indexes other than these will raise an
Index Error
Syntax: mylist[index]
Eg :l1=[1,2,3,4]
l1[2]

Slicing a list:
The slice operator [ ] is used to access the individual element of the [Link],we can use
the :(colon) operator in python to access the sublist from the given list.
Eg: l1=[1,2,3,4,5]
l1[1:4]

Change list elements:


Lists are mutable,meaning their elements can be changed unlike string or tuple. We can use
the assignment operator = to change an item or a range of items.
Syntax: list[index]
Eg: e=[2,4,6,8,10]
e[0]=1 #[1,4,6,8,10]
e[1:4]=[3,4,7] #[1,3,4,7,10]
Delete list elements:
We can delete one or more items from a list using the python del statement.
It can even delete the list entirely.
Syntax:l1=[1,3,5,7,9]
Eg: del l1[1] #[1,5,7,9]
del l1[2:4] #[1,9]
del l1
Traversing elements in a loop:
The elements in a python list are iterable.
Eg: l1=[1,3,5,7,9]
for i in l1:
print(i)
List Methods

1) len()
Python list method len() returns the number of elements in the list!

Syntax:len(list)

Example: thislist=[100, 50, 65, 82, 231]


len(thislist) #output 5

2) append()
The append() method adds an item to the end of the list.
The item can be a number, string, list etc

Syntax: [Link](item)

Example 1: mylist [[Link].9] #adds 11 at end of list


[Link](11)
Example 2: list2=[13,15,17]
[Link](list2) #appending list

3) insert()
The insert() method inserts an element to the list at the specified index.

Syntax:[Link](index, element)

Example:vowel=['a', 'e', 'i', 'u']


[Link](3, 'o’') #'o' is inserted at index 3 (4th position)

4) extend()
The extend() method adds all the elements of an iterable (list, tuple, string etc.) to the end of
the list.

Syntax:[Link](iterable)

Example:list1=[1,2,3]
list2=[4,5,6]
[Link](list2) #now list1 contains [[Link].5.6]

5) remove()
The remove() method removes the first matching element (which is passed as an argument)
from the list.

Syntax:[Link](element)
Example:list1 [10,20,30,40,50]
[Link](30) #now list1 contains [[Link]]
If the element doesn't exist, it throws ValueError

6) pop()
The pop() method removes the item at the given index from the list and returns the removed
item.

Syntax:[Link](index)

Example:list1 [[Link].50]
[Link](2) #now list1 contains [[Link]]

If index not passed, the default index -1 is passed as an argument (index of the last item). If
the index passed to the method is not in range, it throws IndexError

7) clear()
The clear() method removes all items from the list.

Syntax:[Link]()

Example:list1=[10,20,30,40,50]
[Link]()

8) index()
The index() method returns the index of the specified element in the list.

Syntax:[Link](element, start, end)

Example:list1=[10,20,30,40,50]
[Link](30) #returns 2

9) count()
The count() method returns the number of times the specified element appears in the list.

Syntax:[Link](element)

Example:list1=[10,20,30,40,50,30]
[Link](30) #returns 2
10) sort()
The sort() method sorts the items of a list in ascending or descending order. It changes the
original list.

Syntax:[Link](reverse=True)

reverse - If True, the sorted list is reversed (or sorted in Descending order)

Example:list1=[20,10,30.50.40]
[Link]() #returns [10.20,30,40,50,30]
[Link](reverse=True) #returns [50, 40, 30, 20, 10]

11) reverse()
The reverse() method reverses the elements of the list.

Syntax:[Link]()

Example:list1=[10,20,30,80,50]
[Link]() #returns [50, 80, 30, 20, 10]

12) copy()
The copy() method returns a shallow copy of the list.

Syntax:new_listlist.copy()

Example:list1=[10,20,30,40,50]
list2=[Link]() #now list2 contains [[Link].50]
We can also use the operator to copy a list.
Example:list2=list1
Tuples:
A tuple is a collection of objects which are ordered and immutable. Tuples are sequences,
just like lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.
Eg: t1=()
t2=(1,”john”,3.4)

Access Tuple Elements:


An element in a tuple can be accessed through the index operator [] syntax tuple[index]
In Python, indices start at 0, tuple Index range from 0 to len(my Tuple)-1 Trying to access
indexes other than these will raise an Index Error.
Eg: t1=(2,3,5,2,33,21)
t1[0]
t1[-1]

Slicing a tuple:
We can access a range of items in a tuple by using the slicing operator
Eg: t1[2:5]
t1[2:]

Add/Change Tuple Elements:


Unlike lists, tuples are immutable. Once a tuple is created, you cannot add new elements,
delete elements, replace elements, or reorder the elements in the tuple

Delete tuple elements:


We cannot change the elements in a tuple. It means that we cannot delete or remove items
from a tuple . so delete tuples entirely.
Syntax: del tuplename
Eg: del t1

Tuple Methods
1) count()
The count() method returns the number of times the specified element appears in the tuple.

Syntax:[Link](element)

Example:vowels=(‘a’,’ e’, ‘i’,’ o’,’u’)


[Link](‘i’) #result is 1

2) index()
The index() method returns the index of the specified element in the tuple.

Syntax:[Link](element, start, end)


Example:t1=(10,20,30,40,50)
[Link](30) #returns 2

3) len()
Python tuple method len() returns the number of elements in the tuple

Syntax:len(tuple)

Example:t1=(10,20,30,40,50)
len(t1) #prints 5

4) min()
The min() method returns the elements from the tuple with minimum value.

Syntax:min(tuple)

Example:t1=(10,20,30,40,50)
min(t1) #prints 10

5) max()
The max() method returns the elements from the tuple with maximum value.

Syntax:max(tuple)

Example:t=(10,20,30,40,50)
max(t) #prints 50
Sets:
1) Unordered & Unindexed collection of items.
2) Set elements are unique. Duplicate elements are not allowed.
3) Set elements are immutable (cannot be changed).
4) Set itself is mutable. We can add or remove items from it.
Set items are unordered, changeable and do not allow duplicate values.
Sets can also be used to perform mathematical set operations like union, intersection,
symmetric difference, etc.
Eg: s1=set()
s2={1.2,”apple”,(6,7,8)}
s3=set([1,2,3,4,5])

Modifying Items in a set:


Once a set is created, you cannot change its items, but you can add new items. We cannot
access or change an element of a set using indexing or slicing.

Adding Items to a set:


add() can be used to add a single element
Syntax:[Link](item)
Eg:s1={1,2,3}
[Link](5)
[Link](3)

Removing elements from a set:


A particular item can be removed from a set using the methods discard() and remove(),
discard(): Used to remove an item from a set.
Syntax:[Link](item)
Eg:s1={1,2,3}
[Link](2)

Accessing elements in a set:


You cannot access items in a set by referring to an index or a key. But you can loop through
the set items using a for loop
Eg: s1={“john”,1,2.3}
for i in s1:
print(i)

Set Methods

1) update()
The update() method can be used to add multiple elements.
In all cases, duplicates are avoided.
The update() method can take tuples, lists, strings or other sets as its argument.
Syntax:[Link](list, set, dictionary, string....)

Example:sl = {1,2,3}
lst=[5,6]
tup=(7,8)
[Link] ([Link])
#now set contains {1,2, 3,5,6, 7, 8}

2) clear()
The clear() method removes all items from the set.

Syntax:[Link]()

Example:s1={1,2,3}
[Link]() #empty set()

3) copy()
The copy() method returns a copy (shallow copy) of the set.

Syntax:[Link]()

Example:s1 = {1,2 , 3}
s2=[Link]() # Output : now s2 contains {1.2.3}

4) union()
The Python set union() method returns a new set with distinct elements from all the sets.

Syntax:[Link](set2.set3...)

Example:A={2,3,5}
B = {1, 3, 5}
[Link](B) #Output: AUB= {1,2,3,5}

You can also find the union of sets using the | operator. Ex: A|B

5) intersection()
The intersection() method returns a new set with elements that are common to all sets.

Syntax:set1. intersection (set2,set.3...)


Example:

A = {2, 3, 5}
B = {1, 3, 5}
[Link](B) Output: A & B = {3, 5}
You can also find the intersection of sets using & operator. Ex: A& B

6) difference()
The difference() method computes the difference of two sets and returns items that are unique
to the first set

Syntax: set1. difference(set2)

Example: A = {2, 3, 5}
B = {1, 3, 5}
A. difference(B) Output: A-B ={2}
We can also find the set difference using-operator in Python. Ex: A-B

7) symmetric_difference()
The symmetric_difference() method returns all the items present in given sets, except the
items in their intersections.

Syntax:set1. symmetric_difference(set2)

Example:A = {2, 3, 5}
B = {1, 3, 5}
A. symmetric_difference(B) Output: A ^ B = {1, 2}
We can also find the symmetric difference using the operator in Python. Ex: A^B

8) isdisjoint()
The isdisjoint() method returns True if two sets don't have any common items between them,
i.e. they are disjoint. Else the returns False.

Syntax:setl. isdisjoint (set2)

Example:A = {2, 3, 5}
B = {1, 3, 5}
[Link] (B) Output: false
Frozenset :
Definition
A frozen set is a built-in data type in Python that is an immutable collection of unique
[Link] is similar to a set but cannot be modified after creation.
Unordered,unchangeable,do not allow duplicate values
Syntax: frozenset(iterable)
Creating a frozenset from a list:The frozenset constructor takes an iterable (like a list, tuple,
or another set) and returns a frozen set containing the elements of the iterable.

# Creating an empty frozen set

empty_frozen_set = frozenset()

print(empty_frozen_set) # Output: frozenset()

# Creating a frozen set from a list

frozen_set = frozenset([1, 2, 3, 4, 5])

print(frozen_set) # Output: frozenset({1, 2, 3, 4, 5})

# Creating a frozen set from a tuple

frozen_set = frozenset((1, 2, 3, 4, 5))

print(frozen_set) # Output: frozenset({1, 2, 3, 4, 5})

# Creating a frozen set from a string

frozen_set = frozenset("hello")

print(frozen_set) # Output: frozenset({'h', 'e', 'l', 'o'})

Operations on Frozen Sets:

Frozen sets support various set operations, but since they are immutable, you cannot use
methods that modify the set (like add, remove, etc.).

# Union

set1 = frozenset([1, 2, 3])

set2 = frozenset([3, 4, 5])

union_set = [Link](set2)

print(union_set) # Output: frozenset({1, 2, 3, 4, 5})


# Intersection

intersection_set = [Link](set2)

print(intersection_set) # Output: frozenset({3})

# Difference

difference_set = [Link](set2)

print(difference_set) # Output: frozenset({1, 2})

# Symmetric Difference

symmetric_difference_set = set1.symmetric_difference(set2)

print(symmetric_difference_set) # Output: frozenset({1, 2, 4, 5})

Use Cases

Dictionary Keys: Since frozen sets are hashable, they can be used as keys in dictionaries.

my_dict = {frozenset([1, 2, 3]): "value"}

print(my_dict) # Output: {frozenset({1, 2, 3}): 'value'}

Set of Sets: You can create a set of frozen sets.

set_of_sets = {frozenset([1, 2]), frozenset([3, 4])}

print(set_of_sets) # Output: {frozenset({1, 2}), frozenset({3, 4})}


Dictionary:
A dictionary is a container object that stores a collection of key/value pairs. It enables fast
retrieval, deletion, and updating of the value by using the key.
Dictionaries are written with curly brackets, and have keys and values
Dictionary items are ordered, changeable, and do not allow duplicates.

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

Creating Dictionary:
Creating a dictionary is as simple as placing items inside curly braces {} separated by
commas.
An item has a key and a corresponding [Link] is expressed as a pair (key: value).
Syntax:
dict_obj(key:value, key:value, key:value....)
Eg:
my_dict={}
#dictionary with integer keys
my_dict={1: 'apple', 2: 'ball'}
#dictionary with mixed keys
my_dict={'name': 'John', 1: [2, 4, 3]}

Accessing Elements from Dictionary:


A dictionary uses keys to access elements. Keys can be used either inside square brackets []
or with the get() method.
If we use the square brackets []. KeyError is raised in case a key is not found in the
dictionary. On the other hand, the get() method returns None if the key is not found.
Syntax:dict_obj[key]
Eg: my_dict ={1: 'apple', 2: 'ball"}
my_dict[1]
my_dict[2]
Add/Change Dictionary values:
The dictionary is a mutable data type, and its values can be updated by using the specific key.
The update() method is also used to update an existing value. If the key-value is already
present in the dictionary, the value gets updated. Otherwise, the new keys added in the
dictionary.
Syntax:dict_obj[key] = value
Eg:
my_dict={1: apple', 2: 'ball'}
my dict|1| =fruit #changes value for key '1'
my_dict[3]=26 #adds new item​
Removing elements from Dictionary:
We can also use the del keyword to remove individual items or the entire dictionary itself.
Syntax:
#used to remove individual item
del dict_obj[key]
#used to remove entire dictionary
del dict_obj
Display Elements in Dictionary:
(a) Print all key names in the dictionary d1, one by one:
for x in dl:
print(x)
(b) Print all values in the dictionary, one by one:
for x in dl:
print(d1[x])

Dictionary Methods.

1) keys()
The keys() method extracts the keys of the dictionary and returns the list of keys as a view
object

Syntax:[Link]()

Example:d1={‘rno’: 12, 'name': 'Srijay ‘,'age’: 13}


[Link]() #displays dict_keys(['rno', 'name', 'age'])

2) items()
The items() method returns a view object that displays a list of dictionary's (key, value) tuple
pairs.

Syntax:[Link]()

Example:d1={‘rno’: 12, 'name': 'Srijay 'age: 13}


d1 items() Output:dict_items([(‘rno’: 12),( 'name': 'Srijay '),(’age’:
13)])

3) len()
The len() method returns the number of items in a dictionary.

Syntax:len(dict)

Example:d1={‘rno’: 12, 'name': 'Srijay ',’age’: 13}


len(d1) output:len(d1)
4) values()
The values() method returns a view object that displays a list of all the values in the
dictionary.

Syntax:[Link]()

Example:d1={‘rno’: 12, 'name': 'Srijay ',’age’: 13}


[Link]() Output:dict values([12. Srijay', 13))

5) get()
The get() method returns the value for the specified key if the key is in the dictionary and
None if the key is not found.

Syntax:[Link](key)

Example: d1={‘rno’: 12, 'name': 'Srijay ',’age’: 13}


[Link]('name') Output:Srijav

6) pop()
The pop() method removes and returns an element from a dictionary having the given key, If
key is found-it returns value of removed/popped element from the dictionary If key is not
found - Key Error exception is raised

Syntax:[Link](key)

Example:d1={‘rno’: 12, 'name': 'Srijay ',’age’: 13}


[Link](‘age’) output:13

7) popitem()
The popitem() method removes and returns the (key, value) pair from the dictionary in the
Last In. First Out (LIFO) order.

Syntax:[Link]()

Example:d1={‘rno’: 12, 'name': 'Srijay ',’age’: 13}


[Link]() Output:{'age’: 13}

8) clear()
The clear() method removes all items from the dictionary.

Syntax:[Link]()

Example:d1={‘rno’: 12, 'name': 'Srijay ',’age’: 13}


[Link]() Output:{} #empty dictionary
9) copy()
They copy() method returns a copy (shallow copy i of the dictionary

Syntax:[Link]()

Example:d1={‘rno’: 12, 'name': 'Srijay ',’age’: 13}


d2=[Link]()
Output:now d2 contains {‘rno’: 12, 'name': 'Srijay ',’age’: 13}
Type Conversion:

The process of converting the value of one data type (integer, string, float, etc.) to another
data type is called type conversion. Python has two types of type conversion.​
Implicit Type Conversion​
1. Implicit Type Conversion​
2. Explicit Type Conversion​

type():

The type() function returns the type of the specified object.

Example:​
a = "Hello World"​
b = ("apple", "banana", "cherry")​
c = 33

type(a)​
type(b)​
type(c)

[Link] Type Conversion​


In implicit type conversion, Python automatically converts one data type to another data
type. This process doesn't need any user involvement.​
In Python, when performing implicit type conversion, it avoids the loss of data.​

Example:​
x = 10​
type(x)

y = 10.6​
type(y)

x = x + y​
type(x)

As we can see the data type of x got automatically changed to the float type while one
variable x is of integer type while the other variable y is of float type.

[Link] Type Conversion (Type Casting)

In explicit type conversion, users convert the data type of an object to required data type. We
use built-in functions like int(), float(), str(), etc.
Syntax:​
<required_data_type>(expression)

1)int(a,base)

This function converts any data type to integer. “base” specifies the base in which string is
the data type for a string.​

Example:​
a = "10010" #string​
b=int(a) #10010

c= int(a, 2) #18

2)float()

This function is used to convert data type to a floating-point number.​


Example:​
float(“10010”) #10010.0

3)ord()

This function is used to convert a character to integer.​


Example:​
ord('A') #65

4)str()

This function is used to convert integers into a string.

5)list():

This function is used to convert any data type to a list type.​


Example:​
list((1, 3, 7))

6)tuple():

This function is used to convert string, list, set, dictionary to a tuple.​


Example:​
tuple([1, 3, 7])​
tuple("Hello")
7)set():

This function returns the type after converting to set.​


Example:​
set([1, 3, 7])

8)chr():

The chr() method converts the character (string) from integer.​


Example:​
chr(65) #’A’

9)eval():

The eval() function takes a string that contains a Python expression, converts it into a
Python expression, and then executes it. Example:​
eval("2+3")
User Defined functions:

In Python, a function is a group of related statements that performs a specific task.

Functions avoid repetition and make the code reusable.

Functions provide better modularity for your application and a high degree of code reusing.

The functions which are created by a programmer i=are called User defined Functions.

Syntax:

def function_name(parameters):

"Function_docstring"

Function_suite

return [expression]

1)Function without parameters and without return values:

def greet():

print(“welcome to python”)

2)Function without parameters and with return values:

def greet():

return "Hello, World!"

print(greet())

3)Function with parameters and without return values:

def greet(name, age):

print(f"Hello, {name}! You are {age} years old.")

# Call the function

greet("John", 30)
4)Function with parameters and with return values:

def add_numbers(a, b):

result = a + b

return result

# Call the function

num1 = 5

num2 = 7

sum_result = add_numbers(num1, num2)

print(f"The sum of {num1} and {num2} is: {sum_result}")


Function Arguments:

The argument is a value, a variable, or an object that we pass to a function or method call. In
Python, there are four types of arguments allowed.

a)Formal arguments

b)actual arguments

c) Positional (Required) arguments

d) Keyword arguments.

e) Default arguments.

f) Variable-length arguments

a)Formal arguments

Called function arguments are called as formal arguments

b)actual arguments.

Calling function arguments are called as actual arguments.

c) Positional (Required) arguments

Required arguments are the arguments passed to a function in correct positional [Link]
a function call, values passed through arguments should be in the order of parameters in the
function definition. This is called positional [Link] the positional argument number
and position of arguments must be matched. If we change the order, then the result may
change. Also, If we change the number of arguments, then we will get an error.

Example:

def add(a, b):

print(a+b)

add(50, 10)

#number and position of arguments are matched here

add(50, 10, 4)

#TypeError: add() takes 2 positional arguments but 3 #were given


b) Keyword Arguments

When we call a function with some values, these values get assigned to the arguments
according to their [Link] can also be called using keyword arguments of the form
kwargs = [Link] we call functions in this way, the order (position) of the arguments can
be [Link] a positional argument after keyword arguments will result in errors.

Example:

def add(a, b ,c ):

print(a+b+c)

add( b = 10,c = 15,a = 20 )

# Output 45

add(a = 10)

# Output 25

add (c = 5, a = 5 )

# Output 15

Example:

def message(first_nm, last_nm):

print("Hello..!". first_nm. last_nm)

message("John", "Wilson")

message("John", last_nm="Wilson")

c) Default arguments

Default arguments are values that are provided while defining functions.

The assignment operator = is used to assign a default value to the argument.

Default arguments become optional during the function calls.

If we provide a value to the default arguments during function calls, it overrides the default
value.

The function can have any number of default arguments


Default arguments should follow non-default arguments.

Example:

def add(a,b=5,c=10):

return (a+b+c)

print(add(3))

print(add(3,4))

print(add(2,3,4))

#Output: 18

#Output: 17

Given only the mandatory argument

Given one of the optional arguments.

#3 is assigned to a, 4 is assigned to b.

# Output:9

d) Variable-length (Arbitrary Arguments) Arguments

In Python, sometimes, there is a situation where we need to pass multiple numbers of


arguments to the function. Such types of arguments are called variable-length [Link]
the function definition, we use an asterisk (*) before the parameter name to denote
variable-length argument

Syntax:

def fun(*var):

function body

We can pass any number of arguments to this function. Internally all these values are
represented in the form of a tuple.

Example:

def add(*numbers):
total = 0

for no in numbers:

total=total + no

print("Sum is:", total)

add()

#0 arguments

add(10,5, 2, 5, 4)

#5 arguments

add(78,7,2.5)

# 4 arguments

Output

Sum is: 0

Sum is: 26

Sum is : 87.5
args & kwargs
*args:
When we are not sure about the number of arguments being passed to a function then we can

use *args as function parameter.

*args allow us to pass the variable number of Non Keyword Arguments to function.

We can simply use an asterisk * before the parameter name to pass variable length

arguments.

The arguments are always passed as a tuple.

We can rename it to anything as long as it is preceded by a single asterisk (*). It's best

practice to keep naming it args to make it immediately recognizable.

**kwargs:
**kwargs allows us to pass the variable number of Keyword Arguments to the function.

We can simply use an double asterisk ** before the parameter name to pass variable length

arguments.

The arguments are passed as a dictionary.

We can rename it to anything as long as it is preceded by a double asterisk (**). It's best

practice to keep naming it kwargs to make it immediately recognizable


Lambda, Filter, Map and Reduce

Lambda

A lambda function is an anonymous function (function without a name).

Lambda functions can have any number of arguments but only one expression. The

expression is evaluated and returned.

We use lambda functions when we require a nameless function for a short period of time.


Filter:

It is used to filter the iterables/sequence as per the conditions.

Filter function filters the original iterable and passes the items that returns True for the
function provided to filter

It is normally used with Lambda functions to filter list, tuple, or sets.

filter() method takes two parameters:

function - function tests if elements of an iterable returns true or false

iterable - Sequence which needs to be filtered, could be sets, lists, tuples, or any iterators
Map

The map() function applies a given function to each item of an iterable (list, tuple etc.) and

returns a list of the results.

map() function takes two Parameters :

function : The function to execute for each item of given iterable.

iterable : It is an iterable which is to be mapped.

Returns : Returns a list of the results after applying the given function to each item of a given

iterable (list, tuple etc.)


Reduce:

The reduce() function is defined in the functools python [Link] reduce() function

receives two arguments, a function and an iterable. However, it doesn't return another
iterable,

instead it returns a single value.

Working:

1) Apply a function to the first two items in an iterable and generate a partial result.

2) The function is then called again with the result obtained in step 1 and the next value in the

sequence. This process keeps on repeating until there are items in the sequence.

3) The final returned result is returned and printed on console


Math Functions

The math module is a built-in module in Python that you can use for mathematical tasks.​
To use mathematical functions under this module, you have to import the module using​
import math

●​ fabs()​
The fabs() method returns the absolute value of a number as a float.​
Syntax:​
[Link](x)​
Example:​
[Link](-9) # returns 9.0
●​ sqrt()​
The sqrt() method returns the square root of a number. The number must be greater
than or equal to 0.​
Syntax:​
[Link](x)​
Example:​
[Link](9) # returns 3.0
●​ trunc()​
The trunc() method returns the truncated integer part of a number.​
Syntax:​
[Link](x)​
Example:​
[Link](2.77) # returns 2
●​ pow()​
The pow() method returns the value of x raised to power y.​
If x is negative and y is not an integer, it returns a ValueError.​
Syntax:​
[Link](x, y)​
Example:​
[Link](2, 3) # returns 8.0
●​ floor()​
The floor() method rounds a number DOWN to the nearest integer.​
Syntax:​
[Link](x)​
Example:​
[Link](2.8) # returns 2
●​ ceil()​
The ceil() method rounds a number UP to the nearest integer.​
Syntax:​
[Link](x)​
Example:​
[Link](2.3) # returns 3
●​ fmod()​
The fmod() method returns the remainder (modulo) of x/y.​
If y = 0, it returns a ValueError.​
Syntax:​
[Link](x, y)​
Example:​
[Link](20, 3) # returns 2.0
●​ fsum()​
The fsum() method returns the sum of all items in an iterable (tuples, arrays, lists,
etc.).​
Syntax:​
[Link](iterable)​
Example:​
[Link]([1, 2, 3, 4, 5]) # returns 15.0
●​ sin()​
The sin() method returns the sine of a number.​
Syntax:​
[Link](x)​
Example:​
[Link]([Link](0)) # returns 0.0
●​ cos()​
The cos() method returns the cosine of a number.​
Syntax:​
[Link](x)​
Example:​
[Link](0) # returns 1.0

—>print(round([Link]([Link](90)), 2))

●​ tan()​
The tan() method returns the tangent of a number.​
Syntax:​
[Link](x)​
Example:​
[Link](45) # returns 1.619
●​ exp()​
The exp() method returns E raised to the power of x (Ex).​
E is the base of the natural system of logarithms (approximately 2.71828).​
Syntax:​
[Link](x)

e = 2.718281828
Example:​
[Link](1) # returns 2.71828

●​ factorial():

The factorial of n is written as n!​


It means multiplication of all numbers from 1 to n​
Used in permutations, combinations, probability

Example :

import math

num = 5

print([Link](num))

●​ gcd():

GCD is the largest number that divides both numbers [Link] called HCF

Example:

gcd(20, 30)

Common factors: 1,2,5,10

Greatest = 10

Program:

import math

print([Link](20, 30))
Random Number Functions

Python has a built-in module that you can use to make random numbers.​
Random numbers are used for games, simulations, testing, security, and privacy applications.​
To use random functions under this module, you have to import the module using​
import random

1.​ random()​
The random() method returns a random floating number between 0 and 1.​
Syntax:​
[Link]()​
Example:​
[Link]() # returns 0.2815479193
2.​ randrange()​
The randrange() method returns a randomly selected element from the specified
range.​
It generates a random number between start and stop.​
Syntax:​
[Link](start, stop, step)​
start – Optional. An integer specifying at which position to start. Default is 0​
stop – Required. An integer specifying the end position​
step – Optional. An integer specifying the incrementation. Default is 1

Example:​
[Link](3, 9)

3.​ randint()​
The randint() method returns an integer number selected from the specified range.​
It generates a random number between start and end.​
Syntax:​
[Link](start, stop)​
Example:​
[Link](3, 9)
4.​ uniform()​
The uniform() method returns a random floating number between the two specified
numbers (both included).​
Syntax:​
[Link](a, b)​
Example:​
[Link](20, 60)
5.​ choice()​
The choice() method returns a randomly selected element from the specified
sequence.​
The sequence can be a string, a range, a list, a tuple, or any other kind of sequence.​
Syntax:​
[Link](sequence)​
Example:​
mylist = ["apple", "banana", "cherry"]​
[Link](mylist) # returns banana
6.​ sample()​
The sample() method returns a list with a random selection of a specified number of
items from a sequence.​
Syntax:​
[Link](sequence, k)​
Example:​
[Link](["apple", "banana", "cherry"], 2)
7.​ seed()​
The seed() method is used to initialize the random number generator.​
The random number generator needs a number to start with (a seed value), to be able
to generate a random number.​
By default the random number generator uses the current system time.​
Syntax:​
[Link](value)​
Example:​
[Link](10)​
[Link]()
Container
Containers are data structures that hold data values.

They support membership tests which means we can check whether a value exists in the

container or not.

Generally containers provide a way to access the contained objects and to iterate over them.

Examples of containers include tuple, list, set, dict, str

Iterable & Iterator

An iterable is an object that can be iterated upon. It can return an iterator object with the

purpose of traversing through all the elements of an iterable.

An iterable object implements __iter()__ which is expected to return an iterator object. The

iterator object uses the __next()__ method. Every time next() is called next element in the

iterator stream is returned. When there are no more elements available StopIteration

An exception is encountered. So any object that has a __next()__ method is called an iterator.

Python lists, tuples, dictionaries and sets are all examples of iterable objects
Generator

Python generators are an easy way of creating iterators. It generates values one at a time from
a given sequence instead of returning the entire sequence at once.

It is a special type of function which returns an iterator object.

In a generator function, a yield statement is used rather than a return statement.

The generator function cannot include the return keyword. If we include it then it will
terminate

the execution of the function.

The difference between yield and return is that once yield returns a value the function is

paused and the control is transferred to the [Link] variables and their states are
remembered between successive calls. In case of the return statement value is returned and

the execution of the function is terminated.

Methods like iter() and next() are implemented automatically in generator function

Simple generators can be easily created using generator expressions. Generator

expressions create anonymous generator functions like lambda.

The syntax for generator expression is similar to that of a list comprehension but the only

The difference is square brackets are replaced with round parentheses. Also list
comprehension

produces the entire list while the generator expression produces one item at a time which is

more memory efficient than list comprehension.

Decorator

Decorator is a very powerful and useful tool in Python as it allows us to wrap another
function in order to extend the behavior of the wrapped function without permanently
modifying it.

In Decorators functions are taken as the argument into another function and then called inside
the wrapper functi​ on.
Recursion:

A function calling itself

def fact(n):

if n == 1:

return 1

return n * fact(n-1)

Recursion for Fibonacci Series:

def fib(n):

if n <= 1:

return n

return fib(n-1) + fib(n-2)

print(fib(6)) # 8

Sum of a list using recursion

def sum_list(lst):

if len(lst) == 0:

return 0

return lst[0] + sum_list(lst[1:])

print(sum_list([1,2,3,4,5])) # 15

Recursion for String Reverse

def reverse_string(s):
if s == "":

return s

return reverse_string(s[1:]) + s[0]

print(reverse_string("hello")) # olleh

Recursion for Palindrome Check

def is_palindrome(s):

if len(s) <= 1:

return True

if s[0] != s[-1]:

return False

return is_palindrome(s[1:-1])

print(is_palindrome("madam")) # True

Tail Recursion

def factorial(n, result=1):

if n == 1:

return result

return factorial(n-1, result*n)


Exception Handling:

An error that occurs at runtime is also called an exception

When an exception occurs, Python will normally stop and generate an error message.

Python has many built-in exceptions that are raised when your program encounters an error.

When these exceptions occur, the Python interpreter stops the current process and passes it to
the calling process until it is handled. If not handled, the program will crash.

The BaseException class is the root of exception classes. All Python exception classes inherit
directly or indirectly from BaseException.

BaseException

Exception

StandardError

수 수 수 수 수
ArithmeticError EnvironmentError RuntimeError LookupError SyntaxError

수 수 수 수

ZeroDivisionError IOError,OSError IndexError,KeyError IndentationError ++

Syntax:

try:

#Some Code.... # statement(s)

except <Exception Type>:

#statement(s) block for Handling exceptions (if required)

except <Exception Type>:

#statement(s) block for Handling exceptions (if required)

except:
#statement(s) block for Handling exceptions (if required)

else:

#execute if no exception

finally:

# Some code #statement(s) (always executed)

Example:

try:

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

b=int(input("Enter a number :"))

k=a//b

# raises divide by zero exception if b=0

print(k)

except ZeroDivisionError:

#handles zerodivision exception

print("Can't divide by zero")

except SyntaxError:

print("Something wrong in the input")

except:

print("Something wrong in the input")

else:

print("No exceptions")

finally:

# this block is always executed regardless of exception generation.

print('This is always executed')


Output:

Can't divide by zero

This is always executed

Raising Exception:

In Python programming, exceptions are raised when errors occur at runtime. We can also
manually raise exceptions using the raise keyword.

The sole argument in raise indicates the exception to be raised. This must be either an
exception instance or an exception class (a class that derives from Exception).

We can optionally pass values to the exception to clarify why that exception was raised.

Syntax:

raise ExceptionClass("Some message ")

Example 1:

x=-1

if x < 0:

raise Exception("Sorry, no numbers below zero")

Example 2:

x = "hello"

if not( type(x) is int):

raise TypeError("Only integers are allowed")

Example 3:

try:

a = int(input("Enter a positive integer: "))


if a <= 0:

raise ValueError("That is not a positive number!")

except ValueError as ve:

print(ve)
OOPS Concepts:

OOPS stands for Object Oriented Programming System. It is a programming paradigm or


methodology, to design a program using classes and objects. OOPS treats every entity as an
object. The object is related to real-word entities such as book, house, pencil, [Link]
principles of object-oriented programming system are given below.

1) Class

2) Object

3) Inheritance

4) Polymorphism

5) Data Abstraction

6) Encapsulation

1) Class

variables(members,attributes,state)

function(methods,behaviour)

The class is a user-defined data structure. It is a logical entity that binds the data members
and methods into a single unit. Class is a blueprint or code template for object creation. Using
a class, you can create as many objects as you want.

For example: if you have an employee class, then it should contain an attributes like empID,
Ename, email id, age, salary, etc and methods like insertemp(),display() etc

Some points on Python class:

​ Classes are created by keyword class.


​ Attributes are the variables that belong to a class.
​ Attributes are always public and can be accessed using the dot (.) operator. Eg.:
[Link]

Syntax:

class ClassName:

""docstring to describe a new class ""

#statement suite (attributes & methods)


Example:

class Employee:

id=10

name = "Srijay"

def display (self):

print("ID: ",[Link], "\n Name: ", [Link])

2) Object

The object is an entity that has state and behavior. It may be any real-world object like the
mouse, keyboard, chair, table, pen, etc.

An object (instance) is an instantiation of a class. When class is defined, only the description
for the object is defined. We use the object of a class to perform actions.

For example: if you have an employee class, then el,e2 can be created as objects

An object consists of:

State:It is represented by the attributes of an object.

Behavior:It is represented by the methods of an object

Identity:It gives a unique name to an object and enables one object to interact with other
objects.

In Python we create instances in the following manner

<object-name> = <class-name>(<arguments>)

Example:

emp = Employee()

[Link]()

Output:

ID: 10

Name: Srijay
Constructors:

A constructor is a special method used to create and initialize an object of a class. This
method is defined in the class.

●​ The constructor is executed automatically at the time of object creation


●​ The primary use of a constructor is to declare and initiative data member instance
variables of a class. The constructor contains a collection of statements
(i.e,instructions) that executes at the time of object creation to initialize the attributes
of an object
●​ For every object, the constructor will be executed only once.
●​ Python will provide a default constructor if no constructor is defined.
●​ In Python, the constructor does not return any value.

In Python. Object creation is divided into two parts in Object Creation and Object
initialization

●​ Internally, the new is the method that creates the object.


●​ And, using the init() method we can implement constructor to initialize the object.

Syntax:

def __init__(self):

#body of the constructor

Where.

def: The keyword is used to define function.

__init__() Method: It is a reserved method. This method gets called as soon as an object of a
class is instantiated.

The __init__() method arguments are optional. We can define a constructor with any number
of arguments.

self. The first argument self refers to the current object. It binds the instance to the init
method. It's usually named self to follow the naming convention
Example

class Student:

def __init__(self, name): #constructor initialize instance variable

print("Inside Constructor")

[Link] name

print(All variables initialized)

def show(self): #instance Method

print('Hello, my name is, self name)

s1=Student('Emma') #create object asing contractor

[Link]()

Output:

Inside Constructor

All variables initialized

Hello, my name is Emma

Types of Constructors
In Python, There are three types of constructors

1.​ Default Constructor


2.​ Non-parametrized constructor
3.​ Parameterized constructor

Default Constructor:

Python will provide a default constructor if no constructor is defined. It does not perform any
task but initializes the objects. It is an empty constructor without a body.

If you do not implement any constructor in your class or forget to declare it, the Python
inserts a default constructor into your code on your behalf. This constructor is known as the
default constructor
Example:

class Employee:

def display(self):

print('Inside Display)

emp=Employee()

[Link]()

Non-Parametrized Constructor:

A constructor without any arguments is called a non-parameterized constructor. This type of


constructor is used to initialize each object with default [Link] constructor doesn't accept
the arguments during object creation. Instead, it initializes every object with the same set of
values.

Example

class Company:

def __init__ (self):

[Link]="PYnative"

[Link]="ABC Street"

def show(self):

print("Name:,[Link]. "Address", [Link])

emp=Company()

[Link]()
Parameterized Constructor:

A constructor with defined parameters or arguments is called a parameterized constructor. We


can pass different values to each object at the time of creation using a parameterized
constructor

The first parameter to the constructor is self that is a reference to the being constructed, and
the rest of the arguments are provided by the programmer. A parameterized constructor can
have any number of arguments.

For example, consider a company that contains thousands of employees. In this case, while
creating each employee object, we need to pass a different name, age, and salary, In such
cases. use the parameterized constructor.

Example: class Employee:

def __init__ (self, name, age, salary)

[Link]=name

[Link] age

[Link]=salary

def show(self):

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

el=Employee(‘Srijay’, 23, 7500)

[Link]()

e2=Employee(‘Srisha', 25, 8500)

[Link]()

Output

Srijay 23 7500

Srisha 25 8500
Constructor With Default Values:

Python allows us to define a constructor with default values. The default value will be used if
we do not pass arguments to the constructor at the time of object creation

Example

def init (self, name, age 12, classroom-7):

[Link]=name

[Link]=age

[Link]=classroom

el=Employee("Srijay')

Self Keyword

The class contains instance variables and methods. Whenever we define instance methods
for a class, we use self as the first parameter. Using self, we can access the instance variable
and instance method of the object.

The first argument self refers to the current object.

Whenever we call an instance method through an object, the Python compiler implicitly
passes object reference as the first argument commonly known as self.
Data Encapsulation:

Data hiding is also known as information hiding or Data Encapsulation.

Data hiding in python is a technique of preventing methods and variables of a class from
being accessed directly outside of the class in which the methods and variables are initialized.

Data hiding increases security.

It is a method used in object-oriented programming (OOP) to hide information/ data within a


class. Data members are hidden within a class. It guarantees restricted access to the data to
class members while maintaining object integrity. Data hiding includes a process of
combining the data and functions into a single unit to conceal data within a class by
restricting direct access to the data from outside the class.

The use of data hiding also helps in reducing the complexity of the program by reducing
interdependencies.

Data hiding in python can be achieved by declaring class members as private by putting a
double underscore () as prefix before the member name.

Syntax: __ variableName

Private members are accessible only within the class, and we can't access them directly from
the class objects.

Public methods can access private members in a class

Example:

class add:

c=0

def sum(self, x,y):

self._c += x+y
print ("SUM=",self._c)

obj = add()

[Link](5.6)

[Link](10.20)

#declaring private member of class

#accessing private member

Output

SUM=11

SUM=30
Data Abstraction:

Abstraction is used to hide the internal functionality of the function from the users. The users
only interact with the basic implementation of the function, but inner working is hidden.
Users are familiar with "what function does" but they don't know "how it does."

Syntax:

from abc import ABC, abstractmethod

class abs className(ABC):

@abstractmethod

def abs_methodNamel(self):

pass

def abs_methodName2(self):

#abstract method

#abstract method

pass

Example

from abe import ABC, abstractmethod

class Polygon(ABC):

def display(self):

print("I am a Shape having sides")

@abstractmethod

def sides(self):

pass

#common method

#abstract method

class Triangle(Polygon):

def sides(self):
print("Triangle has 3 sides")

#code for abstract method

class Pentagon(Polygon):

def sides(self):

print("Pentagon has 5 sides")

class square (Polygon):

def sides(self):

print("I have 4 sides")

t = Triangle()

[Link]()

[Link]()

s = square()

[Link]()

[Link]()

p = Pentagon()

[Link]()

[Link]()

Output:

I am a Shape having sides

Triangle has 3 sides

I am a Shape having sides

I have 4 sides

I am a Shape having sides

Pentagon has 5 sides


Polymorphism:

Polymorphism is a fundamental concept in object-oriented programming (OOP) that allows


objects of different classes to be treated as objects of a common superclass. It enables a single
interface to represent different types of objects. Polymorphism is derived from two Greek
words: "poly" meaning many, and "morph" meaning forms. Thus, polymorphism means the
ability to take many forms.

In Python, polymorphism is achieved through method overriding, method overloading, and


operator overloading. Here's a detailed explanation of each:

Polymorphism, in the context of object-oriented programming, can be broadly categorized


into two main types:

1.​ Compile-time Polymorphism (Static Polymorphism,overloading)


2.​ Run-time Polymorphism (Dynamic Polymorphism,overriding)

1. Compile-time Polymorphism (Static Polymorphism)

Compile-time polymorphism is resolved during the compilation phase. It is achieved through


method overloading and operator overloading.

●​ Method Overloading: Multiple methods with the same name but different parameters.
●​ Operator Overloading: Overloading operators to work with user-defined types.

Example in Python (using default arguments for method overloading):

class Calculator:

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

return a + b + c

# Creating an instance of the class

calc = Calculator()

# Calling the add method with different numbers of arguments

print([Link](2)) # Output: 2

print([Link](2, 3)) # Output: 5

print([Link](2, 3, 4)) # Output: 9


2. Run-time Polymorphism (Dynamic Polymorphism)

Run-time polymorphism is resolved during the execution phase. It is achieved through


method overriding.

●​ Method Overriding: A subclass provides a specific implementation of a method that is


already defined in its superclass.

Example:

class Vehicle:

def start(self):

print( "Vehicle is starting")

class Car(Vehicle):

def start(self):

print("Car is starting")

super().start()

class Bicycle(Vehicle):

def start(self):

print("Bicycle is starting")

# Creating instances of the classes

car = Car()

bicycle = Bicycle()

# Calling the start method

[Link]() # Output: Car is starting

[Link]() # Output: Bicycle is starting


Inheritance:

Inheritance is the capability of one class to derive or inherit the properties from another
[Link] provides the reusability of a [Link] allows us to add more features to a class without
modifying it.

Base Class

Parent class is the class being inherited from, also called base class (or) superclass.

Child class

A child class is the class that inherits from another class, also called derived class (or)
[Link] inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its specific
implementation to the functions of the parent class.

Derived Class

In python, a Derived class can inherit Base class by just mentioning the base in the bracket
after the derived class name.

Syntax:

class BaseClass:

# Body of base class

class DerivedClass(BaseClass):

# Body of derived class

Types of Inheritance

In Python, based upon the number of child and parent classes involved, there are five types of
inheritance.

a) Single inheritance

b) Multiple Inheritance

c) Multilevel inheritance

d) Hierarchical Inheritance

e) Hybrid Inheritance
a)single inheritance
In single inheritance, a child class inherits from a single-parent class. Here is one child class
and one parent class

Syntax:class ParentClass:
#Body of base class
class ChildClass(ParentClass):
#Body of derived class
Example:class parent:
def func1(self):
print("Hello Parent")
class child(parent):
def func2(self):
print("Hello Child")
test=child()
[Link]()
test.func2()
Output:
Hello Parent
Hello Child

Example 2:
class Person:
def __init__ (self, f_name, Iname):
[Link]=f_name
[Link]=Iname
def printname(sell):
print([Link], [Link])
class Student(Person):
def __init__ (self, f_name, Iname, cgpa):
super().__ init__ (f_name, Iname)
[Link]=cgpa
def welcome(self):
print("Hi", self firstname, self lastname.". Your CGPA is", [Link])
stObj=Student("RAM", "KUMAR", 85)
[Link]()

Output:
HI RAM KUMAR! Your CGPA is 85

b) Multi-Level inheritance

Multi-level inheritance is achieved when a derived claw inherits the mother derived class.
There is no limit on the number of levels up to which the multi-level inheritance is archived
in python.

While inheriting the methods and members of both base class and derived class will be
inherited to the newly derived class.

For Example, If we have three classes A, B, and C then A is the superclass (Parent), B is the
subclass (child), and C is the subclass of B (Grandchild)

Syntax:
class class _l:
<class-suite>
class class2(class_1):
<class suite>
class class3(class2):
<class suite>
Example:
class grandparent:
def func1 (self):
print "Hello Grandparent")
class parent(grandparent):
def func2(self):
print "Hello Parent")
class child(parent):
def func3(self):
print Hello Child")
test=child()
test.fune1()
test.func2()
test.func3()

Output:
Hello Grandparent
Hello Parent
Hello Child

Example 2:
class Parent:
def __init__ (self, name):
[Link]=name
def getName(self):
return [Link]
class Child(Parent):
def init (self, name, age):
Parent. __init__ ([Link])
[Link]=age
def getAge(self):
retum [Link]
class Grandchild(Child):
def init (self, name, age, location):
Child.__init__ (self, name, age)
[Link]=location
def getLocation(self):
return [Link]
gc=Grandchild("Srinivas" 24, "Hyderabad")
print([Link](),[Link](), [Link]())

Output:
Srinivas 24 Hyderabad
class OTP_CEO:
def __init__(self,name):
[Link]=name
def show_name(self):
print("OTP CEO name is:",[Link])
class OTP_Manager:
def __init__(self,name):
[Link]=name
def show_name(self):
print("OTP manager name is:",[Link])
class emp1(OTP_CEO):
def __init__(self,name,salary):
OTP_CEO.__init__(self,name)
[Link]=salary
def show_salary(self):
print("employee salary is:",[Link])
class emp2(emp1,OTP_Manager):
def __init__(self,id):
OTP_Manager.__init__(self,name)
[Link]=id
def show_idproof(self):
print("employee id proof is:",[Link])
c) Multiple Inheritance
Python provides us the flexibility to inherit multiple base classes in the child class.A class can
be derived from more than one base class in python ,similar to C++.This is called multiple
inheritance.

Syntax:

class Basel:
<class-suite>
class Base2:
<class-suite>

class BaseN:
<class-suite>

class Derived(Basel, Base2,BaseN):


<class-suite>

Example:

class parent1:
del func1(self):
print("Hello Parent1")
class parent2:
def func2(self):
print("Hello Parent2")
class parent3:
def func2(self):
print("Hello Parent.3")
class child(parent1, parent2, parent3):
def func3(self):
print("Hello Child")
test=child()
test.func1()
test.func2()
test.func3()

Output:
Hello Parent1
Hello Parent2
Hello Child

d)Hierarchical Inheritance:

When more than one derived class is created from a single base this type of inheritance is
called hierarchical inheritance.

Example:

class parent:
def func1(self):
print("Hello Parent")
class child1(parent):
def func2(self)
print "Hello Child")
class child2(parent):
def func3(self):
print Hello Child2")

test1=child1()
test2=child2()
test1.func2()
test2.func3()

Output:

Hello Parent

Hello Child1

Hello Parent

Hello Child2

e)Hybrid Inheritance

Hybrid inheritance satisfies more than one form of inheritance Hybrid Inheritance is the
mixture of two or more different types of inheritance. Here we can have many to many
relations between parent classes and child classes with multiple levels Hybrid Inheritance is
the combination of simple, multiple multilevel and hierarchical inheritance. This type of
inheritance is very helpful if we want to use concepts of inheritance without any limitations
according to our requirements
Example:

class parent1:
def func1(self):
print("Hello Parent1”)
class parent2:
def func2(self):
print(“Hello Parent2”)
class child(parent1):
def func3(self):
print(“Hello Child”)
class child2(child1, porent2)
def func4(self)
print("Hello Child2")
test1=child1()
test2= child2()
test1.func1()
test1.func2()
test2.func1()
test2.func2()
test2.func3()
test2.func4()

Output:
Hello Parent1
Hello Child1
Hello Parent1
Hello Parent2
Hello Child1
Hello Child2

class len:
def var(self,*a):
if len(a)==1:
print("one argument",a[0])
if len(a)==2:
print("two arguments",a[0],a[1])
else:
print("invalid")
if len(a)==3:
print("three arguments",a[0],a[1],a[2])
else:
print("invalid")
if len(a)>3:
print(" enter only 3 arguments")

You might also like