0% found this document useful (0 votes)
6 views42 pages

Python Year - 2020 - 2023

The document explains Python operators, typecasting, conditional statements, lists, tuples, and loop control statements. It details various types of operators, typecasting functions, and conditional structures, providing examples for clarity. Additionally, it compares lists and tuples, highlighting their differences, and describes the use of break and continue statements in loops.

Uploaded by

nekowex210
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)
6 views42 pages

Python Year - 2020 - 2023

The document explains Python operators, typecasting, conditional statements, lists, tuples, and loop control statements. It details various types of operators, typecasting functions, and conditional structures, providing examples for clarity. Additionally, it compares lists and tuples, highlighting their differences, and describes the use of break and continue statements in loops.

Uploaded by

nekowex210
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

Year : 2020 - 2023

Subject:

1. What is Operator in Python ? Explain each type of operator with suitable


example.
Answer:
In Python, an operator is a special symbol that performs an operation on
values or variables. Operators allow Python to perform actions such as
arithmetic calculations, comparisons, logical decisions, assignments,
and more. The values on which an operator works are called operands.
For example, in the expression 10 + 5 ,
+ is the operator and 10 , 5 are operands.
Python supports many types of operators, and each of them is used for a
different purpose.

Types of Operators in Python


Python provides the following categories of operators:

1. Arithmetic Operators

2. Relational / Comparison 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.

Year : 2020 - 2023 1


Operator Description Example
+ Addition 10 + 3 → 13

- Subtraction 10 - 3 → 7

* Multiplication 4 * 3 → 12

/ Float Division 10 / 3 → 3.33

// 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

2. Comparison (Relational) Operators


These operators compare two values and return True or False.

Operator Meaning Example


== Equal to 5 == 5 → True

!= Not equal to 5 != 3 → True

> Greater than 10 > 4 → True

< Less than 3 < 1 → False

>= Greater or equal 7 >= 7 → True

<= Less or equal 2 <= 5 → True

Example:

age = 18
print(age >= 18) # True

3. Logical Operators

Year : 2020 - 2023 2


These operators combine multiple conditions.

Operator Explanation Example


and True only if both are True 5 > 2 and 3 > 1 → True

or True if any one is True 5 > 10 or 3 > 1 → True

not Reverses condition not(5 > 3) → False

Real-life Example:

age = 20
citizen = True
print(age > 18 and citizen) # True

4. Assignment Operators
These operators assign values to variables.

Operator Meaning Example


= Assign x=5

+= Add and assign x += 3 → x = x + 3

-= Subtract and assign x -= 3

*= Multiply and assign x *= 3

/= Divide and assign x /= 3

%= 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

Year : 2020 - 2023 3


Operator Meaning

` `
^ XOR
~ NOT
<< Left shift
>> Right shift

Example:

print(5 & 3) # 1

(5 → 101, 3 → 011, bitwise AND → 001)

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:

fruits = ['apple', 'banana', 'mango']


print('apple' in fruits) # True

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

Year : 2020 - 2023 4


print(a is b) # True (same memory object)

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.

2. What is Typecasting? How do we perform typecasting in Python ? Explain


each function used in typecasting with syntax and program.

Answer:

Typecasting in Python refers to the process of converting one data type


into another.

Python is a dynamically typed language, which means a variable’s type is


decided at runtime.

However, there are many situations where the programmer needs to


convert a value explicitly from one type to another—for example,
converting string input to integer or converting a float value to an integer.

Typecasting helps in:

performing mathematical operations on user input

storing data in the correct format

avoiding type errors

improving data processing and compatibility

Python provides several built-in functions to perform typecasting.

Types of Typecasting
There are two main categories:

1. Implicit Typecasting
Done automatically by Python

No data loss occurs

Year : 2020 - 2023 5


Happens when Python converts a smaller data type into a larger one
(e.g., int → float)

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

Uses built-in functions

Risk of data loss (e.g., float → int)

Built-in Functions Used in Typecasting


Below are the most commonly used functions with syntax, description, and
programs.

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'>

Year : 2020 - 2023 6


2. float()
Converts a value into a floating-point number.

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)

Year : 2020 - 2023 7


Example Program

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

Year : 2020 - 2023 8


Syntax

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

float() float float("3") → 3.0

str() string str(25) → "25"

