0% found this document useful (0 votes)
4 views61 pages

Python Notes

The document provides an overview of Python, including its uses, basic concepts such as algorithms, flowcharts, and pseudocode, as well as details on variables, data types, operators, strings, conditional statements, and loops. It explains how to create algorithms, represent them with flowcharts, and write pseudocode, along with the rules for naming variables and the different data types available in Python. Additionally, it covers various operators, string methods, and control structures like conditional statements and loops.
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)
4 views61 pages

Python Notes

The document provides an overview of Python, including its uses, basic concepts such as algorithms, flowcharts, and pseudocode, as well as details on variables, data types, operators, strings, conditional statements, and loops. It explains how to create algorithms, represent them with flowcharts, and write pseudocode, along with the rules for naming variables and the different data types available in Python. Additionally, it covers various operators, string methods, and control structures like conditional statements and loops.
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

Python is a widely used programming language. It was created by Guido van Rossum
and released in 1991.

Python is used for:

❖​ Building websites
❖​ Developing software and applications
❖​ Performing mathematical calculations
❖​ Automating tasks and system operations (scripting)

QNO.1 Explain the concepts of algorithm, flowchart, and pseudocode

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.

Example: Algorithm to add two numbers:

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.

In Python, a variable is created when a value is assigned to it using the assignment


operator (=)

Syntax:

variable_name = value

Rules for Naming Variables

1.​ A variable name must start with a letter or underscore (_).


2.​ It cannot start with a number.
3.​ It can contain letters, numbers, and underscores.
4.​ Variable names are case-sensitive (Age and age are different).
5.​ Keywords such as if, for, and while cannot be used as variable names.

QNO.3. Explain Different Data Types in Python with Suitable Examples

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

Numeric data types are used to store numerical values.

a.​ Integer (int): Stores whole numbers without decimal points.


Example: age = 25
b.​ Float (float): Stores numbers with decimal points.
Example: salary = 25000.50
c.​ Complex (complex): Stores complex numbers consisting of real and
imaginary parts.
Example c = 2 + 4j

B. Sequence Data Types

A sequence is an ordered collection of elements. Elements can be accessed using their


index positions.

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

fruits = ["Apple", "Banana", "Mango"]

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

numbers = (10, 20, 30)


print(numbers)

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.

A.​ Arithmetic Operators in Python

Arithmetic operators are used to perform mathematical calculations on numeric values. They
are commonly used for addition, subtraction, multiplication, division, and other mathematical
operations.

Operator Name Description​ Example

+ Addition​ Adds two values x+y


- Subtraction Subtracts one value x-y


from another

* Multiplication Multiplies two values x*y

/ Division Divides one value by x/y


another

% Modulus Returns the x%y


remainder after
division

** Exponentiation Raises a number to a x ** y


power

// Floor Division Returns the quotient x // y


without decimal part

a. Addition Operator (+)


The addition operator adds two numbers and returns their sum.

Syntax
x+y
Example
x = 10
y=3
print(x + y)

Output
13

b. Subtraction Operator (-)

The subtraction operator subtracts one number from another.

Syntax
x-y
Example
x = 10
y=3
print(x - y)

Output
7

c. Multiplication Operator (*)


The multiplication operator multiplies two numbers.

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

e. Exponentiation Operator (**)


The exponentiation operator raises a number to the power of another number.

Syntax
x ** y
Example
x = 10
y=3
print(x ** y)
Output
1000

