Python Notes
Python Notes
Python is a widely used programming language. It was created by Guido van Rossum
and released in 1991.
❖ Building websites
❖ Developing software and applications
❖ Performing mathematical calculations
❖ Automating tasks and system operations (scripting)
A. Algorithm
An algorithm is a step-by-step procedure used to solve a problem or perform a task. It consists
of a finite number of clear and logical instructions that lead to the desired result.
1. Start
2. Input two numbers
3. Add the numbers
4. Display the result
5. Stop
B. Flowchart
A flowchart is a graphical representation of an algorithm. It uses different symbols and arrows
to show the sequence of steps in a process, making it easier to understand the logic of a
program.
Common symbols:
❖ Oval: Start/Stop
❖ Parallelogram: Input/Output
❖ Rectangle: Process
❖ Diamond: Decision
C. Pseudocode
Pseudocode is an informal way of writing a program using simple English-like statements. It
describes the logic of the program without following the strict syntax of a programming
language.
Example:
START
READ A, B
SUM = A + B
PRINT SUM
STOP
QNO.2 Variables
A variable is a named memory location used to store data in a program. Variables allow
programmers to store, modify, and access values during program execution.
Syntax:
variable_name = value
Data types in Python define the type of value stored in a variable and determine the
operations that can be performed on that data.
A. Numeric Data Types
a. String (str)
A string is a sequence of characters used to store text data. Strings can be enclosed in single
quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).
Example
s = “Welcome to Python”
print(s)
b. List
A list is an ordered and mutable collection of elements. A list can contain elements of different
data types and is enclosed within square brackets [ ].
Example
print(fruits)
c. Tuple
A tuple is an ordered but immutable collection of elements. It is similar to a list, but its elements
cannot be modified after creation. Tuples are enclosed within parentheses ( ).
Example
C. Boolean (bool)
The Boolean data type represents logical values and can have only two possible values:
True or False.
Example
print(10 > 9)
D. Set
A set is an unordered collection of unique elements. Duplicate values are not allowed.
Example
numbers = {1, 2, 3, 4}
E. Dictionary (dict)
A dictionary stores data in the form of key-value pairs. It is enclosed within curly braces
{ }.
Example
student = {"name": "Ali", "age": 20, "mark”}
QNO.4 Operators
Operators are symbols used to perform various operations on data. Python provides arithmetic,
comparison, logical, assignment, and membership operators, which help in performing
calculations, making decisions, and manipulating data efficiently.
Arithmetic operators are used to perform mathematical calculations on numeric values. They
are commonly used for addition, subtraction, multiplication, division, and other mathematical
operations.
Syntax
x+y
Example
x = 10
y=3
print(x + y)
Output
13
Syntax
x-y
Example
x = 10
y=3
print(x - y)
Output
7
Syntax
x*y
Example
x = 10
y=3
print(x * y)
Output
30
d. Division Operator (/)
The division operator divides one number by another and always returns a
floating-point (decimal) value.
Syntax
x/y
Example
x = 10
y=3
print(x / y)
Output
3.3333333333333335
e. Modulus Operator (%)
The modulus operator returns the remainder after division.
Syntax
x%y
Example
x = 10
y=3
print(x % y)
Output
1
Syntax
x ** y
Example
x = 10
y=3
print(x ** y)
Output
1000
The floor division operator returns only the integer quotient and removes the decimal
part.
Syntax
x // y
Example
x = 10
y=3
print(x // y)
Output
3
Assignment operators are used to assign values to variables. They can also perform a
mathematical operation and store the result back into the same variable.
Assignment operators make code shorter, easier to read, and more efficient.
Output
5
Syntax
x += y
Equivalent to:
x=x+y
Example
x = 10
x += 5
print(x)
Output
15
c. Subtract and Assign Operator (-=)
Subtracts a value from the variable and stores the result back.
Syntax
x -= y
Equivalent to
x=x-y
Example
x = 10
x -= 3
print(x)
Output
7
Syntax
x *= y
Equivalent to:
x=x*y
Example
x = 10
x *= 3
print(x)
Output
30
Syntax
x /= y
Equivalent to:
x=x/y
Example
x = 10
x /= 2
print(x)
Output
5.0
Syntax
x %= y
Equivalent to:
x=x%y
Example
x = 10
x %= 3
print(x)
Output
1
Syntax
x //= y
Equivalent to:
x = x // y
Example
x = 10
x //= 3
print(x)
Output
3
Syntax
x **= y
Equivalent to:
x = x ** y
Example
x=2
x **= 3
print(x)
Output
8
Example
a = 13
b = 33
print(a > b)
Output
False
Comparison operators
Operator Name Description Examples
Example
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output
False
True
False
True
False
True
D.Logical Operators
b. Logical OR (or)
Returns True if at least one condition is True
QNO.5 String
A string is a sequence of characters used to store text data in Python. Python provides many
built-in string methods that help in manipulating and processing strings efficiently.
Example
s = “python”
print([Link]())
Output: PYTHON
b. lower()
Example
s = “PYTHON”
print([Link]())
Output: python
c. strip()
Example
s = “Python”
print([Link]())
Output: Python
d. replace()
Example
s = “I like Java”
print([Link](“Java”, “Python”))
Output: I like Python
e. split()
Example:
s = "Apple,Banana,Mango"
print([Link](","))
f. join()
Example:
Output: Python-Java-C++
g. find()
Example:
s = "Welcome to Python"
print([Link]("Python"))
Output: 11
h. count()
Example:
Output: 2
i. startswith()
Example:
s = "Python Programming"
print([Link]("Python"))
Output: True
j. endswith()
Example:
s = "Python Programming"
print([Link]("Programming"))
Output: True
k. isalpha()
Example:
s = "Python"
print([Link]())
Output: True
[Link]()
The len() function returns the total number of characters in a string, including spaces.
Example
s = “Python”
print(len(s))
Output
6
Syntax:
string[start:end]
We can extract characters from a specific range by specifying the start and end indices.
Example
b = “Hello, World!”
print(b[2:5])
Output:
llo
If the start index is omitted, slicing begins from the first character.
Example
b = "Hello, World!"
print(b[:5])
Output:
Hello
If the end index is omitted, slicing continues to the end of the string.
Example
b = "Hello, World!"
print(b[2:])
Output:
llo, World!
d. Negative Indexing
b = "Hello, World!"
print(b[-5:-2])
Output:
orl
Here:
❖ -5 refers to 'o'
❖ -2 refers to 'd' (not included)
In Python, conditional statements are implemented using the keywords if, else, and elif. They
help in solving real-world problems such as checking eligibility, validating user input, grading
students, and comparing values.
For example, a program can check whether a student has passed or failed based on marks
obtained.
The if statement is the simplest form of decision-making statement. It executes a block of code
only when the given condition is true.
Syntax:
if condition:
Statements
Example
age = 20
Output:
B. if-else Statement
The if-else statement is used when there are two possible outcomes. One block executes if the
condition is true, and another block executes if the condition is false.
Syntax:
if condition:
statements
else:
statements
Example:
num = 7
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")
Output:
Odd Number
C. if-elif-else Statement
When multiple conditions need to be checked, the if-elif-else statement is used. Python
evaluates conditions from top to bottom and executes the first condition that is true.
Syntax:
if condition1:
statements
elif condition2:
statements
elif condition3:
statements
else:
statements
Example:
marks = 82
Output:
Grade B
D. Nested if Statement
A nested if statement means placing one if statement inside another if statement. It is used
when a second condition needs to be checked only if the first condition is true.
Syntax:
if condition1:
if condition2:
statements
Example
age = 22
citizen = True
Eligible to Vote
In Python, loops are used when a task needs to be performed multiple times, such as printing
numbers, processing data, or traversing a collection of items.
a. for Loop
The for loop is used to iterate over a sequence such as a string, list, tuple, set, dictionary, or a
range of numbers. It executes a block of code once for each item in the sequence.
Syntax:
Example:
1
2
3
4
5
b. while Loop
The while loop repeatedly executes a block of code as long as a specified condition remains
true. The condition is checked before each iteration.
Syntax:
while condition:
statements
Example:
i=1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
C. Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Print each adjective for every fruit:
for x in adj:
for y in fruits:
print(x, y)
a. break Statement
Example:
Output:
1
2
3
b. continue Statement
The continue statement skips the current iteration of a loop and moves to the next iteration
without terminating the loop.
Example:
Output:
1
2
4
5
c. pass Statement
The pass statement does nothing. It acts as a placeholder when a statement is syntactically
required but no action needs to be performed.
Example:
if i == 3:
pass
print(i)
Output:
Example:
Output:
1
2
3
4
5
b.while Loop
A while loop executes a block of code repeatedly as long as a specified condition is true. It is
generally used when the number of iterations is not known beforehand.
Example:
i=1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Example Comparison
for Loop:
for i in range(5):
print(i)
while Loop:
i=0
while i < 5:
print(i)
i += 1
Both produce:
0
1
2
3
4
A function executes only when it is called. It can also return a value as a result.
Advantages of Functions
❖ Reduce code repetition.
❖ Improve code readability and organization.
❖ Make programs easier to test and maintain.
❖ Allow code reuse in different parts of a program.
A.Creating a Function
In Python, a function is created using the def keyword followed by the function name and
parentheses.
Syntax:
def function_name():
statements
Example:
def my_function():
print("Hello from a function")
In the above example, my_function() is a function that prints a message when called.
[Link] a Function
A function does not execute automatically after it is defined. To execute it, we must call the
function using its name followed by parentheses.
Example:
def my_function():
print("Hello from a function")
my_function()
Output:
def my_function():
print("Hello from a function")
my_function()
my_function()
my_function()
Output:
Syntax
range(start, stop, step)
Where:
Example:
x = range(10)
for i in x:
print(i)
Output:
0
1
2
3
4
5
6
7
8
9
Example:
Output:
3
4
5
6
7
8
9
Example:
Output:
3
5
7
9
Output:
2
4
6
8
10
Before using the math module, it must be imported into the program.
Syntax:
import math
a. [Link]()
Example:
import math
print([Link](64))
Output:
8.0
b. [Link]()
Example:
import math
print([Link](4.2))
Output:
c. [Link]()
Example:
import math
print([Link](4.8))
Output:
d. [Link]()
Example:
import math
print([Link](2, 3))
Output:
8.0
e. [Link]()
import math
print([Link](5))
Output:
120
f. [Link]
Example:
import math
print([Link])
Output:
3.141592653589793
Syntax:
import random
a. random()
Example:
import random
print([Link]())
Possible Output:
0.7345
b. randint()
Example:
import random
print([Link](1, 10))
Possible Output:
c. randrange()
Example:
import random
print([Link](1, 10))
Possible Output:
d. choice()
Example:
import random
Possible Output:
Banana
e. shuffle()
Example:
import random
numbers = [1, 2, 3, 4, 5]
[Link](numbers)
print(numbers)
Possible Output:
[3, 1, 5, 2, 4]
Example:
Output:
[Link] of Lists
a. Ordered
Lists are ordered, which means the items have a fixed position. Each item can be accessed
using its index.
b. Changeable (Mutable)
Lists are mutable, meaning their elements can be modified after creation.
[Link] Length
The len() function returns the number of items in a list.
Example:
Output:
Example:
f. Type of a List
The type() function is used to determine the data type of a list.
Example:
Output:
<class 'list'>
[Link] a List Using list() Constructor
Lists can also be created using the list() constructor.
Example:
Output:
Output:
Output:
['apple', 'mango']
● List
● Tuple
● Set
● Dictionary
Example:
Output:
Characteristics of Tuples
a. Ordered
Tuples are ordered, which means items have a fixed position and can be accessed using
indexes.
b. Unchangeable (Immutable)
d. Tuple Length
The len() function returns the number of items in a tuple.
Example:
Output:
Example:
t = ("apple",)
print(type(t))
Output:
<class 'tuple'>
Example:
Output:
banana
QNO.14. Set
Syntax
[Link](set2)
or
set1 | set2
Example
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print([Link](B))
Output
{1, 2, 3, 4, 5, 6}
. Intersection Operation
B
(intersection() or &)
The intersection of two sets contains only the elements that are
common to both sets.
Syntax
[Link](set2)
or
Example
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print([Link](B))
Output
{3, 4}
c. Difference Operation
(difference() or -)
The difference operation returns elements that are present in the
first set but not in the second set.
Syntax
[Link](set2)
or
set1 - set2
Example
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print([Link](B))
Output
{1, 2}
Another Example
print([Link](A))
Output
{5, 6}
d. Symmetric Difference Operation
(symmetric_difference() or ^)
The symmetric difference returns elements that are in either set but
not in both.
Syntax
set1.symmetric_difference(set2)
or
set1 ^ set2
Example
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A.symmetric_difference(B))
Output
{1, 2, 5, 6}
QNO.15 Type Casting
Type Casting is the process of converting one data type into another data type.
Type casting is useful when we need to perform operations on different data types
x = 10 # int
y = 2.5 # float
z = x + y
print(z)
Example
x = “10”
y = int(x)
print(y)
[Link]
Example
student = {
"name": "Ali",
"age": 20,
"course": "Python"
[Link] of Dictionaries
❖Ordered (Python 3.7 and later)
❖Mutable (Changeable) – Items can be added, updated, or removed.
❖Keys must be unique.
❖Values can be of any data type.
❖Items are accessed using their keys.
Syntax
key in dictionary
Example
student = {
"name": "Ali",
"age": 20,
"course": "Python"
print("name" in student)
Output
True
Example 2
print("address" in student)
Output
False
❖Because
❖Returns True if the key exists in the dictionary.
❖Returns False if the key does not exist.
Features of OOP
1. Modular
● Student Class
● Teacher Class
● Course Class
● Library Class
2. Maintainable
3. Reusable
4. Scalable
[Link]
A Class is a blueprint or template used to create objects.
Example
● Number of rooms
● Doors
● Windows
● Kitchen
Python Syntax
class Dog:
Pass
[Link]
An Object is an actual instance created from a class.
Example
Another example:
● Class → Smartphone
● Objects → Samsung Phone, iPhone, OnePlus Phone.
Student Attributes
● Name
● Age
● Roll Number
Car Attributes
● Color
● Model
● Speed
● Brand
● Battery
● Storage
● Color
Methods
Methods are the actions performed by an object.
Student Methods
● study()
● take_exam()
Car Methods
● start()
● stop()
● brake()
● call()
● message()
● take_photo()
● internet()
name = "Ali"
def display(self):
print("Hello")
Creating an Object
s1 = Student()
Here:
Second Example
class Student:
name = "Ali"
age = 20
def study(self):
print("Student is studying")
def take_exam(self):
print("Student is taking exam")
s1 = Student()
print([Link])
print([Link])
[Link]()
s1.take_exam()
Output
Ali
20
Student is studying
1.Encapsulation
2.Abstraction
3.Inheritance
4.Polymorphism
a. Encapsulation
Encapsulation means wrapping data (variables) and methods
(functions) into a single unit called a class and hiding data from
direct access.
Example
b. Abstraction
Abstraction means showing only important information and hiding
unnecessary details.
Example
When you drive a car, you press the accelerator and brake, but you
don't need to know how the engine works internally.
c. Inheritance
Inheritance means one class acquires the properties and methods of
another class.
Example
● Parent: Animal
● Child: Dog
d. Polymorphism
Polymorphism means one thing having many forms.
Example
A person can be:
● Teacher
● Father
● Friend
[Link] is Inheritance?
Inheritance is an Object-Oriented Programming (OOP) concept where
one class (child class) acquires the properties and methods of
another class (parent class). It helps in code reusability and
reduces duplication.
Advantages
● Code reusability
● Easy maintenance
● Better organization of code
● Supports hierarchical relationships
Types of Inheritance
1.Single Inheritance
2.Multiple Inheritance
3.Multilevel Inheritance
4.Hierarchical Inheritance
5.Hybrid Inheritance
a. Single Inheritance
Single inheritance occurs when one child class inherits from one
parent class.
Diagram
Parent
Child
Example
class Animal:
def eat(self):
print("Animal is eating")
class Dog(Animal):
def bark(self):
print("Dog is barking")
d = Dog()
[Link]()
[Link]()
Output
Animal is eating
Dog is barking
Explanation
b. Multiple Inheritance
Multiple inheritance occurs when one child class inherits from two
or more parent classes.
Diagram
Father Mother
\ /
\ /
▼ ▼
Child
Example
class Father:
def money(self):
class Mother:
def love(self):
pass
c = Child()
[Link]()
[Link]()
Output
Explanation
c. Multilevel Inheritance
Multilevel inheritance occurs when a child class becomes the parent
of another class.
Diagram
Grandparent
Parent
Child
Example
class Animal:
def eat(self):
print("Animal is eating")
class Dog(Animal):
def bark(self):
print("Dog is barking")
class Puppy(Dog):
def sleep(self):
print("Puppy is sleeping")
p = Puppy()
[Link]()
[Link]()
[Link]()
Output
Animal is eating
Dog is barking
Puppy is sleeping
Explanation
d. Hierarchical Inheritance
Hierarchical inheritance occurs when multiple child classes inherit
from the same parent class.
Diagram
Animal
/ \
▼ ▼
Dog Cat
Example
class Animal:
def eat(self):
print("Animal is eating")
class Dog(Animal):
def bark(self):
print("Dog is barking")
class Cat(Animal):
def meow(self):
print("Cat says Meow")
d = Dog()
c = Cat()
[Link]()
[Link]()
[Link]()
[Link]()
Output
Animal is eating
Dog is barking
Animal is eating
Explanation
e. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of
inheritance, such as hierarchical and multiple inheritance.
Diagram
Animal
/ \
▼ ▼
Dog Cat
\ /
▼ ▼
Pet
Example
class Animal:
def eat(self):
print("Animal is eating")
class Dog(Animal):
def bark(self):
print("Dog is barking")
class Cat(Animal):
def meow(self):
pass
p = Pet()
[Link]()
[Link]()
[Link]()
Output
Animal is eating
Dog is barking