list() list list("AB") → ['A','B']

tuple() tuple tuple([1,2]) → (1,2)

set() set set([1,1,2]) → {1,2}

bool() boolean bool(0) → False

complex() complex complex(2,3) → (2+3j)

Year : 2020 - 2023 9


3. What are conditional statements in Python ? Explain each of them with
proper syntax. Write a program to display the result of a student if marks
enter by the user.

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.

If False → statements are skipped.

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

Year : 2020 - 2023 10


else:
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.

Remaining conditions are ignored once a True condition is found.

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

Year : 2020 - 2023 11


else:
statements
else:
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

marks = int(input("Enter your marks: "))

if marks >= 75:


print("Result: Distinction")
elif marks >= 60:
print("Result: First Division")
elif marks >= 45:
print("Result: Second Division")
elif marks >= 33:
print("Result: Pass")
else:
print("Result: Fail")

Explanation of the Program


The user enters marks as input.

int() converts the input to an integer.

The program checks marks using an if–elif–else structure:

75 and above → Distinction

60–74 → First Division

Year : 2020 - 2023 12


45–59 → Second Division

33–44 → Pass

Below 33 → Fail

4. (a) Differentiate between List and Tuple. Explain with an example.


Answer:
In Python, List and Tuple are both sequence data types used to store
multiple items.
However, they differ in several important ways such as mutability,
performance, and use cases.

1. Definition

List
A list is a mutable (changeable) sequence of elements.

It allows inserting, updating, and deleting elements.

Tuple
A tuple is an immutable (unchangeable) sequence of elements.
Once created, its values cannot be modified.

2. Syntax

List Syntax

my_list = [10, 20, 30, 40]

Tuple Syntax

my_tuple = (10, 20, 30, 40)

3. Mutability

List

Year : 2020 - 2023 13


Elements can be changed after creation.

Supports methods like append() , remove() , insert() , etc.

Tuple
Elements cannot be changed, added, or removed.

No methods for modification.

4. Performance

List
Slower because it is mutable and uses more memory.

Tuple
Faster and more memory-efficient.

Often used in programs where data should not change.

5. Use Cases

List
Best for dynamic data

Example: student records, shopping cart items

Tuple
Best for fixed data

Example: coordinates (x, y), months of the year

⭐ Example Illustrating the Difference


List Example (Mutable)

my_list = [1, 2, 3]
my_list[1] = 20 # Modifying second element
print(my_list)

Year : 2020 - 2023 14


Output:

[1, 20, 3]

Tuple Example (Immutable)

my_tuple = (1, 2, 3)
my_tuple[1] = 20 # This will cause an error

Output:

TypeError: 'tuple' object does not support item assignment

⭐ Tabular Difference Between List and Tuple


Feature List Tuple

Mutability Mutable (can change) Immutable (cannot change)

Syntax Uses square brackets [ ] Uses parentheses ( )

Methods Many modification methods Very few methods

Speed Slower Faster

Memory Uses more memory Uses less memory

Use Case Dynamic data Fixed data

Example [10, 20, 30] (10, 20, 30)

(b) Explain break and continue statement with suitable example.


Answer:
Python provides two important loop control statements — break and
continue.
These statements help in controlling the flow of loops ( for and while loops)
depending on certain conditions.

1. break Statement
The break statement is used to terminate the loop immediately, even if the
loop condition is still true.

Year : 2020 - 2023 15


When Python encounters a break , it exits the loop and control moves to the
next statement after the loop.

Key Points
Stops the loop completely.

Used when a condition is met and we no longer want to continue the


loop.

Mostly used in searching, validation, and menu-driven programs.

Syntax

for variable in sequence:


if condition:
break
statements

Example

for num in range(1, 10):


if num == 5:
break
print(num)

Output

1
2
3
4

Explanation
Loop is running from 1 to 9

When num becomes 5, the break statement stops the entire loop

Numbers after 4 are not printed

Year : 2020 - 2023 16


2. continue Statement
The continue statement skips only the current iteration of the loop and
moves to the next iteration.
The loop does not stop; it simply avoids executing the remaining statements
for that iteration.

Key Points
Skips current iteration only

Loop continues from the next iteration

Useful for skipping unwanted values

Syntax

for variable in sequence:


if condition:
continue
statements

Example