f. Floor Division Operator (//)

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

B.​ Assignment operators

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.

a. Assignment Operator (=)


The = operator assigns a value to a variable.
Syntax
variable = value
Example
x=5
print(x)

Output
5

b. Add and Assign Operator (+=)


Adds a value to the current value of a variable and stores the result back in the same variable.

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

d. Multiply and Assign Operator (*=)


Multiplies the variable by a value and stores the result back.

Syntax
x *= y
Equivalent to:
x=x*y
Example
x = 10
x *= 3
print(x)
Output
30

e. Divide and Assign Operator (/=)


Divides the variable by a value and stores the result back.

Syntax
x /= y
Equivalent to:
x=x/y
Example
x = 10
x /= 2
print(x)

Output
5.0

f. Modulus and Assign Operator (%=)


Finds the remainder after division and stores it back.

Syntax
x %= y
Equivalent to:
x=x%y
Example
x = 10
x %= 3
print(x)

Output
1

g. Floor Division and Assign Operator (//=)


Performs floor division and stores the integer quotient back.

Syntax
x //= y
Equivalent to:
x = x // y
Example
x = 10
x //= 3
print(x)

Output
3

h. Exponentiation and Assign Operator (**=)


Raises a number to a power and stores the result back.

Syntax
x **= y
Equivalent to:
x = x ** y
Example
x=2
x **= 3
print(x)

Output
8

C.​Comparison (Relational) Operators


Comparison Operators (also called Relational Operators) are used to compare two values.

They return either:

●​ True → if the condition is correct


●​ False → if the condition is incorrect

Example
a = 13
b = 33

print(a > b)

Output

False

Because 13 is not greater than 33.

Comparison operators
Operator Name Description Examples

== Equal To Checks if two values a == b


are equal

!= Not Equal To Checks if two values a != b


are different

> Greater Than Checks if left value is a > b


greater

< Less Than Checks if left value is a < b


smaller

>= Greater Than Checks if left value is a >= b


or Equal greater than or
To equal to right
value

<= Less Than or Checks if left value is a <= b


Equal To less than or equal
to right value

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

Logical Operators are used to perform logical operations on conditions.

They are mainly used to:

●​ Combine two or more conditions.


●​ Check whether conditions are True or False.
●​ Return a Boolean value (True or False).

a. Logical AND (and)


Returns True only when both conditions are True

b. Logical OR (or)
Returns True if at least one condition is True

C. Logical NOT (not)


Reverses the result of a condition.

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.

A.​ Common String Methods


a. upper()

Converts all characters in a string to uppercase.

Example

s = “python”
print([Link]())
Output: PYTHON

b. lower()

Converts all characters in a string to lowercase.

Example
s = “PYTHON”
print([Link]())
Output: python

c. strip()

Removes leading and trailing spaces from a string.

Example

s = “Python”
print([Link]())
Output: Python

d. replace()

Replaces a specified substring with another substring.

Example

s = “I like Java”
print([Link](“Java”, “Python”))
Output: I like Python

e. split()

Splits a string into a list based on a specified separator.

Example:

s = "Apple,Banana,Mango"
print([Link](","))

Output: ['Apple', 'Banana', 'Mango']

f. join()

Joins elements of a sequence into a single string.

Example:

items = ["Python", "Java", "C++"]


print("-".join(items))

Output: Python-Java-C++

g. find()

Returns the position of the first occurrence of a substring.

Example:

s = "Welcome to Python"
print([Link]("Python"))

Output: 11

h. count()

Returns the number of times a substring appears in a string.

Example:

s = "apple apple mango"


print([Link]("apple"))

Output: 2

i. startswith()

Checks whether a string starts with a specified value.

Example:

s = "Python Programming"
print([Link]("Python"))
Output: True
j. endswith()

Checks whether a string ends with a specified value.

Example:

s = "Python Programming"
print([Link]("Programming"))

Output: True

k. isalpha()

Returns True if all characters in the string are alphabets.

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

B.​ String Slicing in Python

String slicing is a technique used to extract a portion (substring) of a string. It is performed


using the slice operator [:].

Syntax:

string[start:end]

●​ start → Starting index (included)


●​ end → Ending index (excluded)
●​ Indexing starts from 0
a.​ Basic Slicing

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

Here, characters from index 2 to 4 are returned. Index 5 is not included.

b. Slice from the Start

If the start index is omitted, slicing begins from the first character.

Example

b = "Hello, World!"
print(b[:5])

Output:

Hello

c. Slice to the End

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

Negative indices count characters from the end of the string.


Example

b = "Hello, World!"
print(b[-5:-2])

Output:

orl

Here:

❖​ -5 refers to 'o'
❖​ -2 refers to 'd' (not included)

QNO.6 Conditional Statements in Python and Their Types


Conditional statements are one of the most important control structures in programming. They
allow a program to make decisions and execute different sets of instructions based on whether
a condition is True or False. Without conditional statements, a program would execute all
statements sequentially without making any decisions.

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.

Need for Conditional Statements


Conditional statements are used to:

●​ Make decisions in a program.


●​ Execute different actions for different conditions.
●​ Control the flow of program execution.
●​ Improve program flexibility and intelligence.

For example, a program can check whether a student has passed or failed based on marks
obtained.

Types of Conditional Statements in Python


A. Simple if Statement

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

if age >= 18:


print("Eligible for Voting")

Output:

Eligible for Voting

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

if marks >= 90:


print("Grade A")
elif marks >= 75:
print("Grade B")
elif marks >= 60:
print("Grade C")
else:
print("Fail")

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

if age >= 18:


if citizen:
print(“Eligible to Vote”)
Output:

Eligible to Vote

QNO.7Explain the Concept of Loops and Their Types in


Python with Suitable Examples
A loop is a control structure that allows a set of statements to be executed repeatedly until a
specified condition is met. Loops help reduce code repetition, make programs more efficient,
and simplify complex tasks.

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.

Need for Loops


●​ Reduce repetitive code.
●​ Save time and effort.
●​ Make programs shorter and more readable.
●​ Automate repetitive tasks.
●​ Process large amounts of data efficiently.

[Link] of Loops in Python


Python mainly provides two types of loops:

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:

for variable in sequence:


statements

Example:

for i in range(1, 6):


print(i)
Output:

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:

adj = ["red", "big", "tasty"]

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

for x in adj:

for y in fruits:

print(x, y)

B. Loop Control Statements


The break, continue, and pass statements are loop control statements in Python. They are
used to alter the normal execution of loops and conditional statements.

a. break Statement

The break statement immediately terminates the loop.

Example:

for i in range(1, 6):


if i == 4:
break
print(i)

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:

for i in range(1, 6):


if i == 3:
continue
print(i)

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:

for i in range(1, 6):

if i == 3:

pass

print(i)

Output:

[Link] Between for Loop and while Loop with Examples


Loops are used to execute a block of code repeatedly. Python provides two main types of loops:
for loop and while loop.
a.​for Loop
A for loop is used to iterate over a sequence such as a list, tuple, string, or range of values. It is
generally used when the number of iterations is known in advance.

Example:

for i in range(1, 6):


print(i)

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

Difference Between for Loop and while Loop


Feature for Loop while Loop

Definition Iterates over a sequence of Repeats execution while a condition


elements is true
Number of Usually known beforehand Usually not known beforehand
Iterations

Syntax Simpler and shorter Requires condition and variable


update

Initialization Handled automatically Must be done manually

Update of Variable Automatic Must be updated manually

Infinite Loop Less likely More likely if condition is not updated

Common Use Traversing lists, strings, ranges Condition-based repetition

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

QNO.8 Python Functions


A function is a reusable block of code that performs a specific task. Functions help organize
programs into smaller, manageable parts and avoid writing the same code repeatedly.

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:

Hello from a function

A function can be called multiple times.


Example:

def my_function():
print("Hello from a function")

my_function()
my_function()
my_function()

Output:

Hello from a function


Hello from a function
Hello from a function

QNO.9 Python range() Function


The range() function is a built-in Python function used to generate a sequence of numbers. It
is commonly used in loops when a block of code needs to be executed a specific number of
times.

The sequence produced by range() is immutable, meaning it cannot be changed after it is


created.

Syntax
range(start, stop, step)

Where:

●​ start → Starting value (inclusive)


●​ stop → Ending value (exclusive)
●​ step → Difference between consecutive numbers

a. range() with One Argument


When only one argument is provided, it is treated as the stop value. The sequence starts from 0
by default.

Example:

x = range(10)
for i in x:
print(i)

Output:

0
1
2
3
4
5
6
7
8
9

b. range() with Two Arguments


When two arguments are provided, the first is the start value and the second is the stop value.

Example:

for i in range(3, 10):


print(i)

Output:

3
4
5
6
7
8
9

c. range() with Three Arguments


When three arguments are provided, the third argument specifies the step value.

Example:

for i in range(3, 10, 2):


print(i)

Output:

3
5
7
9

Example: Printing Even Numbers


for i in range(2, 11, 2):
print(i)

Output:

2
4
6
8
10

QNO.10 Math Module in Python


The Math Module is a built-in Python module that provides various mathematical functions and
constants for performing advanced mathematical calculations. It extends Python's basic
mathematical capabilities and is useful for scientific, engineering, and numerical computations.

Before using the math module, it must be imported into the program.

Syntax:

import math

Common Functions of the Math Module

a. [Link]()

Returns the square root of a number.

Example:

import math
print([Link](64))
Output:

8.0

b. [Link]()

Rounds a number upward to the nearest integer.

Example:

import math
print([Link](4.2))

Output:

c. [Link]()

Rounds a number downward to the nearest integer.

Example:

import math
print([Link](4.8))

Output:

d. [Link]()

Returns the value of a number raised to a specified power.

Example:

import math
print([Link](2, 3))

Output:

8.0

e. [Link]()

Returns the factorial of a number.


Example:

import math
print([Link](5))

Output:

120

f. [Link]

Returns the value of π (Pi).

Example:

import math
print([Link])

Output:

3.141592653589793

QNO.11 Random Module in Python


The `random` module is a built-in Python module used to generate random numbers and make
random selections. It is useful in games, simulations, lotteries, password generation, and many
other applications where random values are needed.

To use the random module, it must first be imported.

Syntax:

import random

Common Functions of the Random Module

a. random()

Returns a random floating-point number between 0.0 and 1.0.

Example:

import random
print([Link]())

Possible Output:

0.7345

b. randint()

Returns a random integer between the specified range (inclusive).

Example:

import random
print([Link](1, 10))

Possible Output:

c. randrange()

Returns a randomly selected number from a specified range.

Example:

import random
print([Link](1, 10))

Possible Output:

d. choice()

Returns a random element from a sequence such as a list, tuple, or string.

Example:

import random

fruits = ["Apple", "Banana", "Mango"]


print([Link](fruits))

Possible Output:

Banana
e. shuffle()

Randomly rearranges the elements of a list.

Example:

import random

numbers = [1, 2, 3, 4, 5]
[Link](numbers)
print(numbers)

Possible Output:

[3, 1, 5, 2, 4]

QNO.12 Python Lists


A List is a built-in data type in Python used to store multiple items in a single variable. Lists are
one of the most commonly used data structures because they can store collections of data
efficiently.

Lists are created using square brackets [ ].

Example:

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


print(fruits)

Output:

['apple', 'banana', 'cherry']

[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.

c. Allow Duplicate Values

Lists can contain duplicate items.

[Link] Length
The len() function returns the number of items in a list.

Example:

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


print(len(fruits))

Output:

e. List Items Can Have Different Data Types


Lists can store elements of the same or different data types.

Example:

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


list2 = [1, 5, 7, 9]
list3 = [True, False, True]
list4 = ["abc", 34, True, 40, "male"]

f. Type of a List
The type() function is used to determine the data type of a list.

Example:

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


print(type(mylist))

Output:

<class 'list'>
[Link] a List Using list() Constructor
Lists can also be created using the list() constructor.

Example:

thislist = list(("apple", "banana", "cherry"))


print(thislist)

Output:

['apple', 'banana', 'cherry']

[Link] List Operations


a.​ Adding an Item
fruits = ["apple", "banana"]
[Link]("mango")
print(fruits)

Output:

['apple', 'banana', 'mango']

b.​ Removing an Item


fruits = ["apple", "banana", "mango"]
[Link]("banana")
print(fruits)

Output:

['apple', 'mango']

QNO.13 Python Tuples


A Tuple is a built-in data type in Python used to store multiple items in a single variable. Tuples
are similar to lists, but unlike lists, they are immutable (unchangeable).

A tuple is one of the four collection data types in Python:

●​ List
●​ Tuple
●​ Set
●​ Dictionary

Tuples are created using round brackets ( ).

Example:

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


print(thistuple)

Output:

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

Characteristics of Tuples
a. Ordered

Tuples are ordered, which means items have a fixed position and can be accessed using
indexes.

b. Unchangeable (Immutable)

Once a tuple is created, its items cannot be changed, added, or removed.

c. Allow Duplicate Values

Tuples can contain duplicate items.

d. Tuple Length
The len() function returns the number of items in a tuple.

Example:

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


print(len(fruits))

Output:

e. A tuple can store items of different data types.


f. Single-Item Tuple
To create a tuple with only one item, a comma must be added after the item.

Example:

t = ("apple",)
print(type(t))

Output:

<class 'tuple'>

Without the comma, Python treats it as a string.

[Link] a Tuple Using tuple() Constructor


Tuples can also be created using the tuple() constructor.

h. Accessing Tuple Elements


Tuple elements are accessed using indexes.

Example:

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


print(fruits[1])

Output:

banana

QNO.14. Set

A Set in Python is an unordered collection of unique elements. One of


the main advantages of sets is that they support mathematical set
operations such as union, intersection, difference, and symmetric
difference.

Set operations are useful for comparing data, removing duplicates,


and finding common or unique elements between collections.
A. Union Operation (union() or |)
The union of two sets contains all unique elements from both sets.

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

set1 & set2

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.

Python provides built-in functions to perform type conversion such as:

❖​int() → Converts to integer


❖​float() → Converts to float
❖​str() → Converts to string
❖​bool() → Converts to Boolean

Type casting is useful when we need to perform operations on different data types

Why Type Casting is Needed?

Sometimes data is available in one type, but we need it in


another type.

Type Casting Types:

a.​Type Conversion or Implicit Type Conversion: is the


process in which Python automatically converts one data
type to another whenever needed. Example

x = 10 # int

y = 2.5 # float

z = x + y

print(z)

b.​Explicit Type Casting


The programmer manually converts one data type into another
using built-in functions.

Example
x = “10”

y = int(x)
print(y)

[Link]

A Dictionary is a built-in Python data structure used to store data in


key:value pairs.

Example

student = {

"name": "Ali",

"age": 20,

"course": "Python"

In the above dictionary:

●​ name, age, and course are keys.


●​ Ali, 20, and Python are values.

[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.

B. How to Check if a Key Exists in a Dictionary?

We can use the in keyword to check whether a key exists in a


dictionary.

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.

QNO.17 Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that


helps developers build modular, reusable, maintainable, and scalable
applications.

Features of OOP
1. Modular

A large program is divided into smaller parts called classes or


modules.

Example: University Management System

●​ Student Class
●​ Teacher Class
●​ Course Class
●​ Library Class

Each class performs a specific task.

2. Maintainable

Programs can be modified easily without affecting the entire system.

Example: If we want to add a student's email field, we only modify


the Student class.

3. Reusable

A class can be reused in different programs.

Example: A Student class can be used in:

●​ School Management System


●​ College Management System
●​ University Management System

4. Scalable

New features can be added easily as the application grows.

Example: Adding an Online Examination Module to an existing


University Management System.

[Link]
A Class is a blueprint or template used to create objects.
Example

A house blueprint contains:

●​ Number of rooms
●​ Doors
●​ Windows
●​ Kitchen

The blueprint is the class.

Python Syntax
class Dog:

Pass

[Link]
An Object is an actual instance created from a class.

Example

●​ Class → House Blueprint


●​ Object → Actual House built from that blueprint.

Another example:

●​ Class → Smartphone
●​ Objects → Samsung Phone, iPhone, OnePlus Phone.

C. Attributes and Methods


Attributes
Attributes are the properties or characteristics of a class.

Student Attributes

●​ Name
●​ Age
●​ Roll Number

Car Attributes

●​ Color
●​ Model
●​ Speed

Mobile Phone Attributes

●​ Brand
●​ Battery
●​ Storage
●​ Color

Methods
Methods are the actions performed by an object.

Student Methods

●​ study()
●​ take_exam()

Car Methods

●​ start()
●​ stop()
●​ brake()

Mobile Phone Methods

●​ call()
●​ message()
●​ take_photo()
●​ internet()

Methods describe what an object can do.


Python Example
class Student:

name = "Ali"

def display(self):

print("Hello")

Creating an Object

s1 = Student()

Here:

●​ class → keyword used to create a class.


●​ Student → class name.
●​ name → attribute.
●​ display() → method.
●​ s1 → object of Student class.

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

Student is taking exam

[Link] (Concepts) of OOP


Object-Oriented Programming (OOP) is based on four main concepts:

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

A capsule contains medicine inside it. Similarly, a class keeps data


and methods together.

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

The Dog class can use the properties of Animal.

d. Polymorphism
Polymorphism means one thing having many forms.

The same method can behave differently for different objects.

Example
A person can be:

●​ Teacher
●​ Father
●​ Friend

Same person, different roles.

[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

●​ Animal is the parent class.


●​ Dog is the child class.
●​ Dog inherits the eat() method from Animal.
●​ Dog also has its own method bark().

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):

print("Father has money")

class Mother:

def love(self):

print("Mother gives love")

class Child(Father, Mother):

pass
c = Child()

[Link]()

[Link]()

Output

Father has money

Mother gives love

Explanation

●​ Child inherits from both Father and Mother.


●​ Therefore, it can access both money() and love() methods.

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

●​ Dog inherits from Animal.


●​ Puppy inherits from Dog.
●​ Hence, Puppy can use:
○​ eat() from Animal
○​ bark() from Dog
○​ sleep() from Puppy

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

Cat says Meow

Explanation

●​ Both Dog and Cat inherit from Animal.


●​ Therefore, both classes can use the eat() method.

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):

print("Cat says Meow")

class Pet(Dog, Cat):

pass

p = Pet()
[Link]()

[Link]()

[Link]()

Output

Animal is eating

Dog is barking

Cat says Meow

You might also like