Python Full Notes
Python Full Notes
Area Example
Example:
Program:
[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.
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.
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
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.
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
2. Cannot be used as variable names, function names, class names, etc.
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
○ Digits (0–9)
○ Underscore _
○ A–Z
○ a–z
○ _ (underscore)
Python keywords (like if, class, def, return) are reserved words and cannot be used as
identifiers.
Example:
4: Case-Sensitive
5: No Length Limit
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!
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
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
// Floor Division(int) 5 // 2 2
% Modulus(remainder) 5%2 1
** Exponentiation 2 ** 3 8
2. Comparison Operators
== Equal to 5 == 5 True
= 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
5. Identity Operators
is True if same x is y
object
7. Bitwise Operators
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
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:
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
print("Good attendance.")
max_balance = 1000
if balance == 0:
print("Account is empty.")
5)Nested if statement
1)balance = 1000
withdraw_amount = 500
3)marks = 85
if marks >= 50:
print("You passed.")
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")
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
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’
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
String Methods
1) capitalize()
Python capitalize() method converts the first character of the string into uppercase without
altering the whole string.
Syntax: [Link]()
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]()
5) count()
The count() method returns the number of occurrences of a substring in the given string.
6) find()
The find() method returns the index of the first occurrence of the substring (if found). If not
found, it returns-1.
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)
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.
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: {}
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’]
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]
1) len()
Python list method len() returns the number of elements in the list!
Syntax:len(list)
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)
3) insert()
The insert() method inserts an element to the list at the specified index.
Syntax:[Link](index, element)
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.
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)
Slicing a tuple:
We can access a range of items in a tuple by using the slicing operator
Eg: t1[2:5]
t1[2:]
Tuple Methods
1) count()
The count() method returns the number of times the specified element appears in the tuple.
Syntax:[Link](element)
2) index()
The index() method returns the index of the specified element in the tuple.
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])
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.
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
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.
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.
empty_frozen_set = frozenset()
frozen_set = frozenset("hello")
Frozen sets support various set operations, but since they are immutable, you cannot use
methods that modify the set (like add, remove, etc.).
# Union
union_set = [Link](set2)
intersection_set = [Link](set2)
# Difference
difference_set = [Link](set2)
# Symmetric Difference
symmetric_difference_set = set1.symmetric_difference(set2)
Use Cases
Dictionary Keys: Since frozen sets are hashable, they can be used as keys in dictionaries.
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]}
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]()
2) items()
The items() method returns a view object that displays a list of dictionary's (key, value) tuple
pairs.
Syntax:[Link]()
3) len()
The len() method returns the number of items in a dictionary.
Syntax:len(dict)
Syntax:[Link]()
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)
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)
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]()
8) clear()
The clear() method removes all items from the dictionary.
Syntax:[Link]()
Syntax:[Link]()
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():
Example:
a = "Hello World"
b = ("apple", "banana", "cherry")
c = 33
type(a)
type(b)
type(c)
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.
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()
3)ord()
4)str()
5)list():
6)tuple():
8)chr():
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:
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]
def greet():
print(“welcome to python”)
def greet():
print(greet())
greet("John", 30)
4)Function with parameters and with return values:
result = a + b
return result
num1 = 5
num2 = 7
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
d) Keyword arguments.
e) Default arguments.
f) Variable-length arguments
a)Formal arguments
b)actual 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:
print(a+b)
add(50, 10)
add(50, 10, 4)
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)
# Output 45
add(a = 10)
# Output 25
add (c = 5, a = 5 )
# Output 15
Example:
message("John", "Wilson")
message("John", last_nm="Wilson")
c) Default arguments
Default arguments are values that are provided while defining functions.
If we provide a value to the default arguments during function calls, it overrides the default
value.
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
#3 is assigned to a, 4 is assigned to b.
# Output:9
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
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
*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.
We can rename it to anything as long as it is preceded by a single asterisk (*). It's best
**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.
We can rename it to anything as long as it is preceded by a double asterisk (**). It's best
Lambda
Lambda functions can have any number of arguments but only one expression. The
We use lambda functions when we require a nameless function for a short period of time.
Filter:
Filter function filters the original iterable and passes the items that returns True for the
function provided to filter
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 : Returns a list of the results after applying the given function to each item of a given
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,
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.
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():
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)
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.
An iterable is an object that can be iterated upon. It can return an iterator object with the
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.
The generator function cannot include the return keyword. If we include it then it will
terminate
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
Methods like iter() and next() are implemented automatically in generator function
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
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:
def fact(n):
if n == 1:
return 1
return n * fact(n-1)
def fib(n):
if n <= 1:
return n
print(fib(6)) # 8
def sum_list(lst):
if len(lst) == 0:
return 0
print(sum_list([1,2,3,4,5])) # 15
def reverse_string(s):
if s == "":
return s
print(reverse_string("hello")) # olleh
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
if n == 1:
return result
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
수 수 수 수
Syntax:
try:
except:
#statement(s) block for Handling exceptions (if required)
else:
#execute if no exception
finally:
Example:
try:
k=a//b
print(k)
except ZeroDivisionError:
except SyntaxError:
except:
else:
print("No exceptions")
finally:
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:
Example 1:
x=-1
if x < 0:
Example 2:
x = "hello"
Example 3:
try:
print(ve)
OOPS Concepts:
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
Syntax:
class ClassName:
class Employee:
id=10
name = "Srijay"
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
Identity:It gives a unique name to an object and enables one object to interact with other
objects.
<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.
In Python. Object creation is divided into two parts in Object Creation and Object
initialization
Syntax:
def __init__(self):
Where.
__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:
print("Inside Constructor")
[Link] name
[Link]()
Output:
Inside Constructor
Types of Constructors
In Python, There are three types of constructors
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:
Example
class Company:
[Link]="PYnative"
[Link]="ABC Street"
def show(self):
emp=Company()
[Link]()
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.
[Link]=name
[Link] age
[Link]=salary
def show(self):
[Link]()
[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
[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.
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 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.
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.
Example:
class add:
c=0
self._c += x+y
print ("SUM=",self._c)
obj = add()
[Link](5.6)
[Link](10.20)
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:
@abstractmethod
def abs_methodNamel(self):
pass
def abs_methodName2(self):
#abstract method
#abstract method
pass
Example
class Polygon(ABC):
def display(self):
@abstractmethod
def sides(self):
pass
#common method
#abstract method
class Triangle(Polygon):
def sides(self):
print("Triangle has 3 sides")
class Pentagon(Polygon):
def sides(self):
def sides(self):
t = Triangle()
[Link]()
[Link]()
s = square()
[Link]()
[Link]()
p = Pentagon()
[Link]()
[Link]()
Output:
I have 4 sides
● Method Overloading: Multiple methods with the same name but different parameters.
● Operator Overloading: Overloading operators to work with user-defined types.
class Calculator:
return a + b + c
calc = Calculator()
print([Link](2)) # Output: 2
Example:
class Vehicle:
def start(self):
class Car(Vehicle):
def start(self):
print("Car is starting")
super().start()
class Bicycle(Vehicle):
def start(self):
print("Bicycle is starting")
car = Car()
bicycle = Bicycle()
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:
class DerivedClass(BaseClass):
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>
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")