for num in range(1, 10):


if num == 5:
continue
print(num)

Output

1
2
3
4
6
7
8
9

Year : 2020 - 2023 17


Explanation
When num becomes 5, the continue statement skips printing

Loop continues normally from 6 to 9

⭐ Difference Between Break and Continue


Feature break continue

Function Stops the loop completely Skips current iteration

Loop execution Ends immediately Continues with next iteration

Use case Searching, terminating early Filtering values

5. What is Slicing in Python ? Write a program to demonstrate the concept of


iterator's slicing.

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:

Extracting specific parts of a sequence

Reversing sequences

Skipping elements

Working with sub-arrays or substrings

Python follows the slicing notation:

General Syntax

sequence[start : stop : step]

Parameters
start → index from where slicing begins

stop → index where slicing ends (stop index is excluded)

step → gap between elements (default = 1)

Year : 2020 - 2023 18


Example of Normal Slicing

numbers = [10, 20, 30, 40, 50]


print(numbers[1:4]) # [20, 30, 40]
print(numbers[::-1]) # reverse slicing

Iterator Slicing in Python


Normally, slicing works on lists, strings, and tuples.
But slicing does NOT work directly on iterators because iterators do not
support indexing.

To slice an iterator, Python provides the islice() method from the itertools

module.

Using islice() for Iterator Slicing

Syntax

from itertools import islice

islice(iterator, start, stop, step)

Points
Works on any iterator (files, generators, loops, etc.)

Returns sliced output without converting the iterator to a list

Memory-efficient

⭐ Program to Demonstrate Iterator Slicing


Example Program

from itertools import islice

# creating an iterator using range()


numbers = iter(range(1, 20))

Year : 2020 - 2023 19


# slicing the iterator from index 2 to 12 with step 2
sliced_numbers = islice(numbers, 2, 12, 2)

# printing the sliced values


for num in sliced_numbers:
print(num)

Expected Output

3
5
7
9
11

Explanation of the Program


iter(range(1, 20)) creates an iterator of numbers from 1 to 19

Since iterators cannot be sliced directly ( numbers[2:12] would throw error),


we use islice()

islice(numbers, 2, 12, 2) extracts elements:

starting from index 2

ending at index 12 (exclusive)

jumping 2 steps each time

Loop prints only the sliced part of the iterator

6. Explain function in Python ? Write a program to generate Fibonacci series


of n numbers.
Answer:
In Python, a function is a block of organized and reusable code that
performs a specific task.

Functions help in reducing repetition, improving modularity, and making


programs easier to maintain.

Year : 2020 - 2023 20


Instead of writing the same code again and again, we write it once inside a
function and call it whenever needed.
Functions in Python are created using the def keyword and may accept
input values (called parameters) and may return a result using the return

statement.

Characteristics of Functions
1. Reusable Code – write once, use many times.

2. Modular Structure – program is divided into smaller, manageable parts.

3. Improves Clarity – code becomes easier to understand.

4. Supports Parameters – functions can accept values.

5. Return Values – functions can produce output.

6. Avoids Redundancy – no need to repeat same logic multiple times.

Syntax of a Python Function

def function_name(parameters):
statements
return value

Explanation of Syntax
def → keyword used to define a function

function_name → name of the function

parameters → optional inputs

statements → code to be executed

return → sends back value (optional)

⭐ Program to Generate Fibonacci Series of n Numbers


The Fibonacci series is a sequence where:

First number = 0

Second number = 1

Year : 2020 - 2023 21


Every next number = sum of previous two numbers

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

# taking input from the user


num = int(input("Enter how many numbers you want: "))

fibonacci(num)

Explanation of the Program


The function fibonacci(n) generates Fibonacci numbers.

Variables a and b store the first two Fibonacci values: 0 and 1.

Inside the loop, the program prints the current number ( a ) and then
updates:

new a = old b

new b = old a+b

This process continues for n iterations.

The user inputs how many Fibonacci numbers they want.

The function prints the complete series.

7. What is Eval function in Python ? Write advantages of using eval function.


Write a program to evaluate a mathematic expression entered by user using
eval function.

Year : 2020 - 2023 22


Answer:
The eval() function in Python is used to evaluate a string as a Python
expression and return the result.
In simple words:

👉 If you write a mathematical expression inside a string, will eval()

