Data Types, Type Conversion,
Input/Output
1. Understanding Data Types
Why are Data Types Important?
● Every piece of data you work with in a program has a type
that defines:
○ What kind of value it represents (e.g., number, text)
○ What operations you can perform on it (e.g., addition,
concatenation)
○ How much memory it consumes
● Correct understanding helps prevent errors and write
efficient code.
1.1 Primitive Data Types (Basic building blocks)
These hold single values, not collections.
Typ Description Example Notes
e Values
int Integer numbers 5, -3, 0, No decimal points. Used
(whole numbers) 1000 for counting, indexing,
math ops.
flo Floating-point 3.14, -0.001, Represents real numbers,
at numbers 0.0 can handle fractional
(decimals) values.
str String (text data) "hello", Sequence of characters,
'Python3' enclosed in single or
double quotes.
bo Boolean True, Logical values used for
ol (True/False) False decision-making and
conditions.
1.2 Examples and Explanation
x = 10 # x is int (integer)
pi = 3.14159 # pi is float (decimal number)
greeting = "Hi!" # greeting is str (text)
is_happy = True # is_happy is bool (True/False)
● Use type() function to check the data type:
print(type(x)) # Output: <class 'int'>
print(type(pi)) # Output: <class 'float'>
print(type(greeting)) # Output: <class 'str'>
print(type(is_happy)) # Output: <class 'bool'>
1.3 Why differentiate int and float?
● Integers are exact whole numbers.
● Floats represent approximate values and support
decimals.
● Mathematical operations behave differently:
print(5 / 2) # Output: 2.5 (float division)
print(5 // 2) # Output: 2 (integer division)
2️⃣ Collection Data Types (Containers for
multiple values)
Python provides several built-in collection types to group
multiple values.
Type Synt Order Muta Allows Description
ax ed? ble? Duplicates
?
List [] Yes Yes Yes Dynamic array,
commonly used for
sequences
Tupl () Yes No Yes Immutable
e sequence, used for
fixed collections
Set {} No Yes No Unordered collection
(unique of unique elements
only)
Dict {key: No Yes Keys Key-value pairs, like
value unique a real-world
} dictionary
2.1 List — Ordered and Mutable
● Lists can be modified (add, remove, change elements).
● Elements are accessed by index (starting from 0).
Example:
fruits = ["apple", "banana", "cherry"]
print(fruits[1]) # Output: banana
fruits.append("orange") # Add element
print(fruits) # ['apple', 'banana', 'cherry', 'orange']
2.2 Tuple — Ordered and Immutable
● Tuples cannot be changed once created.
● Useful for fixed data sets like coordinates.
Example:
point = (10, 20)
print(point[0]) # Output: 10
# point[0] = 15 # Error! Tuples are immutable
2.3 Set — Unordered and Unique
● Sets store unique elements without order.
● Useful for removing duplicates or membership tests.
Example:
numbers = {1, 2, 3, 2, 1}
print(numbers) # Output: {1, 2, 3} (duplicates removed)
2.4 Dictionary — Key-Value Mapping
● Stores pairs: each key maps to a value.
● Keys must be immutable and unique; values can be any
type.
Example:
person = {"name": "Devita", "age": 25, "city": "Nashik"}
print(person["name"]) # Output: Devita
person["age"] = 26 # Update value
3.Type Conversion (Casting)
Sometimes data needs to be converted from one type to
another.
Why is this important?
● Data from user input or files is often string type.
● You might need numbers for calculations or strings for
concatenation.
3.1 Common type conversion functions
Function Purpose Example
int() Convert to int("123") → 123
integer
float() Convert to float float("3.14") → 3.14
(decimal)
str() Convert to str(100) → "100"
string
bool() Convert to bool(0) → False, bool(5)
boolean → True
(True/False)
3.2 Example:
age_str = "25"
age_int = int(age_str) # Convert from str to int
height_float = float("5.9") # Convert from str to float
num = 10
num_str = str(num) # Convert int to str
3.3 Caution when converting
● Not all conversions are valid:
int("abc") # Error: cannot convert non-numeric string to int
float("hello") # Error
4. Input and Output in Python
4.1 Input (input() function)
● Takes user input as string.
● You can provide a prompt string for better UX.
name = input("Enter your name: ") # User types something,
stored as string in 'name'
● Since input is string by default, convert to int or float if
needed:
age = int(input("Enter your age: "))
4.2 Output (print() function)
● Displays output to the console.
● Can print strings, numbers, variables, or formatted text.
print("Hello World!")
print(age)
print("Age:", age)
4.3 Formatted strings (f-strings)
● Introduced in Python 3.6+
● Embed variables and expressions directly inside strings
using {}.
Example:
name = "Devita"
age = 24
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Devita and I am 24 years old.
● Can also do math inside f-strings:
print(f"In 5 years, you will be {age + 5}.")
5.Demo Script: Interactive User Input
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"In 5 years, you will be {age + 5}")
6. Practice Task:
Write a script to:
● Ask for name, age, and city
● Print a formatted message with the collected data
Example Solution:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
city = input("Enter your city: ")
print(f"Hello {name} from {city}! You are {age} years old.")
Summary Table
Concept Description Example
int Whole numbers 10, -5
float Decimal numbers 3.14, -0.5
str Text (sequence of "hello", "Python"
characters)
bool True or False logical values True, False
List Ordered, changeable [1, 2, 3]
sequence
Tuple Ordered, immutable (1, 2, 3)
sequence
Set Unordered, unique elements {1, 2, 3}
Dict Key-value pairs {"name": "Alice", "age":
30}
input() Takes input as string input("Enter name: ")
print() Prints output print("Hello")
Type Convert between types int("123"), str(456)
conversio
n
f-string Formatted strings with f"My age is {age}"
embedded expressions
PythonOperators —
Introduction
"In Python, operators are special symbols or keywords that carry
out operations on values and variables. Operators are essential
because they allow us to manipulate data, perform calculations,
make decisions, and control flow."
1. Arithmetic Operators
Purpose: Perform mathematical calculations.
Operat Description Example Result
or
+ Addition 5+3 8
- Subtraction 5 - 3 2
* Multiplicati 5*3 15
on
/ Division 5/2 2.5
(float)
// Floor 5 // 2 2
Division
(int)
% Modulo 5%2 1
(remainder)
** Exponentia 5 ** 2 25
tion
Example:
a = 10
b=3
print("a + b =", a + b) # 13
print("a - b =", a - b) #7
print("a * b =", a * b) # 30
print("a / b =", a / b) # 3.3333...
print("a // b =", a // b) # 3 (floor division)
print("a % b =", a % b) # 1 (remainder)
print("a ** b =", a ** b) # 1000 (10^3)
Important Notes:
● Division / always returns a float.
● Floor division // returns the integer quotient without
remainder.
● Modulo % gives the remainder after division.
● Exponent ** raises the left operand to the power of the
right operand.
2. Assignment Operators
Purpose: Assign values to variables, or update existing
variables.
Operator Description Example Equivalent to
= Assign value x=5 N/A
+= Add and x += 3 x=x+3
assign
-= Subtract and x -= 3 x=x-3
assign
*= Multiply and x *= 3 x=x*3
assign
/= Divide and x /= 3 x=x/3
assign
//= Floor divide x //= 3 x = x // 3
assign
%= Modulo and x %= 3 x=x%3
assign
**= Exponentiate x **= 3 x = x ** 3
assign
Example:
x=5
x += 3 #x=8
print(x)
x *=g 2 # x = 16
print(x)
Important Notes:
● These operators combine arithmetic and assignment for
concise updates.
● They work with numbers, strings (concatenation), lists
(extend), and more.
3. Comparison Operators
Purpose: Compare two values; result is always a Boolean (True or
False).
Operator Description Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
< Less than 3<5 True
> Greater than 5>3 True
<= Less than or 3 <= 3 True
equal to
>= Greater than 5 >= 5 True
or equal to
Example:
print(5 == 5) # True
print(5 != 3) # True
print(3 < 5) # True
print(5 > 7) # False
print(3 <= 3) # True
print(4 >= 5) # False
Important Notes:
● Used for conditions in if, while, etc.
● Can be applied to numbers, strings (lexicographically), and
other comparable data types.
4. Logical Operators
Purpose: Combine multiple Boolean expressions or invert
Boolean values.
Operator Description Example Result
and Logical AND True and False
False
or Logical OR True or True
False
not Logical NOT not True False
(negate)
Example:
a = True
b = False
print(a and b) # False (both must be True)
print(a or b) # True (at least one True)
print(not a) # False (negate True)
Important Notes:
● and returns True only if both operands are True.
● or returns True if at least one operand is True.
● not inverts the Boolean value.
5. Membership Operators
Purpose: Check if a value is present (or absent) in a collection
like a list, tuple, string, set, or dictionary keys.
Operator Description Example Result
in Checks 'a' in 'apple' True
presence
not in Checks 5 not in [1, True
absence 2, 3]
Example:
my_list = [1, 2, 3, 4]
print(3 in my_list) # True
print(5 not in my_list) # True
6. Identity Operators
Purpose: Compare if two variables point to the same object in
memory (not just equal values).
Operator Description Example Result
is True if both x is y True/False
are same
object
is not True if both x is not y True/False
are not
same
Example:
x = [1, 2]
y = [1, 2]
z=x
print(x == y) # True (values are equal)
print(x is y) # False (different objects)
print(x is z) # True (same object)
Important Notes:
● is checks for object identity, not equality.
● Useful when checking if something is None (use if x is
None).
Tips
● Use arithmetic operators for math.
● Use assignment operators to update variables efficiently.
● Use comparison operators in conditional statements.
● Use logical operators to combine multiple conditions.
● Use membership operators to check presence in
containers.
● Use identity operators to check if two references point to
the exact same object.
Operator Precedence
Operators have precedence (priority). For example, ** has higher
precedence than * or +.
Example:
print(2 + 3 * 4) # 14 (multiplication first)
print((2 + 3) * 4) # 20 (parentheses change order)
Python Operator Precedence
What is Operator Precedence?
Operator precedence determines the order in which operations
are evaluated in an expression when multiple operators are
present without explicit parentheses.
● Operators with higher precedence are evaluated before
operators with lower precedence.
● If operators have the same precedence, evaluation is
typically left to right (except for some like exponentiation
which is right to left).
Why is Operator Precedence Important?
Consider this expression:
python
CopyEdit
result = 2 + 3 * 4
● If addition were done first: (2 + 3) * 4 = 5 * 4 = 20
● If multiplication is done first: 2 + (3 * 4) = 2 + 12 = 14
Python follows operator precedence rules to decide which one
to do first. In this case, multiplication has higher precedence
than addition, so the result is 14.
Complete Operator Precedence Table in
Python (Highest to Lowest)
Preced Operator Type Operators Associativity
ence
1 Parentheses, Grouping ( ... ) Left to right
2 Exponentiation ** Right to left
3 Unary plus, minus, +x, -x, ~x Right to left
bitwise NOT
4 Multiplication, *, /, //, % Left to right
Division, Floor Division,
Modulo
5 Addition, Subtraction +, - Left to right
6 Bitwise Shift <<, >> Left to right
7 Bitwise AND & Left to right
8 Bitwise XOR ^ Left to right
9 Bitwise OR | Left to right
10 Comparison ==, !=, >, <, >=, <=, is, Left to right
Operators is not, in, not in
11 Logical NOT not Right to left
12 Logical AND and Left to right
13 Logical OR or Left to right
14 Conditional if - else Right to left
Expressions
15 Assignment Operators =, +=, -=, *=, /=, //=, Right to left
%= etc.
16 Lambda Expressions lambda Right to left
● 1. Parentheses ( )
● Used to group expressions and override default
precedence.
●
● print((2 + 3) * 4) # Outputs: 20 (parentheses force 2+3 to
happen first)
●
●
● 2. Exponentiation **
● Evaluated right to left.
●
● print(2 ** 3 ** 2) # 3**2 = 9, then 2**9 = 512
●
●
● 3. Unary +, -, ~
● Unary operators applied right to left.
●
● x = -3
● print(+x, -x, ~x) # +(-3) = -3, -(-3) = 3, ~(-3) = 2 (bitwise NOT)
●
●
● 4. Multiplication, Division, Floor Division, Modulo * /
// %
●
● print(10 * 2 / 5 // 1 % 3) # Output: 2.0 (evaluated left to right)
●
●
● 5. Addition, Subtraction + -
●
● print(5 + 3 - 2) # Output: 6
●
●
● 6. Bitwise Shift << >>
●
● print(2 << 2) # 2 * 2^2 = 8
● print(8 >> 2) # 8 / 2^2 = 2
●
●
● 7. Bitwise AND &
●
● print(5 & 3) # 101 & 011 = 001 = 1
●
●
● 8. Bitwise XOR ^
●
● print(5 ^ 3) # 101 ^ 011 = 110 = 6
●
●
● 9. Bitwise OR |
●
● print(5 | 3) # 101 | 011 = 111 = 7
●
●
● 10. Comparison Operators == != > < is in
●
● print(5 > 3 and 3 != 2) # Output: True
● print(5 is 5, 'a' in 'abc') # True, True
●
●
● 11. Logical NOT not
●
● print(not True) # Output: False
●
●
● 12. Logical AND and
●
● print(True and False) # Output: False
●
●
● 13. Logical OR or
●
●
● print(False or True) # Output: True
●
●
● 14. Conditional Expression x if cond else y
●
● x = 10
● y = 20
● print(x if x > y else y) # Output: 20
●
●
● 15. Assignment = += -= ...
●
● a = 5
● a += 2
● print(a) # Output: 7
●
●
● 16. Lambda Expression
●
●
● f = lambda x: x * 2
● print(f(5)) # Output: 10
●
●
Examples with Precedence
Example 1:
python
CopyEdit
print(3 + 4 * 2) # 3 + (4*2) = 3 + 8 = 11
Example 2:
python
CopyEdit
print(3 ** 2 ** 2) # 3 ** (2 ** 2) = 3 ** 4 = 81
Example 3:
python
CopyEdit
print(-3 ** 2) # -(3 ** 2) = -9
Example 4:
python
CopyEdit
print(not True or False and True)
# Evaluate `not True` first → False
# Then `False or False and True`
# `and` before `or`, so `False and True` = False
# Then `False or False` = False
Control Flow Statements
(Conditionals)
1. if Statement
What is it?
The if statement is used to execute a block of code only if a
condition is true.
When to use?
Use it when you want to perform an action only if a specific
condition is met.
Why use it?
To control the flow of execution based on logical conditions (e.g.,
user input, values, comparisons).
If (cond):
print(yes)#if cond is true
Syntax:
print ("yes")
elif(condition2): # if condition 2 is True
print("no")
else: # otherwise
print("maybe") code to run if condition is true
Example1:
a=22
If a>9:
print("greater")
else:
print("lesser")
Example 1:
age = 18
if age >= 18:
print("You can vote.")
Example 2:
temperature = 25
if temperature > 20:
print("It's a warm day.")
Example 3:
password = "admin123"
if password == "admin123":
print("Access granted.")
2. if-else Statement
What is it?
Executes one block of code if the condition is true, and another
if it is false.
When to use?
Use when there are two outcomes: one if a condition is true, and
another if false.
Why use it?
To handle binary decisions — yes/no, true/false, success/failure.
Syntax:
if condition:
# code if condition is true
else:
# code if condition is false
Example 1:
marks = 60
if marks >= 50:
print("Pass")
else:
print("Fail")
Example 2:
user_input = "yes"
if user_input == "yes":
print("You agreed.")
else:
print("You disagreed.")
Example 3:
number = 5
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
3. if-elif-else Ladder
What is it?
Checks multiple conditions in sequence. Executes the first
condition that is true.
When to use?
Use when you have more than two possible outcomes.
Why use it?
To avoid writing many nested if or multiple separate if
statements.
Syntax:
if condition1:
# code block
elif condition2:
# another block
elif condition3:
# another block
else:
# final block
Example 1:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
Example 2:
day = "Wednesday"
if day == "Monday":
print("Start of the week.")
elif day == "Friday":
print("Weekend is near.")
elif day == "Sunday":
print("Weekend!")
else:
print("A regular weekday.")
Example 3:
temperature = 15
if temperature > 30:
print("It's hot.")
elif temperature > 20:
print("Nice weather.")
elif temperature > 10:
print("It's cool.")
else:
print("It's cold.")
4. Nested if Statements
What is it?
An if block inside another if block. It checks a second-level
condition only if the first is true.
When to use?
Use when decisions depend on multiple layers of logic.
Why use it?
To build step-by-step condition checks in complex logic flows.
Syntax:
if condition1:
if condition2:
# code if both are true
Example 1:
age = 25
has_id = True
if age >= 18:
if has_id:
print("Entry allowed.")
Example 2:
username = "admin"
password = "1234"
if username == "admin":
if password == "1234":
print("Login successful.")
Example 3:
num = 10
if num > 0:
if num % 2 == 0:
print("Positive even number.")
5. Short-hand if and if-else
What is it?
A compact way to write simple if or if-else statements in
one line.
When to use?
Use only for simple logic that improves readability.
Why use it?
To write cleaner, shorter code for basic decisions.
Single-line if Syntax:
if condition: action
Single-line if-else Syntax:
action_if_true if condition else action_if_false
Example 1
x=5
if x > 0: print("Positive number")
Example 2 (short-hand if-else):
a=7
print("Even") if a % 2 == 0 else print("Odd")
Example 3 (short-hand in variable assignment):
marks = 90
result = "Pass" if marks >= 50 else "Fail"
print(result)
LOOPS IN PYTHON
What is a Loop?
A loop is a programming construct that repeats a block of code
multiple times, as long as a certain condition is true.
Why Use Loops?
Sometimes we want to do something many times, like:
● Print numbers from 1 to 1000
● Go through each student in a class
● Add all numbers in a list
Instead of writing the same code again and again, we use a
loop to repeat that block automatically.
Primarily there are two types of loops in python.
• while loops
• for loops
1.while Loop in Python
A while loop is used to repeat a block of code as long as a
condition is True.
How it works:
1. The condition is checked first.
2. If the condition is True, the loop's body is executed.
3. After the body runs, the condition is checked again.
4. This repeats until the condition becomes False.
Syntax:
while condition:
# Body of the loop
# Statements to be repeated
Example:
# Print numbers from 1 to 5 using while loop
i = 1
while i <= 5:
print(i)
i += 1
Output:
1,2,3,4,5
i Value Condition (i Action
<= 5)
1 True print 1, i = 2
2 True print 2, i = 3
3 True print 3, i = 4
4 True print 4, i = 5
5 True print 5, i = 6
6 False STOP the loop
Example 2
i=0
while i < 5: # print "Neha" – 5 times!
print("Neha")
i=i+1
..2.FOR LOOP in Python
A for loop in Python is used to iterate (loop through) a
sequence — such as:
● A list
● A tuple
● A string
● A range of numbers
This loop repeats code for each item in the sequence.
RANGE FUNCTION IN PYTHON The range() function in python is
used to generate a sequence of number
Syntax:
for item in iterable:
# Body of the loop
# Code to execute for each item
Example:
l = [1, 7, 8]
for item in l:
print(item)
Flow:
1. l = [1, 7, 8]
○ A list named l is created with 3 elements: 1, 7, and 8.
2. for item in l:
○ Python reads: "For each item in the list l..."
3. print(item)
○ This prints the value of item on each loop cycle.
How it works:
Iteration Value of Action
item
1st 1 print(1)
2nd 7 print(7)
3rd 8 print(8)
Output:
1,7,8
1. Iterating Over a String
for char in "Hello":
print(char)
2. Using range() Function
for i in range(5):
print(i)
Output:
0,1,2,3,4
● range(5) generates numbers from 0 to 4.
● Can also use range(start, stop, step) for custom
sequences.
● range(start, stop, step_size)
●
for i in range(0,7): # range(7) can also be used.
print(i) # prints 0 to 6
3. List Iteration with Index
l = [10, 20, 30]
for i in range(len(l)):
print("Index:", i, "Value:", l[i])
Output:
Index: 0 Value: 10
Index: 1 Value: 20
Index: 2 Value: 30
Important Points:
● for loop is used when you know how many times to repeat.
● Works well with iterables (lists, strings, tuples, etc.).
● print() inside the loop is indented to show it's part of the
loop body.
● If indentation is missing, Python will raise an
IndentationError.
FOR LOOP WITH ELSE
An optional else can be used with a for loop if the code is to be
executed when the
loops exhausts.
Example:
l= [1,7,8]
for item in l:
print(item)
else:
print("done") # this is printed when the loop exhausts!
Output:
done
THE BREAK STATEMENT
● ‘break’ is used to come out of the loop when encountered.
It instructs the program to – exit the loop now.
Syntax
for item in iterable:
if condition:
break # exits the loop
while condition:
if condition2:
break # exits the loop
Example:
for i in range (0,80):
print(i) # this will print 0,1,2 and 3
if i==3
Break
When to Use break:
● When you want to stop a loop early if a certain condition is
met.
● Commonly used in searching, menu systems, or games.
Example 1: Breaking a for loop
for i in range(1, 10):
if i == 5:
print("Found 5! Breaking the loop.")
break
print("Current number:", i)
Output:
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Found 5! Breaking the loop.
Example 2: Breaking a while loop
count = 1
while count <= 10:
if count == 4:
print("Stopping loop at", count)
break
print("Count is", count)
count += 1
Output:
Count is 1
Count is 2
Count is 3
Stopping loop at 4
Note:
● After break, the loop is completely exited.
● Code after the loop continues as normal.
Use Case Example: Searching in a List
names = ["Neha", "Sunita", "Ishita", "Gitika"]
search = "Devita"
for name in names:
if name == search:
print("Name found:", name)
break
● What will be the output?
for i in range(5)://
if i == 3:
break
print(i)
The continue Statement in Python
Definition:
The continue statement is used to skip the current iteration of
a loop and move to the next one.
When to Use continue:
● When you want to ignore specific values or conditions in a
loop.
● Helps to filter out unwanted cases during iteration.
Syntax:
for item in iterable:
if condition:
continue # skips to next loop iteration
# rest of the loop code
while condition:
if condition2:
continue
Example 1: Skipping even numbers
for i in range(1, 6):
if i % 2 == 0:
continue
print("Odd number:", i)
Output:
Odd number: 1
Odd number: 3
Odd number: 5
Example 2: Using in while loop
i = 0
while i < 5:
i += 1
if i == 3:
continue
print("i is", i)
Output:
i is 1
i is 2
i is 4
i is 5
Comparison with break:
Feature break continue
Action Exits the entire loop Skips current iteration
only
Use case When loop should When some values should
stop early be skipped
Summary:
● continue is used to skip the rest of the loop body for
certain conditions.
● The loop continues with the next iteration.
● Useful for filtering data, ignoring values, or customizing
loop flow.
What will be the output
for i in range(1, 5):
if i == 3:
continue
print(i)
1. What is a Function?
A function is a block of code that runs only when it is called. It
helps break programs into smaller, reusable pieces.
Why Use Functions?
● Reusability (write once, use many times)
● Makes the code organized and clean
● Helps with debugging and maintenance
2. Function Syntax
def function_name(parameters):
# code block
return result
The syntax of a function looks as follows:
def func1():
print('hello')
This function can be called any number of times, anywhere in
the program.
FUNCTION CALL
Whenever we want to call a function, we put the name of the
function followed by parentheses as follows:
func1() # This is called function
Quick Quiz: Write a program to greet a user with “Good day”
using functions.
TYPES OF FUNCTIONS IN PYTHON
There are two types of functions in python:
• Built in functions (Already present in python)
• User defined functions (Defined by the user) Examples of built
in functions includes len(), print(), range() etc. The func1()
function we defined is an example of user defined function.
1.Example:
def greet():
print("Hello, welcome to Python!")
greet() # calling the function
DEFAULT PARAMETER VALUE
We can have a value as default as default argument in a
function.
If we specify name = “stranger” in the line containing
def, this value is used when no
argument is passed.
Example:
def greet(name = "stranger"):
# function body
greet() # name will be "stranger" in function body
(default)
greet("neha") # name will be "neha" in function body
(passed)
3. Function with Parameters
Functions can take inputs called parameters or
arguments.
def greet(name):
print("Hello", name)
greet("Devita")
Output:
Hello Devita
4. Return Statement
You can use return to return a value from a function.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
5. Types of Arguments
Type Description
Required Must be passed in the correct
order
Keyword Passed using name=value syntax
Default Argument with a default value
Variable Can take any number of
-length arguments (*args, **kwargs)
Examples:
Required & Keyword Arguments:
def student(name, age):
print(name, age)
student("Devita", 23) # Positional
student(age=23, name="Devita") # Keyword
Default Argument:
def greet(name="Guest"):
print("Hello", name)
greet()
greet("Devita")
Variable-length Argument:
def add_all(*numbers):
total = 0
for num in numbers:
total += num
return total
print(add_all(1, 2, 3, 4)) # Output: 10
6. Scope of Variables
● Local Variable: Defined inside a function, used
only inside it
● Global Variable: Defined outside all functions
x = 10 # Global
def func():
x = 5 # Local
print("Inside:", x)
func()
print("Outside:", x)
Output:
Inside: 5
Outside: 10
7. Recursion (Function Calling Itself)
A recursive function is a function that calls itself.
Example: Factorial
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print(factorial(5)) # Output: 120
Note: Always include a base case to avoid infinite
recursion.
#Full stack Batch
8. Lambda (Anonymous Function)
A short function without a name, mostly used in
one-line expressions.
square = lambda x: x * x
print(square(5)) # Output: 25
9. Function Inside Function (Nested
Function)
def outer():
def inner():
print("Inner function")
inner()
outer()
10. *args vs **kwargs
Name Use Case Type
*args Multiple Tuple
positional
arguments
**kwarg Multiple Dictionary
s keyword
arguments
def show_details(*args, **kwargs):
print(args)
print(kwargs)
show_details("Python", "Function", name="Devita",
age=23)
Summary Chart:
Concept Description Example
Simple Function Basic reusable block def greet():
With Parameters Inputs to function def add(a, b):
With Return Gives back result return a + b
Value
Default Has default value if def
Parameter not passed greet(name="Guest
")
*args Variable number of def f(*args)
positional args
**kwargs Variable keyword def f(**kwargs)
args
Lambda One-line anonymous lambda x: x+1
function
Recursion Function calling factorial(n)
itself
Task:
1. Write a program using functions to find the greatest
of three numbers.
2.Write a function that takes two numbers as input and
returns their sum.
3.Write a function that checks whether a number is even
or odd.
Python built-in functions:
1.Basic Functions
Function Description
print() Prints output to the screen
input() Takes input from the user
type() Returns the type of an
object
id() Returns the identity
(memory address)
2.Conversion Functions:
Function Description
int() Converts to integer
float() Converts to float
str() Converts to string
bool() Converts to boolean
list() Converts to list
tuple() Converts to tuple
set() Converts to set
dict() Converts to dictionary
ord() Converts character to
Unicode code
chr() Converts Unicode to
character
bin() Converts to binary
hex() Converts to hexadecimal
oct() Converts to octal
3.Mathematical Functions
Function Description
abs() Returns absolute value
round() Rounds a number
pow() Returns x raised to the
power y
divmod() Returns quotient and
remainder
sum() Returns sum of all items
min() Returns minimum value
max() Returns maximum value
Task 1: Rock, Paper, Scissors Game
Description:
Write a Python program to play Rock, Paper, Scissors
with the user. Use random module to generate computer’s
choice.
Concepts Used: random, if-else, input()
Task 2: Number Guessing Game
Description:
The program randomly picks a number between 1 and 100.
The user must guess the number. After each guess, the
program tells the user whether the guess is too low,
too high, or correct.
Concepts Used: random, while, input()
Task 3: Odd or Even Game
Description:
Ask the user to input a number. The computer randomly
chooses one too. If the sum of both is even, the "Even"
player wins, else "Odd" player wins. Alternate
user/computer roles each time.
Concepts Used: random, if-else, functions
Task 4: Simple Calculator
Description:
Make a basic calculator that takes two numbers and an
operator (+, -, *, /) from the user and returns the
result.
Concepts Used: input(), functions, if-elif-else
Task 5: Lucky Draw Game
Description:
Create a program where 10 random names are put in a
list. The program randomly selects one as the winner.
Concepts Used: random.choice(), lists, functions
Object-Oriented Programming (OOP) in
Python
Solving a problem by creating objects is one of
the most popular approaches in programming. This
is called object-oriented programming. This
concept focuses on using reusable code (DRY
Principle).
1. What is OOP?
OOP is a programming style based on objects and
classes. It helps you structure code by bundling
data and behavior together.
Key Benefits:
● Reusability
● Scalability
● Organization
● Real-world modeling
2. Important OOP Concepts
Concept Description
Class Blueprint for creating objects
Object Instance of a class
Constructor Special method to initialize
objects (__init__)
Self Refers to the current object
Inheritance One class can inherit from
another
Encapsulati Hide internal details from
on outside
Polymorphis Same method behaves differently
m in different classes
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties
and methods.
A Class is like an object constructor, or a "blueprint" for
creating objects.
Create a Class
To create a class, use the keyword class:
Create a class named MyClass, with a property named x:
class MyClass:
x = 5
print(MyClass)
Create Object
Now we can use the class named MyClass to create objects:
Create an object named p1, and print the value of x:
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
The __init__() Function
When we create a class in Python, one special method you will
often see is called __init__(). This method is known as the
constructor.
What is __init__()?
● It is a built-in method.
● Automatically called when you create (instantiate) an
object from a class.
● Used to initialize the object's properties (also called
attributes).
● You can also perform any setup or operations that need to
happen as soon as an object is created.
Why use __init__()?
Imagine you want each student object to have a name and age
assigned as soon as it is created. The __init__() method lets
you do that immediately without needing to call a separate
setup function.
Syntax of __init__() method
class ClassName:
def __init__(self, parameters):
# initialize object properties
self.property1 = parameter1
self.property2 = parameter2
# other setup code if needed
● The first parameter is always self (which represents the
object being created).
● Other parameters are passed during object creation to set
initial values.
Example of __init__() in action:
class Student:
def __init__(self, name, age):
self.name = name # Assign name property
self.age = age # Assign age property
def display(self):
print("Name:", self.name)
print("Age:", self.age)
# Create objects with initial values
student1 = Student("Devita", 22)
student2 = Student("Ishita", 25)
student1.display()
student2.display()
Output:
Name: Devita
Age: 22
Name: Ishita
Age: 25
● When you write student1 = Student("Devita", 22),
Python:
○ Creates a new Student object.
○ Automatically calls the __init__() method with self
referring to this new object, name as "Devita", and
age as 22.
○ Inside __init__(), the values "Devita" and 22 are
assigned to the object's properties self.name and
self.age.
● The object is now ready with these initial values.
Summary:
● __init__() is called automatically when you create an
object.
● It initializes the object's properties.
● Helps in creating objects with different data easily.
● Makes your classes flexible and useful in real applications.
Using Default Values in __init__()
Sometimes you want to make some parameters optional — if
the user doesn't provide a value, the object uses a default one.
Example with Default Values:
class Student:
def __init__(self, name="Unknown", age=18):
self.name = name
self.age = age
def display(self):
print("Name:", self.name)
print("Age:", self.age)
# Create object without arguments (uses defaults)
student1 = Student()
# Create object with some arguments
student2 = Student("Devita")
# Create object with all arguments
student3 = Student("Ishita", 25)
student1.display()
student2.display()
student3.display()
l=[student1,student2,student3]
Output:
Name: Unknown
Age: 18
Name: Devita
Age: 18
Name: Ishita
Age: 25
- INHERITANCE & MORE ON OOPS
Inheritance allows a class (child) to inherit the properties and methods
of another class (parent).
Syntax:
class Parent:
def func1(self):
print("This is Parent class")
class Child(Parent):
def func2(self):
print("This is Child class")
class Employee: # Base class
# Code
class Programmer(Employee): # Derived or child class
# Code
We can use the method and attributes of ‘Employee’ in ‘Programmer’
object.
Also, we can overwrite or add new attributes and methods in
‘Programmer’ class.
TYPES OF INHERITANCE
• Single inheritance
• Multiple inheritance
• Multilevel inheritance
SINGLE INHERITANCE
Single inheritance occurs when child class inherits only a single parent
class
Base
||
Derived
# Parent Class
class Animal:
def speak(self):
print("Animals make sounds")
# Child Class inheriting from Animal
class Dog(Animal):
def bark(self):
print("Dog barks")
# Create object of Dog
d = Dog()
d.speak() # Inherited from Animal class
d.bark() # Defined in Dog class
Animal is the parent/base class.
Dog is the child/derived class that inherits from Animal.
Dog can use both speak() (from Animal) and bark() (its own method).
MULTIPLE INHERITANCE
Multiple Inheritance occurs when the child class inherits from more than
one parent classes.
Example:
# First Parent Class
class Father:
def skills(self):
print("Father: Knows gardening and carpentry")
# Second Parent Class
class Mother:
def skills(self):
print("Mother: Knows cooking and painting")
# Child Class inheriting from both Father and Mother
class Child(Father, Mother):
def own_skills(self):
print("Child: Knows programming")
# Create object of Child
c = Child()
c.skills() # Which skills()? Depends on MRO (Method
Resolution Order)
c.own_skills() # Child's own method
Child class inherits from both Father and Mother.
When calling c.skills(), Python looks at the first class
in the inheritance list, which is Father here (based on
MRO).
You can use super() to handle ambiguity or override
methods if needed.
3.MULTILEVEL INHERITANCE
When a child class becomes a parent for another child
class.
Example:
# Base Class
class Grandfather:
def show_grandfather(self):
print("Grandfather: Loves farming")
# Intermediate Class inheriting from Grandfather
class Father(Grandfather):
def show_father(self):
print("Father: Loves teaching")
# Derived Class inheriting from Father
class Son(Father):
def show_son(self):
print("Son: Loves coding")
# Create object of Son
s = Son()
s.show_grandfather() # Inherited from Grandfather
s.show_father() # Inherited from Father
s.show_son() # Defined in Son
Grandfather → Father → Son
Each class inherits the properties and methods from the
class above it.
The Son class can access all methods from Father and
Grandfather.
● SUPER() METHOD
super() method is used to access the methods of a super
class in the derived class.
super().__init__() # __init__() Calls constructor of the
base class
super() is used to call a method (usually __init__)
from the parent class in a child class. It helps in
reusing code and avoiding duplication, especially in
inheritance.
Example:
# Parent class
class Person:
def __init__(self):
print("Person constructor called")
# Child class
class Student(Person):
def __init__(self):
super().__init__() # Call the constructor of Person
print("Student constructor called")
# Create an object
s = Student()
Why use super()?
● Reuse code from parent class.
● Maintain clean and DRY (Don't Repeat Yourself) code.
● Useful in multilevel and multiple inheritance to
manage method resolution.
Example:
class Animal:
def sound(self):
print("Animal makes a sound")
class Dog(Animal):
def sound(self):
super().sound() # Call parent method
print("Dog barks")
d = Dog()
d.sound()
CLASS METHOD
A class method is a method which is bound to the class and not
the object of the class.
@classmethod decorator is used to create a class method.
● Defined using the @classmethod decorator
● Takes cls as its first parameter instead of self
Syntax:
class MyClass:
class_variable = 0
@classmethod
def my_class_method(cls):
print("Accessing class_variable:",
cls.class_variable)
Example:
class Student:
school_name = "ABC School" # Class variable
def __init__(self, name):
self.name = name # Instance variable
@classmethod
def change_school(cls, new_name):
cls.school_name = new_name
# Before changing
print(Student.school_name)
# Change school using class method
Student.change_school("XYZ School")
# After changing
print(Student.school_name)
Output:
ABC School
XYZ School
Exception Handling in Python –
1. What is an Exception?
An exception is a runtime error that occurs during
the execution of a program, which interrupts the
normal flow of instructions.
Unlike syntax errors, exceptions occur after the code
is syntactically correct, but something unexpected
happens during execution.
Examples of exceptions:
print(10 / 0) # ZeroDivisionError
int("abc") # ValueError
my_list = [1, 2]
print(my_list[5]) # IndexError
open("abc.txt", "r") # FileNotFoundError
2. Why Exception Handling is Needed?
Without exception handling:
● The program stops execution at the point of
error.
● It can show an ugly traceback to the user.
● Sensitive operations like file handling or
database connections may remain open or unstable.
With exception handling:
● You can gracefully catch and handle errors.
● Prevent program crash.
● Provide custom error messages.
3. Basic Syntax of Exception Handling
try:
# Code that might throw an exception
except ExceptionType:
# Code to handle the exception
4. Example 1: Handling Division by Zero
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
Explanation:
● try: Code that may raise an error.
● except: If ZeroDivisionError occurs, this block
is executed.
5. Multiple except Blocks
You can handle different exceptions separately:
try:
a = int(input("Enter number A: "))
b = int(input("Enter number B: "))
result = a / b
print("Result:", result)
except ZeroDivisionError:
print("Division by zero is not allowed.")
except ValueError:
print("Please enter valid numbers.")
6. Generic Exception Handling
try:
x = int(input("Enter number: "))
y = 10 / x
except Exception as e:
print("An error occurred:", e)
This catches any exception type. Useful for logging
or debugging.
7. else Clause
The else block executes only if the try block runs
without any exception.
try:
x = int(input("Enter number: "))
except ValueError:
print("Not a valid number.")
else:
print("Valid input:", x)
8. finally Clause
The finally block is always executed regardless of
whether an exception occurred or not.
try:
f = open("data.txt", "r")
print(f.read())
except FileNotFoundError:
print("File not found.")
finally:
print("Finished trying to read the file.")
9. Handling Multiple Exceptions in a Single
Block
try:
num = int(input("Enter a number: "))
print(10 / num)
except (ValueError, ZeroDivisionError) as e:
print("Error occurred:", e)
10. Nested try Blocks
try:
a = int(input("Enter A: "))
try:
b = int(input("Enter B: "))
print(a / b)
except ZeroDivisionError:
print("Inner block: Cannot divide by zero.")
except ValueError:
print("Outer block: Invalid input.")
11. Raising Exceptions Manually
You can raise exceptions using raise.
age = int(input("Enter your age: "))
if age < 18:
raise ValueError("Age must be at least 18.")
else:
print("Access granted.")
12. Custom Exceptions (User-Defined)
You can create your own exceptions by defining a
class that inherits from Exception.
class AgeTooSmallError(Exception):
pass
age = int(input("Enter your age: "))
if age < 18:
raise AgeTooSmallError("Custom Exception: Age is
too small!")
13. Real-Life Example: File Handling with
Exception
try:
file = open("students.txt", "r")
content = file.read()
print(content)
except FileNotFoundError:
print("The file you're trying to open does not
exist.")
finally:
print("File operation complete.")
14. Real-Life Example: List Access
try:
students = ["Alice", "Bob", "Charlie"]
index = int(input("Enter index: "))
print("Student:", students[index])
except IndexError:
print("Index out of range.")
except ValueError:
print("Invalid index input.")
15. Summary Table of Keywords
Keyword Description
try Block that contains
risky code
except Handles the error if it
occurs
else Executes if no error
occurred in try
finally Executes whether error
occurs or not
raise Manually raise an
exception
16. Best Practices
● Always catch specific exceptions (avoid catching
Exceptions unless necessary).
● Use finally for cleanup (closing files, releasing
resources).
● Don't silence exceptions—provide clear messages
or logging.
● Validate inputs to reduce exceptions.
Task
1.Ask the user to input age. Raise a ValueError
manually if age is less than 18.
2.Create a custom exception PasswordTooShortError.
Ask the user to enter a password and raise the custom
error if it's less than 6 characters.
3.Write a calculator that supports +, -, *, /
operations based on user input. Handle:
● ValueError
● ZeroDivisionError
● Invalid operator
1.
try:
age = int(input("Enter your age: "))
if age < 18:
raise ValueError("Age must be at least 18.")
print("Age accepted.")
except ValueError as ve:
print("Error:", ve)
2.class PasswordTooShortError(Exception):
pass
try:
password = input("Enter your password: ")
if len(password) < 6:
raise PasswordTooShortError("Password must be
at least 6 characters long.")
print("Password accepted.")
except PasswordTooShortError as e:
print("Error:", e)
3.
try:
num1 = float(input("Enter first number: "))
operator = input("Enter operator (+, -, *, /): ")
num2 = float(input("Enter second number: "))
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 == 0:
raise ZeroDivisionError("Cannot divide by
zero.")
result = num1 / num2
else:
raise ValueError("Invalid operator.")
print("Result:", result)
except ValueError as ve:
print("Input Error:", ve)
except ZeroDivisionError as zde:
print("Math Error:", zde)
Multithreading and
Multiprocessing in Python
1. Introduction
Modern programs often require performing multiple
tasks simultaneously. Python provides two primary
ways to achieve concurrency:
● Multithreading: Used for I/O-bound tasks.
● Multiprocessing: Used for CPU-bound tasks.
2. Multithreading in Python
What is a Thread?
A thread is the smallest unit of execution in a
process. Multiple threads can run in a single process
and share the same memory space.
Why Use Multithreading?
Multithreading is beneficial when a program spends a
lot of time waiting for external resources such as
disk I/O or network access. It allows other threads
to continue execution during these waits.
Important Module: threading
Basic Multithreading Example
import threading
import time
def display():
for i in range(5):
print(f"Thread running: {i}")
time.sleep(1)
# Creating two threads
t1 = threading.Thread(target=display)
t2 = threading.Thread(target=display)
# Starting threads
t1.start()
t2.start()
# Wait for both threads to finish
t1.join()
t2.join()
print("Multithreading complete")
Key Points
● Thread() is used to create a thread.
● start() begins the thread execution.
● join() waits for the thread to complete.
Use Case: I/O-Bound Tasks
Multithreading is ideal for applications like:
● Downloading files
● Web scraping
● Handling user input/output
● Network calls
3. Multiprocessing in Python
What is a Process?
A process is an instance of a program. It has its own
memory space and resources. Unlike threads, processes
do not share memory.
Why Use Multiprocessing?
Multiprocessing is useful for programs that are
CPU-bound, such as:
● Complex mathematical calculations
● Image or video processing
● Machine learning model training
Important Module: multiprocessing
Basic Multiprocessing Example
import multiprocessing
import time
def compute():
for i in range(5):
print(f"Process running: {i*i}")
time.sleep(1)
if __name__ == '__main__':
# Creating two processes
p1 = multiprocessing.Process(target=compute)
p2 = multiprocessing.Process(target=compute)
# Starting processes
p1.start()
p2.start()
# Wait for both processes to finish
p1.join()
p2.join()
print("Multiprocessing complete")
Key Points
● Process() is used to create a new process.
● Each process runs in its own memory space.
● Processes do not share variables.
Use Case: CPU-Bound Tasks
Multiprocessing is ideal for:
● Performing large calculations
● Heavy data processing
● Scientific computing
4. Global Interpreter Lock (GIL)
● GIL is a mechanism in CPython that allows only
one thread to execute Python bytecode at a time.
● This means multithreading does not achieve true
parallelism in CPU-bound tasks.
● Multiprocessing bypasses this limitation by using
separate processes.
5. Comparison Table
Feature Multithreading Multiprocessing
Memory Shared memory Each process has its
Sharing between threads own memory
Performan Good for I/O-bound Good for CPU-bound
ce tasks tasks
Overhead Less More
True No (because of Yes
Paralleli GIL)
sm
Use Case Web scraping, file Data processing, ML
I/O training
Crash One thread crash One process crash does
Safety can affect others not affect others
Module threading multiprocessing
Used
6. When to Use What?
● Use Multithreading when:
○ The program is I/O bound.
○ You want lightweight concurrency.
○ Memory consumption should be low.
● Use Multiprocessing when:
○ The program is CPU bound.
○ True parallel execution is needed.
○ Processes must run independently.
7. Real-world Examples
Multithreading Example: Downloading Webpages
import threading
import requests
def download(url):
print(f"Downloading {url}")
response = requests.get(url)
print(f"Finished downloading {url}:
{len(response.content)} bytes")
urls = [
"https://example.com",
"https://example.org",
"https://example.net"
threads = []
for url in urls:
t = threading.Thread(target=download,
args=(url,))
threads.append(t)
t.start()
for t in threads:
t.join()
print("All downloads completed")
Multiprocessing Example: Calculating Squares
import multiprocessing
def calculate_squares(numbers):
result = [n * n for n in numbers]
print(f"Squares: {result}")
if __name__ == "__main__":
numbers = [1, 2, 3, 4, 5]
p =
multiprocessing.Process(target=calculate_squares,
args=(numbers,))
p.start()
p.join()
8. Summary
● Multithreading: Lightweight, shared memory,
affected by GIL, ideal for I/O tasks.
● Multiprocessing: Heavyweight, isolated memory,
true parallelism, ideal for CPU-heavy tasks.
● Python supports both via built-in modules
(threading and multiprocessing).
● Always choose the right one depending on your
task type.