Python Year - 2020 - 2023
Python Year - 2020 - 2023
Subject:
1. Arithmetic Operators
3. Logical Operators
4. Assignment Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators
These operators perform mathematical operations like addition, subtraction,
multiplication, etc.
- Subtraction 10 - 3 → 7
* Multiplication 4 * 3 → 12
// Floor Division 10 // 3 → 3
% Modulus (Remainder) 10 % 3 → 1
** Exponent (Power) 2 ** 3 → 8
Real-life Example:
If you are calculating total marks:
math = 88
science = 92
total = math + science
print(total) # 180
Example:
age = 18
print(age >= 18) # True
3. Logical Operators
Real-life Example:
age = 20
citizen = True
print(age > 18 and citizen) # True
4. Assignment Operators
These operators assign values to variables.
%= Modulus assign x %= 3
Example:
x = 10
x += 5
print(x) # 15
5. Bitwise Operators
These operators work on bits (0s and 1s). Used in low-level programming.
Operator Meaning
& AND
` `
^ XOR
~ NOT
<< Left shift
>> Right shift
Example:
print(5 & 3) # 1
6. Membership Operators
Used to check whether a value exists in a sequence (list, tuple, string, etc.)
Operator Meaning
in True if value exists
not in True if value does not exist
Example:
7. Identity Operators
Used to compare the memory location of two objects.
Operator Meaning
is True if both refer to same object
is not True if they refer to different objects
Example:
a = [1,2,3]
b=a
Conclusion
Python operators allow the language to perform a wide variety of tasks,
from simple arithmetic to logical decisions, memory identity checks,
membership checks, and bitwise operations. Understanding operators is
essential for writing efficient and powerful Python programs.
Answer:
Types of Typecasting
There are two main categories:
1. Implicit Typecasting
Done automatically by Python
Example:
a = 5 # int
b = 3.5 # float
c = a + b # Python automatically converts 'a' to float
print(c) # 8.5
2. Explicit Typecasting
Done manually by the programmer
1. int()
Converts the given value into an integer.
If a float is passed, the decimal part is removed (truncated).
Syntax
int(value)
Example Program
num = "25"
result = int(num)
print(result) # 25
print(type(result)) # <class 'int'>
Syntax
float(value)
Example Program
num = "12"
result = float(num)
print(result) # 12.0
print(type(result)) # <class 'float'>
3. str()
Converts a value into a string.
Syntax
str(value)
Example Program
age = 20
result = str(age)
print(result) # "20"
print(type(result)) # <class 'str'>
4. list()
Converts a sequence (string, tuple, set) into a list.
Syntax
list(value)
text = "ABC"
result = list(text)
print(result) # ['A', 'B', 'C']
5. tuple()
Converts a sequence into a tuple (immutable).
Syntax
tuple(value)
Example Program
numbers = [1, 2, 3]
result = tuple(numbers)
print(result) # (1, 2, 3)
6. set()
Converts a sequence into a set (removes duplicates).
Syntax
set(value)
Example Program
data = [1, 2, 2, 3, 3, 3]
result = set(data)
print(result) # {1, 2, 3}
7. bool()
Converts a value into Boolean (True/False).
bool(value)
Example Program
print(bool(0)) # False
print(bool(10)) # True
print(bool("")) # False
print(bool("Hi")) # True
8. complex()
Converts a value into a complex number.
Syntax
complex(real, imaginary)
Example Program
num = complex(4, 6)
print(num) # (4+6j)
⭐ Summary Table
Function Converts To Example
int() integer int("10") → 10
Answer:
In Python, conditional statements are used to control the flow of a program
based on certain conditions.
They allow the program to make decisions and execute different blocks of
code depending on whether a condition is True or False.
Python mainly provides four types of conditional statements:
1. if Statement
The if statement executes a block of code only when the given condition is
True.
It is used for simple one-way decision making.
Syntax
if condition:
statements
Explanation
If the condition evaluates to True → statements run.
2. if–else Statement
The if–else statement provides two paths.
If the condition is True, one block executes; otherwise, the else block
executes.
Syntax
if condition:
statements
Explanation
Used when an alternative action is needed for False conditions.
3. if–elif–else Ladder
When multiple conditions must be checked one after another, the if–elif–else
ladder is used.
Only the first block whose condition becomes True gets executed.
Syntax
if condition1:
statements
elif condition2:
statements
elif condition3:
statements
else:
statements
Explanation
Used for multi-way decision making.
4. Nested if Statement
A nested if means one if statement inside another.
It is used when decisions depend on multiple levels of conditions.
Syntax
if condition1:
if condition2:
statements
Explanation
Helps to check conditions inside another condition.
⭐Marks
Program to Display the Result of a Student Based on
The program below accepts marks from the user and displays the result
category.
Python Program
33–44 → Pass
Below 33 → Fail
1. Definition
List
A list is a mutable (changeable) sequence of elements.
Tuple
A tuple is an immutable (unchangeable) sequence of elements.
Once created, its values cannot be modified.
2. Syntax
List Syntax
Tuple Syntax
3. Mutability
List
Tuple
Elements cannot be changed, added, or removed.
4. Performance
List
Slower because it is mutable and uses more memory.
Tuple
Faster and more memory-efficient.
5. Use Cases
List
Best for dynamic data
Tuple
Best for fixed data
my_list = [1, 2, 3]
my_list[1] = 20 # Modifying second element
print(my_list)
[1, 20, 3]
my_tuple = (1, 2, 3)
my_tuple[1] = 20 # This will cause an error
Output:
1. break Statement
The break statement is used to terminate the loop immediately, even if the
loop condition is still true.
Key Points
Stops the loop completely.
Syntax
Example
Output
1
2
3
4
Explanation
Loop is running from 1 to 9
When num becomes 5, the break statement stops the entire loop
Key Points
Skips current iteration only
Syntax
Example
Output
1
2
3
4
6
7
8
9
Answer:
Slicing in Python is a technique used to extract a portion (sub-sequence) of
elements from string, list, tuple, or any sequence type.
It allows accessing a range of elements using a start, stop, and step value.
Slicing is useful for:
Reversing sequences
Skipping elements
General Syntax
Parameters
start → index from where slicing begins
To slice an iterator, Python provides the islice() method from the itertools
module.
Syntax
Points
Works on any iterator (files, generators, loops, etc.)
Memory-efficient
Expected Output
3
5
7
9
11
statement.
Characteristics of Functions
1. Reusable Code – write once, use many times.
def function_name(parameters):
statements
return value
Explanation of Syntax
def → keyword used to define a function
First number = 0
Second number = 1
Example:
0, 1, 1, 2, 3, 5, 8, 13 …
Python Program
def fibonacci(n):
a, b = 0, 1
print("Fibonacci Series:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b
fibonacci(num)
Inside the loop, the program prints the current number ( a ) and then
updates:
new a = old b
calculate it.
👉 If you write a Python expression inside a string, will execute it and
eval()
Syntax
eval("expression")
Python Program
Example Input
Output
Result = 20
Another example:
Input:
(50 + 30) / 4
Output:
20.0
Short Summary
eval() → evaluates string expressions like Python code.
Uninstall libraries
Python uses a package manager called pip (Python Installer for Packages).
With pip, you can easily install thousands of external packages available on
PyPI (Python Package Index).
pip --version
import requests
import requests
Output (Example)
Short Summary
Python’s package manager = pip
Answer:
1. try
The try block contains the code that might cause an exception.
Syntax
try:
# code that may cause an error
2. except
The except block handles the exception if it occurs.
Syntax
except ExceptionType:
# code to run if that particular exception occurs
except:
# handles all exceptions
3. else
The else block runs only if no exception occurs in the try block.
Syntax
else:
# code that executes if no error occurs
Syntax
finally:
# code that runs always
5. raise
Used to manually raise an exception.
Syntax
try:
a = 10 / 2
print("Result:", a)
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("No error occurred.")
finally:
print("Execution completed.")
Problem:
User enters a string like "abc", but we try to convert it into an integer →
causes ValueError .
# trying to typecast
number = int(value)
except ValueError:
print("Error: Invalid input! Please enter a numeric value only.")
finally:
print("Program ended.")
Explanation:
If user enters "25" → program converts successfully.
Enter a number: 56
You entered: 56
Program ended.
Definition
A Regular Expression (Regex) is a special sequence of characters that
forms a search pattern.
It is used to check whether a string contains a specific pattern or not.
Searching text
Replacing text
Splitting strings
1. [Link]()
Searches for first match of pattern in string.
2. [Link]()
3. [Link]()
Returns all matches in a list.
4. [Link]()
Splits string based on pattern.
5. [Link]()
Replaces all occurrences of a pattern.
import re
if [Link](r"\d+", text):
print("Digits found!")
import re
emails = [Link](r"[A-Za-z0-9._%+-]+@[A-Za-z.-]+\.[A-Za-z]{2,}", te
xt)
print(emails)
import re
print(new_text)
(b) Decorators
Answer:
A Decorator in Python is a special feature that allows a programmer to add
new functionality to an existing function without modifying its original
code.
Decorators use the concept of higher-order functions and closures.
Simple Definition
A Decorator is a function that takes another function as input, adds extra
features to it, and returns the modified function.
Add logging
Validate arguments
Syntax of a Decorator
def decorator_name(original_function):
def wrapper():
# extra code
original_function()
# extra code
return wrapper
@decorator_name
def function():
pass
Real-Life Analogy
Think of a decorator as adding toppings on a pizza.
The base stays the same, but the final output becomes more powerful.
def my_decorator(func):
def wrapper():
print("Before the function runs")
func()
@my_decorator
def greet():
print("Hello, Python!")
greet()
Output
Explanation
my_decorator adds extra lines before and after the main function.
The original function greet() is not changed, but its output is enhanced.
def smart_divide(func):
def wrapper(a, b):
if b == 0:
print("Error: Cannot divide by zero!")
return
return func(a, b)
return wrapper
@smart_divide
def divide(a, b):
print("Result:", a/b)
divide(10, 2)
divide(5, 0)
2. Authorization
Check if a user has permission.
3. Performance measurement
Calculate time taken by a function.
4. Input validation
Check if arguments are correct.
5. Caching
Save frequently used results.
6. Web frameworks
Used heavily in Django & Flask for URL routing and authentication.
Exam-Focused Summary
A decorator modifies a function without changing its actual code.
Definition
A dynamically typed language is a programming language in which the
type of a variable is determined automatically at runtime, rather than
being explicitly declared by the programmer.
This means you do not need to declare the data type of a variable
before using it.
Features
1. No Type Declaration Required
You can directly assign a value to a variable without mentioning its type.
Examples
x = 10 # x is an integer
print(type(x))
Output
<class 'int'>
<class 'str'>
y = 5.5 # float
y = y + 2 # still float
y = "Python" # now string
print(y)
2. Faster Development
Less boilerplate code; flexible coding.
Disadvantages
1. Type-Related Errors at Runtime
Errors like adding a string to a number are detected only when program
runs.
2. Slower Execution
Type checking happens at runtime, so may reduce performance
compared to statically typed languages.
Offers flexibility and ease of coding, but may cause runtime type
errors.
Definition
A Garbage Collector is a process in Python that automatically frees
memory of objects that are no longer referenced by the program, so that
the memory can be reused.
If objects are no longer needed but still occupy memory, it can lead to
memory waste.
Points
1. Automatic Memory Management – no need for manual deletion in most
cases.
4. Cycles Handling – detects and frees objects that reference each other.
Syntax
import gc
Example
import gc
class MyClass:
def __del__(self):
print("Object deleted")
# Create object
obj = MyClass()
Output
Object deleted
Exam Summary
Garbage Collector automatically frees memory occupied by objects no
longer in use.