calculate it.
👉 If you write a Python expression inside a string, will execute it and
eval()

give the output.

Syntax

eval(expression, globals=None, locals=None)

expression → a string containing a valid Python expression

globals (optional) → dictionary defining global variables

locals (optional) → dictionary defining local variables

Usually, we only use:

eval("expression")

Advantages of Using eval()


1. Evaluates mathematical expressions directly
You can take user input like "10+20*3" and get the answer.

2. Converts string expressions into real code

Example: "5 > 3" → gives True .

3. Useful for dynamic calculations


When expressions are not fixed.

4. Reduces extra code

Instead of writing a full parser for math expressions, eval() handles


everything.

Year : 2020 - 2023 23


⚠️ Important Note
eval() can be dangerous if user enters harmful code (like deleting files).
So use it only when input is trusted.

Program: Evaluate a Mathematical Expression Entered by


User Using eval()

Python Program

expression = input("Enter a mathematical expression: ")

# Using eval to calculate the result


result = eval(expression)

print("Result =", result)

Example Input

Enter a mathematical expression: 10 + 5 * 2

Output

Result = 20

Another example:
Input:

(50 + 30) / 4

Output:

20.0

Short Summary
eval() → evaluates string expressions like Python code.

Year : 2020 - 2023 24


Useful for math calculations and dynamic expressions.

Should be used carefully due to security reasons.

8. What is Package Manager in Python ? Write steps to install any external


package. And write a simple program to use external package.
Answer:

What is a Package Manager in Python?


A Package Manager in Python is a tool that helps you:

Install external libraries

Update installed libraries

Uninstall libraries

Manage package versions

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

Why Do We Need a Package Manager?


Because Python has many useful external libraries like:

numpy → for numerical calculations

pandas → for data analysis

matplotlib → for graphs

requests → for web API calls

These do NOT come with Python by default.


So we use pip to download and install them.

Steps to Install Any External Package Using pip

Step 1: Open Command Prompt / Terminal


Windows:
Press Win + R → type cmd → Enter

Year : 2020 - 2023 25


Linux/Mac:
Open Terminal

Step 2: Check if pip is installed

pip --version

If pip is installed, it will show the version number.

Step 3: Install a Package


Example: Installing requests package

pip install requests

Step 4: Verify Installation

pip show requests

This shows details like version, location, dependencies, etc.

Step 5: Import and Use in Python Program


Once installed, you can use it in any Python program by writing:

import requests

Example Program Using an External Package ( requests )

Program to Fetch Webpage Content Using requests Library

import requests

# Getting webpage content


response = [Link]("[Link]

# Display status code and first 200 characters

Year : 2020 - 2023 26


print("Status Code:", response.status_code)
print("Content:", [Link][:200])

Output (Example)

Status Code: 200


Content: <!doctype html><html>....

This simple program demonstrates that the external package is working


correctly.

Short Summary
Python’s package manager = pip

Used to install, update, and remove external libraries.

External packages extend Python’s power.

Use pip install <package-name> to install.

Import the package inside Python to use it.

9. What are Exceptions ? Explain all statements used in exception handling


with proper syntax and
example. Write a program to handle exception while typecasting in case of
invalid input provided by the user.

Answer:

What are Exceptions in Python?


An exception is an error that occurs during the execution of a program.
When Python cannot understand or execute a statement, it stops the
program and throws an exception.
Example of exception:

Dividing a number by zero → ZeroDivisionError

Converting a non-numeric string into integer → ValueError

Accessing index out of range → IndexError

Year : 2020 - 2023 27


Exceptions help programmers detect and manage errors without stopping
the program.

Statements Used in Exception Handling


Python provides five main keywords for exception handling:

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

If you don't specify exception type:

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

Year : 2020 - 2023 28


4. finally
The finally block always executes, whether an exception occurs or not.
Useful for closing files, releasing resources, etc.

Syntax

finally:
# code that runs always

5. raise
Used to manually raise an exception.

Syntax

raise Exception("Error message")

Full Example Combining try, except, else, finally

try:
a = 10 / 2
print("Result:", a)
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("No error occurred.")
finally:
print("Execution completed.")

Program to Handle Exception While Typecasting (User Gives


Invalid Input)

Problem:
User enters a string like "abc", but we try to convert it into an integer →
causes ValueError .

Year : 2020 - 2023 29


Solution:
Use exception handling to catch the error and display message.

✅ Program: Typecasting with Exception Handling


try:
value = input("Enter a number: ")

# trying to typecast
number = int(value)

print("You entered:", number)

except ValueError:
print("Error: Invalid input! Please enter a numeric value only.")

finally:
print("Program ended.")

Explanation:
If user enters "25" → program converts successfully.

If user enters "abc" → ValueError occurs → handled by except block.

Sample Output 1 (Valid Input)

Enter a number: 56
You entered: 56
Program ended.

Sample Output 2 (Invalid Input)

Enter a number: hello


Error: Invalid input! Please enter a numeric value only.
Program ended.

Year : 2020 - 2023 30


Short Summary (Good for Exams)
Exception: Runtime error that stops program execution.

try: Wrap code that may cause error.

except: Handles the error.

else: Runs only when no error occurs.

finally: Always runs, useful for cleanup.

raise: Manually trigger an exception.

10. Write short notes on the following :


(a) Regex
Answer:
Regex stands for Regular Expressions.
It is a powerful tool used in Python (and many other languages) for pattern
matching, text searching, and text manipulation.
In Python, regex support is provided by the re module (regular expression
module).

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.

Why Regex Is Used?


Regex is used for:

Searching text

Matching patterns in strings

Replacing text

Splitting strings

Data validation (email, phone number, PIN code, etc.)

Year : 2020 - 2023 31


Common Applications of Regex
1. Validating email addresses

2. Checking phone numbers

3. Extracting digits from a string

4. Finding all occurrences of a word in text

5. Replacing unwanted characters

6. Password validation rules

7. Filtering log files / data cleaning

Common Regex Symbols


Symbol Meaning
. Matches any single character
^ Matches beginning of string
$ Matches end of string
* Matches 0 or more repetitions
+ Matches 1 or more repetitions
? Matches 0 or 1 occurrence
\d Matches digits (0–9)
\D Matches non-digit
\w Matches word characters (letters, digits, _)
\W Matches non-word characters
\s Matches white spaces
[] Matches any character inside bracket
{n} Exactly n repetitions

Important Methods in re Module

1. [Link]()
Searches for first match of pattern in string.

2. [Link]()

Year : 2020 - 2023 32


Checks match only at the beginning of string.

3. [Link]()
Returns all matches in a list.

4. [Link]()
Splits string based on pattern.

5. [Link]()
Replaces all occurrences of a pattern.

Example 1: Checking if string contains digits

import re

text = "My number is 987654."

if [Link](r"\d+", text):
print("Digits found!")

Example 2: Extract all email addresses

import re

text = "Contact me at abc@[Link] or xyz@[Link]"

emails = [Link](r"[A-Za-z0-9._%+-]+@[A-Za-z.-]+\.[A-Za-z]{2,}", te
xt)

print(emails)

*Example 3: Replace all digits with * **

import re

text = "My score is 95"

Year : 2020 - 2023 33


new_text = [Link](r"\d", "*", text)

print(new_text)

In Simple Words (Exam Line)


Regular Expressions allow Python to search, match, filter, and modify text
patterns with high flexibility and accuracy, making them essential for string
processing and data validation.

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

They are represented using the symbol @ placed above a function.

Simple Definition
A Decorator is a function that takes another function as input, adds extra
features to it, and returns the modified function.

Why Do We Use Decorators?


Decorators are used to:

Add common functionality to multiple functions

Reduce code repetition

Add logging

Add authentication checks

Measure execution time of functions

Validate arguments

Run pre-processing and post-processing

Year : 2020 - 2023 34


How Decorators Work? (Concept)
1. A decorator is defined as a function.

2. It takes another function as an argument.

3. Performs some additional task.

4. Returns another function.

Syntax of a Decorator

def decorator_name(original_function):
def wrapper():
# extra code
original_function()
# extra code
return wrapper

@decorator_name
def function():
pass

Keyword @decorator_name automatically applies the decorator to the function.

Real-Life Analogy
Think of a decorator as adding toppings on a pizza.

Base pizza = original function

Extra cheese / olives = additional features

Decorator = the topping machine

The base stays the same, but the final output becomes more powerful.

Example: Simple Decorator

def my_decorator(func):
def wrapper():
print("Before the function runs")
func()

Year : 2020 - 2023 35


print("After the function runs")
return wrapper

@my_decorator
def greet():
print("Hello, Python!")

greet()

Output

Before the function runs


Hello, Python!
After the function runs

Explanation
my_decorator adds extra lines before and after the main function.

The original function greet() is not changed, but its output is enhanced.

Example: Decorator with Function Arguments

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)

Year : 2020 - 2023 36


Practical Uses of Decorators
1. Logging
Track when a function is called.

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.

Uses @decorator_name syntax.

Adds pre-processing and post-processing functionality.

Very useful for logging, validation, authentication, and debugging.

(c) Dynamically typed language


Answer:
Python is known as a Dynamically Typed Language.

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.

Year : 2020 - 2023 37


Python figures out the type of the variable based on the value assigned
to it.

Features
1. No Type Declaration Required

You can directly assign a value to a variable without mentioning its type.

2. Type Determined at Runtime


Python decides the type when the program runs.

3. Type Can Change


The same variable can hold values of different types at different times.

4. Flexible and Easy to Use


Makes programming faster and simpler.

Examples

Example 1: Automatic Type Assignment

x = 10 # x is an integer
print(type(x))

x = "Hello" # now x is a string


print(type(x))

Output

<class 'int'>
<class 'str'>

Example 2: Changing Type Dynamically

y = 5.5 # float
y = y + 2 # still float
y = "Python" # now string
print(y)

Year : 2020 - 2023 38


Advantages of Dynamically Typed Languages
1. Ease of Coding
Programmer does not need to write type declarations.

2. Faster Development
Less boilerplate code; flexible coding.

3. Flexible Variable Usage


Same variable can hold different types during program execution.

4. Good for Rapid Prototyping

Quickly test ideas without worrying about data types.

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.

3. Debugging Can Be Harder


If types are not managed carefully, bugs may occur.

Summary for Exam


Python is dynamically typed because variables do not need explicit
type declaration.

Types are decided at runtime.

Variable types can change dynamically.

Offers flexibility and ease of coding, but may cause runtime type
errors.

(d) Garbage collector


Answer:

Year : 2020 - 2023 39


In Python, a Garbage Collector (GC) is a built-in memory management
system that automatically reclaims memory occupied by objects that are
no longer in use.
This helps in efficient memory utilization and prevents memory leaks
during program execution.

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.

Why Garbage Collection is Needed?


When Python programs create objects dynamically, memory is
allocated in the heap.

If objects are no longer needed but still occupy memory, it can lead to
memory waste.

Garbage collection ensures automatic cleanup without programmer


intervention.

How Garbage Collection Works in Python


1. Python uses reference counting to keep track of how many references
point to an object.

If reference count = 0 → object is unreachable → eligible for


garbage collection.

2. Python also handles circular references (objects referencing each


other) using a cyclic garbage collector in the gc module.

Points
1. Automatic Memory Management – no need for manual deletion in most
cases.

2. gc Module – allows manual control over garbage collection.

3. Reference Counting – primary mechanism for memory tracking.

4. Cycles Handling – detects and frees objects that reference each other.

Year : 2020 - 2023 40


Using Garbage Collector ( gc Module)

Syntax

import gc

[Link]() # Manually triggers garbage collection

Example

import gc

class MyClass:
def __del__(self):
print("Object deleted")

# Create object
obj = MyClass()

# Delete object reference


del obj

# Force garbage collection


[Link]()

Output

Object deleted

Advantages of Garbage Collector


1. Automatic Memory Management – reduces programmer effort.

2. Prevents Memory Leaks – frees memory of unused objects.

3. Safe for Large Programs – handles memory efficiently.

4. Handles Cyclic References – cleans objects referencing each other.

Year : 2020 - 2023 41


Disadvantages
1. Extra Overhead – GC consumes CPU to track objects.

2. Unpredictable Execution – cannot predict exact time when GC runs.

3. May Delay Program – in memory-intensive programs, garbage


collection may cause slight delays.

Exam Summary
Garbage Collector automatically frees memory occupied by objects no
longer in use.

Uses reference counting and cyclic GC.

Controlled manually via gc module if needed.

Essential for efficient memory management and avoiding memory


leaks.

Year : 2020 - 2023 42

You might also like