Python Programming QP With Answer 2025
Python Programming QP With Answer 2025
4 x 5 = 20
Part A
A list in Python is an ordered collection of elements that can store different types of values such
as integers, strings, or other objects. Lists are mutable, meaning their elements can be modified
after creation. Python provides several list operators that allow performing operations on lists
such as combining lists or repeating elements
The concatenation operator (+) is used to join two or more lists into a single list. It combines
the elements of the lists and creates a new list as the result.
Syntax :
list1 + list2
Example :
list1 = [1, 2, 3]
list2 = [4, 5, 6]
Output :
[1, 2, 3, 4, 5, 6]
In this example, the + operator combines list1 and list2. The elements of list2 are
appended after the elements of list1, producing a new list containing all the elements. The
original lists remain unchanged.
The repetition operator (*) is used to repeat the elements of a list multiple times. It duplicates
the list elements according to the number specified.
Syntax :
list * n
Example :
list1 = [10, 20, 30]
result = list1 * 3
print(result)
Output :
[10, 20, 30, 10, 20, 30, 10, 20, 30]
In this example, the list [10, 20, 30] is repeated three times using the * operator. The
operator duplicates the list elements and forms a new list containing repeated values.
A dictionary in Python is a built-in data type used to store data in the form of key–value pairs.
Each key in a dictionary is unique and is used to access its corresponding value. Dictionaries are
mutable, which means their elements can be modified after creation. Dictionaries are commonly
used when data needs to be stored and retrieved using a key instead of an index.
In Python, a dictionary is declared using curly braces { }, where each element consists of a
key and value separated by a colon ( : ).
Syntax :
dictionary_name = {key1:value1, key2:value2, key3:value3}
Example program :
student = {"name":"Rahul", "age":20, "course":"MCA"}
print(student)
Output :
{'name': 'Rahul', 'age': 20, 'course': 'MCA'}
Example :
student = {"name":"Rahul", "age":20, "course":"MCA"}
print(student["name"])
Output :
Rahul
3. Distinguish between user-defined and built-in function with example each.
In Python, a function is a block of code that performs a specific task. Functions help in reducing
code repetition and improving program readability. Python provides two types of functions:
Built-in functions and User-defined functions.
1) Built-in Functions
Built-in functions are the functions that are already defined in Python. These functions are
provided by the Python language and can be used directly without writing their definitions.
Example program :
numbers = [10, 20, 30, 40]
print(len(numbers))
Output :
In the above example, len() is a built-in function that returns the number of elements present
in the list.
User-defined Functions
Syntax :
def function_name(parameters):
statements
Example program :
print(add(5, 3))
Output :
8
In this example, the function add() is created by the programmer to add two numbers and
return the result.
1) Single Inheritance
In single inheritance, one child class inherits from only one parent class.
example program
class Parent:
def display(self):
print("This is parent class")
class Child(Parent):
pass
obj = Child()
[Link]()
Here, the Child class inherits the properties and methods of the Parent class.
Multiple Inheritance
In multiple inheritance, a child class inherits from more than one parent class.
class A:
def showA(self):
print("Class A")
class B:
def showB(self):
print("Class B")
obj = C()
[Link]()
[Link]()
Multilevel Inheritance
In multilevel inheritance, a class is derived from another derived class, forming a chain of
inheritance.
Example :
class A:
def showA(self):
print("Class A")
class B(A):
pass
class C(B):
pass
obj = C()
[Link]()
Hierarchical Inheritance
In hierarchical inheritance, multiple child classes inherit from a single parent class.
Example :
class Parent:
def display(self):
print("Parent class")
class Child1(Parent):
pass
class Child2(Parent):
pass
Both Child1 and Child2 inherit properties from the same Parent class.
Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance such as multiple and
hierarchical inheritance.
Example :
class A:
pass
class B(A):
pass
class C(A):
pass
Here, the inheritance structure combines multiple and hierarchical inheritance, forming hybrid
inheritance.
1) if Statement
The if statement is used to execute a block of code only when a given condition is true.
Syntax :
if condition:
statements
Example :
x = 10
if x > 5:
print("x is greater than 5")
In this example, the condition x > 5 is true, so the statement inside the if block is executed.
2) if–else Statement
The if–else statement is used when a program needs to execute one block of code if the
condition is true and another block if the condition is false.
Syntax :
if condition:
statements
else:
statements
Example :
num = 7
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
If the number is divisible by 2, it prints Even number; otherwise, it prints Odd number.
3) if–elif–else Statement
The if–elif–else statement is used when there are multiple conditions to check.
Syntax:
if condition1:
statements
elif condition2:
statements
else:
statements
Example :
marks = 75
The program checks conditions one by one and executes the corresponding block when the
condition becomes true.
Recursion is commonly used to solve problems such as factorial calculation, Fibonacci series,
tree traversal, and mathematical computations.
print(factorial(5))
Output:
120
● Then 4 × factorial(3)
● Then 3 × factorial(2)
● Then 2 × factorial(1)
When n = 1, the base condition is reached and the recursion stops. The final result is 120.
PART B
3 x 10 =30
Introduction
In Python, loops are used to execute a block of statements repeatedly until a specified condition
becomes false. A while loop is a control structure that repeatedly executes a block of code as
long as a given condition is true.
The while loop is also known as a condition-controlled loop because the loop continues
execution based on the evaluation of a condition. If the condition is true, the loop body executes;
if the condition becomes false, the loop stops.
Python programs are written as a sequence of statements, and blocks of statements are defined
using indentation, which makes the structure of the program clear and readable.
A while loop is a looping control statement that repeatedly executes a block of statements while
a specified condition remains true.
In simple terms:
A while loop executes a set of statements repeatedly until the given condition
becomes false.
while condition:
statement1
statement2
statement3
Explanation
If the condition evaluates to True, the statements inside the loop are executed.
When the condition becomes False, the control comes out of the loop.
Start
Initialize variable
Check Condition
/ \
True False
| |
Update variable
Go back to condition
Sum of Numbers
sum = 0
i=1
while i <= 5:
sum = sum + i
i=i+1
In Python programming, loops are used to execute a block of statements repeatedly based on a
condition. Sometimes during loop execution we may need to terminate the loop immediately
or skip certain iterations.
Python provides special control statements called break and continue to control the execution of
loops.
● continue statement → used to skip the current iteration and move to the next iteration of
the loop.
These statements are generally used inside for loops and while loops.
Definition
The break statement is used to terminate the loop immediately when a specified condition is
satisfied. When the break statement is executed, the program control comes out of the loop and
continues with the next statement after the loop.
Syntax
while condition:
statements
if condition:
break
or
statements
if condition:
break
Example program
if i == 5:
break
print(i)
Output :
Continue Statement
Definition
The continue statement is used to skip the current iteration of the loop and continue with
the next iteration.
Unlike break, it does not terminate the loop, but only skips the remaining statements of the
current iteration.
Syntax
while condition:
statements
if condition:
continue
or
if condition:
continue
statements
Program
if i == 3:
continue
print(i)
Output
Explanation
Break Continue
Introduction
In Python, a string is a sequence of characters enclosed in single quotes (' ') or double quotes ("
"). Each character in a string has a position number called an index. By using these index
positions, we can access individual characters or a group of characters in a string.
● Indexing
● Slicing
These techniques help programmers retrieve specific characters or parts of a string easily.
According to Python concepts, characters in a string are stored in sequence and the index always
starts from 0.
2. Indexing in Strings
Definition
Indexing is the process of accessing a single character from a string using its position
number (index).
In Python, each character in the string is assigned a unique index value starting from 0.
s = "Python"
Character P y t h o n
Index 0 1 2 3 4 5
Example program:
s = "Python"
print(s[0])
print(s[3])
Output
Explanation
Negative Indexing
Python also allows negative indexing, which starts from the end of the string.
Example:
Character P y t h o n
Index 0 1 2 3 4 5
Negative Index -6 -5 -4 -3 -2 -1
Example program:
s = "Python"
print(s[-1])
print(s[-3])
Output
Negative indexing helps to access characters from the end of the string.
3. Slicing in Strings
Definition
Slicing is the process of extracting a substring (group of characters) from a string using
index positions.
string[start : end]
Where:
Example Program
print(s[6:12])
Output
Hello
Python
Explanation
4. Types of Slicing
1. Slicing from Beginning
s = "Python"
print(s[:4])
Output
Pyth
s = "Python"
print(s[2:])
Output
thon
3. Negative Slicing
s = "Python"
print(s[-4:-1])
Output
tho
Introduction
● Syntax Errors
● Semantic Errors
● Logical Errors
Syntax Errors
Definition
A syntax error occurs when the rules or grammar of the programming language are not
followed correctly.
In other words, syntax errors occur when the program is written incorrectly according to the
language rules.
These errors are usually detected by the compiler or interpreter before the program runs.
Example Program
print("Hello World"
Explanation
In this example, the closing parenthesis is missing, so Python shows a syntax error.
Semantic Errors
Definition
A semantic error occurs when the program statements are syntactically correct but are used
incorrectly.
Example
a = "Hello"
b=5
c=a-b
Explanation
Logical Errors
Definition
A logical error occurs when the program runs successfully but produces incorrect output
because of mistakes in the program logic.
These errors are difficult to detect because the program executes without showing an error
message.
Example Program
return a - b
Explanation
The function is intended to add two numbers, but it performs subtraction instead.
The program runs without errors but produces the wrong result.
1. Compile-time Errors
These errors occur during compilation and include syntax errors and some semantic errors.
2. Runtime Errors
Examples:
● Division by zero
● File not found
● Invalid input
Example:
a = 10
b=0
c=a/b
Introduction
A function is a block of organized and reusable code used to perform a specific task. Functions
help in dividing a large program into smaller modules, which makes the program easier to
understand, maintain, and debug.
● User-defined functions
Definition
A user-defined function is a function that is written and defined by the user using the def
keyword in Python.
def function_name(parameters):
statements
Explanation
Example:
def greet():
print("Hello Python")
A function without return value performs a task but does not return any value to the calling
function.
Example Program
c=a+b
print("Sum =", c)
add(5, 3)
Output
Sum = 8
Explanation
Example Program
c=a+b
return c
result = add(5, 3)
Output
Sum = 8
Explanation
● The return statement sends the result back to the calling program.
PART C
2 x 15 = 30
Data abstraction means hiding the internal implementation details of a program and showing
only the necessary information to the user. The main aim of abstraction is to reduce
complexity and increase efficiency while designing software systems.
In Python, abstraction is implemented using classes, abstract classes, methods and interfaces.
It helps programmers to focus on what an object does instead of how it does it.
Data abstraction refers to the process of hiding the internal details of a system and exposing
only the essential features to the user.
For example, when a user uses a mobile phone, they simply make calls or send messages without
knowing the internal hardware and software working inside the device. Similarly, in Python
programs, the user interacts only with the required functions and methods while the complex
implementation remains hidden.
● Classes
● Abstract classes
● Abstract methods
By using abstraction, programmers can design large and complex programs in a simple and
organized way.
Data abstraction is very important in software development because it provides the following
advantages:
Large software systems contain many modules and functions. Abstraction simplifies these
systems by hiding unnecessary details.
● Better Security
Sensitive data and implementation logic remain hidden from the user, which improves program
security.
● Reusability
A class defines the properties and behavior of an object. The class exposes only necessary
methods while hiding the internal logic.
Example concept:
● Class → Blueprint
Example:
class Car:
def start(self):
print("Car is starting")
def stop(self):
print("Car is stopping")
Usage:
c = Car()
[Link]()
[Link]()
In this example:
Python provides abstraction through abstract classes using the abc module.
An abstract class:
Syntax:
Example:
class Shape(ABC):
@abstractmethod
def area(self):
pass
Here:
Abstract Method
An abstract method is a method that is declared but does not contain implementation.
Derived classes must provide implementation for abstract methods.
Example:
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self,l,b):
self.l = l
self.b = b
def area(self):
return self.l * self.b
r = Rectangle(5,4)
print("Area:", [Link]())
Output:
Area: 20
Explanation:
● Deposit money
● Check balance
Thus the ATM system shows only necessary operations while hiding complex internal processes.
● Reduces Complexity
● Improves Security
● Improves Maintainability
In Python, regular expressions are supported through the re module, which provides functions
and methods for searching, matching, and manipulating text patterns. A regular expression
pattern is composed of ordinary characters, metacharacters, quantifiers, and special
sequences, which together define the rule used to match a string.
Basic pattern matching refers to the process of searching for a particular sequence of characters
in a given string using regular expressions. Regular expressions combine characters,
metacharacters, and special symbols to create patterns that match specific text.
To work with regular expressions in Python, the re module must first be imported.
Syntax
import re
pattern = "expression"
match = [Link](pattern, text)
Example Program
import re
text = "I have an apple and a banana."
pattern = r"apple"
if match:
print("The word 'apple' is present.")
else:
print("The word 'apple' is not found.")
Output
The word 'apple' is present.
In this example, the regular expression pattern "apple" is used to search for the word apple in the
text. If the pattern is found, the program displays a message indicating that the word is present
The syntax of regular expressions consists of special characters, symbols, and sequences that
represent patterns in text. These elements define how matching should occur within the given
string.
Symbol Meaning
These symbols are known as metacharacters because they have special meanings within a
regular expression.
Quantifiers are special symbols that specify how many times a pattern should occur in the
text. They are used to match repeated characters or sequences.
● * (asterisk)
● + (plus)
● ? (question mark)
● { } (curly braces)
Quantifiers allow flexible pattern matching and help detect repeated patterns in text.
The asterisk (*) symbol matches zero or more occurrences of the preceding character.
Example
import re
text = "abccdeeeeffff"
pattern = r"c*"
print(matches)
Output
['', '', 'ccc', '', '', '', '', '', '', '', '']
In this example, the pattern c* matches zero or more occurrences of the letter 'c'. The findall()
method returns all matches found in the text.
The plus symbol (+) is used to match one or more occurrences of the preceding character.
Example
import re
text = "abccdeeeeffff"
pattern = r"c+"
matches = [Link](pattern, text)
print(matches)
Output
['ccc']
Here, the pattern c+ matches sequences where the letter c appears one or more times
continuously.
The question mark (?) specifies that the preceding character is optional and may appear zero or
one time.
Example
import re
pattern = r"colou?r"
print(matches)
Output
['color', 'colour']
In this pattern, the letter u is optional. Therefore, both color and colour are matched.
Curly braces are used when a pattern must match a specific number of repetitions.
Example
import re
text = "12345 123456 1234567"
pattern = r"\d{5,7}"
print(matches)
Output
Character Classes
Character classes are used to define a set or range of characters that should be matched in a
pattern.
Character classes allow patterns to match multiple possible characters instead of a single fixed
character.
Escape Sequences
Escape sequences are used when a character has special meaning in regular expressions but
needs to be treated as a normal character.
For example:
Escape sequences ensure that special characters are interpreted correctly during pattern
matching.
The findall() function of the re module is commonly used to retrieve all occurrences of a
pattern in a string.
Syntax
[Link](pattern, string)
This function returns a list containing all matches found in the text.
Example
import re
text = "abccdeeeeffff"
pattern = r"c+"
print(matches)
Output
['ccc']
The method scans the entire string and returns every occurrence of the matching pattern.
They help developers handle complex text-processing tasks efficiently by using concise and
flexible pattern definitions.
Different techniques can be used to search elements in a list. Some of the commonly used
methods are:
The simplest way to check whether an element exists in a list is by using the membership
operator in. This operator checks whether a value is present in the list and returns True or
False.
Syntax
element in list_name
Example Program
numbers = [10, 20, 30, 40, 50]
if 30 in numbers:
else:
Output
In this method, Python automatically checks each element of the list until it finds the desired
value. If the element exists, the result will be True; otherwise, it returns False
Python lists provide a built-in method called index() which is used to locate the position of an
element in a list. This method returns the index number of the first occurrence of the element.
Syntax
list_name.index(element)
Example Program
position = [Link](15)
Output
In this example, the element 15 is located at index 2. If the element is not present in the list,
Python generates a ValueError.
Searching Using a For Loop (Linear Search)
Another common way of searching an element in a list is by using a for loop. This method
checks each element of the list sequentially until the required element is found. This technique is
called Linear Search.
Example Program
search = 40
found = False
if num == search:
found = True
break
if found:
else:
Output
In this method, the program compares each element in the list with the search value. When the
match is found, the loop stops using the break statement.
The enumerate() function is used when both the element and its index position are required
during searching.
Example Program
if value == 36:
Output
Here, the enumerate function returns both the index and the value of each element while iterating
through the list.
List comprehension can also be used to search elements in a list by filtering values that match the
given condition.
Example Program
Output
This method creates a new list containing the elements that satisfy the search condition.
Python supports several types of operators that help programmers perform different tasks while
writing programs.
● Arithmetic Operators
● Comparison (Relational) Operators
● Bitwise Operators
● Logical Operators
● Assignment Operators
● Membership Operators
● Identity Operators
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations such as addition, subtraction,
multiplication, and division.
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus (remainder) x % y
// Floor division x // y
** Exponentiation x ** y
Example Program
x=7
y=3
print("Addition:", x + y)
print("Subtraction:", x - y)
print("Multiplication:", x * y)
print("Division:", x / y)
print("Modulus:", x % y)
print("Floor Division:", x // y)
print("Exponent:", x ** y)
Output
Addition: 10
Subtraction: 4
Multiplication: 21
Division: 2.3333
Modulus: 1
Floor Division: 2
Exponent: 343
Arithmetic operators are mainly used for performing mathematical calculations in programs.
Comparison operators are used to compare two values. These operators return either True or
False depending on the result of the comparison.
Operator Meaning
== Equal to
!= Not equal to
Example Program
x=7
y=3
print("x == y:", x == y)
print("x != y:", x != y)
Output
x > y: True
x < y: False
x == y: False
x != y: True
x >= y: True
x <= y: False
These operators are useful in decision-making statements such as if conditions.
Bitwise Operators
Bitwise operators perform operations on binary numbers. They work bit by bit on integer values.
Operator Meaning
` `
^ Bitwise XOR
~ Bitwise NOT
Example Program
x=2
y=7
print("AND:", x & y)
print("OR:", x | y)
print("XOR:", x ^ y)
print("NOT:", ~x)
These operators are commonly used in low-level programming and data manipulation tasks.
Logical Operators
Logical operators are used to combine conditional statements. They return Boolean values (True
or False).
Operator Meaning
Example Program
x = True
y = False
print("x or y:", x or y)
Output
x and y: False
x or y: True
not x: False
Assignment Operators
Example:
x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
**= x **= 5 x = x ** 5
Example
x=4
x += 5
print(x)
Output:
Membership Operators
Membership operators are used to check whether a value exists in a sequence such as a list,
string, set, or dictionary.
Example Program
x = "Hello Python"
print('H' in x)
print('hello' in x)
Output
True
False
Identity Operators
Identity operators are used to check whether two variables refer to the same memory location.
Operator Meaning
Example Program
x = [1,2,3]
y = [1,2,3]
z=x
print(x is y)
print(x is z)
Output
False
True
In this example, x and z refer to the same object, while x and y are different objects even though
their values are the same.
PYTHON PROGRAMMING OCT/NOV 2025
4 X 5 = 20
PART A
Using super() improves code reusability and makes the program easier to maintain.
Syntax
super().method_name()
Example Program
class Parent:
def display(self):
print("This is parent class method")
class Child(Parent):
def display(self):
super().display()
print("This is child class method")
obj = Child()
[Link]()
Output
This is parent class method
This is child class method
Explanation
● After executing the parent class method, the child class method is executed.
Syntax
for variable in sequence:
statements
Example Program
for i in range(1,6):
print(i)
Output
1
2
3
4
5
In this example, the range(1,6) generates numbers from 1 to 5. The loop variable i takes
each value one by one and prints it. The loop stops when the sequence ends.
Flowchart of forloop
Start
|
Initialize sequence
|
Get next element
|
Is element available?
| |
Yes No
| |
Execute End
statements
|
Repeat loop
Explanation of Flowchart:
● If the element exists, the statements inside the loop are executed.
● When no elements remain, the loop ends and the program stops.
Example:
if 30 in numbers:
print("Element found in the list")
else:
print("Element not found")
Output:
Explanation:
The in operator checks if the element 30 is present in the list numbers. Since it exists, the
program prints Element found in the list.
We can also search an element by checking each element in the list using a for loop.
Example:
for i in numbers:
if i == search:
print("Element found")
break
Explanation:
The loop checks each element of the list. When the element 40 is found, the program prints
Element found and stops the loop.
A dictionary in Python is a built-in data type used to store data in the form of key–value pairs.
Each key in the dictionary is unique and is used to access its corresponding value. Dictionaries
are mutable, which means their elements can be modified after creation. Dictionaries are written
using curly braces { } and each key is separated from its value by a colon ( : ).
Syntax:
print(student)
Output
Explanation:
In the above example:
Example:
print(student["name"])
Output
Ravi
In Python functions, arguments are values passed to a function when it is called. These
arguments help the function perform operations using the given values. Arguments are mainly
classified into actual arguments and formal arguments.
Actual Arguments
Actual arguments are the values or variables that are passed to a function when the function is
called. These arguments supply the input values to the function.
Example:
return a + b
print(add(5, 3))
Explanation:
In the function call add(5, 3), the values 5 and 3 are called actual arguments because they
are passed to the function.
Formal Arguments
Formal arguments are the parameters defined in the function definition. They receive the values
from the actual arguments when the function is called.
Example:
return a + b
Explanation:
In the function definition def add(a, b):, a and b are called formal arguments because
they receive the values passed to the function.
A logical error is a type of error in a program where the program runs successfully but produces
an incorrect or unexpected result. These errors occur due to mistakes in the logic or algorithm
used in the program. Unlike syntax errors, logical errors are not detected by the compiler or
interpreter during execution.
Logical errors usually happen when the programmer writes incorrect formulas, conditions, or
steps to solve a problem. Since the program does not stop execution, these errors are often
difficult to detect and require careful debugging.
return a - b
print(sum(5, 3))
Explanation:
In this example, the function is intended to add two numbers, but the programmer mistakenly
used the subtraction operator (-) instead of the addition operator (+). The program runs without
any error, but it produces the wrong result.
3 x 10 = 30
Introduction
This allows the child class to modify or extend the behavior of the parent class method.
Definition
Method overriding is a process in which a method in the child class has the same name as
the method in the parent class but performs a different function.
When the object of the child class calls the method, the child class method is executed instead
of the parent class method.
class Parent:
def display(self):
class Child(Parent):
def display(self):
Here the method display() in the child class overrides the method defined in the parent class.
Example Program
class Animal:
def sound(self):
class Dog(Animal):
def sound(self):
print("Dog barks")
d = Dog()
[Link]()
Output
Dog barks
● When the object d calls sound(), the child class method executes instead of the parent
method.
Operators are special symbols used to perform operations on variables and values. In Python,
relational operators are used to compare two values or expressions.
Relational operators compare the operands and return the result in the form of Boolean values,
either True or False. These operators are commonly used in decision-making statements such
as if, while, and loops.
Definition
Relational operators are used to compare two values and determine the relationship
between them. The result of the comparison is always either True or False.
!= Not equal to a != b
Example Program
x=7
y=3
print("x == y :", x == y)
print("x != y :", x != y)
Output
x > y : True
x < y : False
x == y : False
x != y : True
x >= y : True
x <= y : False
Explanation
● Controlling loops
Example:
a = 10
b=5
if a > b:
In Python, loops such as for loop and while loop are used to execute a block of statements
repeatedly. Sometimes it is necessary to stop the loop or skip certain iterations based on a
condition.
Python provides two special loop control statements for this purpose:
● break statement
● continue statement
Break Statement
Definition
The break statement is used to terminate the loop immediately when a specific condition is
satisfied. When the break statement is executed, the program control moves outside the loop and
continues with the next statement.
Syntax
if condition:
break
or
while condition:
if condition:
break
Example Program
if i == 5:
break
print(i)
Output
Explanation
Continue Statement
Definition
The continue statement is used to skip the current iteration of the loop and move to the next
iteration.
It does not terminate the loop but skips the remaining statements of the current iteration.
Syntax
for variable in sequence:
if condition:
continue
statements
Example Program
if i == 3:
continue
print(i)
Output
Explanation
4. Write the methods used to insert an element to a list at the end .Explain
with an example.
A list in Python is an ordered collection of elements that can store different types of data such as
numbers, strings, or objects. Lists are mutable, which means their elements can be changed,
added, or removed after creation.
Python provides several built-in methods to add elements to a list, especially at the end of the
list. The most commonly used methods are:
● append() method
● extend() method
append() Method
Definition
The append() method is used to add a single element at the end of the list.
Syntax
list_name.append(element)
Example Program
numbers = [1, 2, 3, 4]
[Link](5)
print(numbers)
Output
[1, 2, 3, 4, 5]
Explanation
extend() Method
Definition
The extend() method is used to add multiple elements at the end of a list.
Syntax
list_name.extend(iterable)
Example Program
numbers = [1, 2, 3]
[Link]([4, 5, 6])
print(numbers)
Output
[1, 2, 3, 4, 5, 6]
Explanation
Using + Operator
Definition
The + operator can also be used to add elements to the end of a list by concatenating two lists.
Example Program
list1 = [1, 2, 3]
print(list1)
Output
[1, 2, 3, 4]
Explanation
The + operator joins two lists and adds the new element at the end.
Method Description
A dictionary in Python is a collection of key–value pairs enclosed in curly braces { }. Each key
in a dictionary is associated with a value. Dictionaries are commonly used to store and retrieve
data efficiently.
Traversing a dictionary means accessing or iterating through all the elements (keys and values)
present in the dictionary one by one.
The keys() method returns all the keys present in the dictionary.
Example Program
print(key)
Output
name
age
course
Explanation
The loop accesses each key in the dictionary and prints it.
Example Program
print(value)
Output
Rahul
21
MCA
Explanation
The loop accesses each value in the dictionary and prints it.
Example Program
Output
name : Rahul
age : 21
course : MCA
Explanation
The loop retrieves both the key and value together and prints them.
Example Program
print(key, student[key])
Output
name Rahul
age 21
course MCA
Explanation
The loop iterates through each key, and the value is accessed using the key.
Method Description
2 X 15 = 30
In Python, a function is a block of reusable code that performs a specific task. Functions help in
reducing repetition and improving the modularity of programs. A user-defined function is a
function created by the programmer using the def keyword.
When a function is called, values are passed to it. These values are known as actual arguments.
The parameters defined in the function definition are called formal arguments, while the values
supplied during the function call are called actual arguments.
Python supports several types of actual arguments that can be passed to functions. The major
types are:
● Positional Arguments
● Keyword Arguments
● Default Arguments
● Variable Length Arguments
1. Positional Arguments
Positional arguments are the most common type of arguments used in function calls. In this
method, the values passed to the function are assigned to parameters in the same order in which
they are defined.
The first argument corresponds to the first parameter, the second argument corresponds to the
second parameter, and so on.
Syntax
function_name(value1, value2)
Example Program
print("Sum =", c)
add(5, 10)
Output
Sum = 15
In this example, the value 5 is assigned to parameter a, and 10 is assigned to parameter b because
of their position in the function call.
If the order of arguments is changed, the result will also change. Therefore, positional arguments
depend on the correct order of parameters.
2. Keyword Arguments
Keyword arguments are passed to the function using parameter names along with their values.
In this method, the order of arguments does not matter because each value is assigned to the
corresponding parameter using its name.
Syntax
function_name(parameter1=value1, parameter2=value2)
Example Program
print("Name:", name)
print("Age:", age)
display(age=22, name="Shreyas")
Output
Name: Shreyas
Age: 22
In this example, the arguments are passed using the parameter names name and age, so the order
of arguments does not affect the result.
3. Default Arguments
Default arguments are parameters that have default values assigned in the function definition.
If the user does not provide a value for such parameters during the function call, Python
automatically uses the default value.
Syntax
def function_name(parameter=value):
Example Program
def greet(name="Student"):
print("Hello", name)
greet("Ravi")
greet()
Output
Hello Ravi
Hello Student
In the first function call, the value Ravi is passed as an argument, so it replaces the default value.
In the second call, no value is passed, so the default value Student is used.
Sometimes it is not known how many arguments will be passed to a function. In such cases,
variable length arguments are used. These allow a function to accept any number of arguments.
In Python, variable length arguments are defined using the asterisk (*) symbol.
Syntax
def function_name(*args):
Example Program
def total(*numbers):
sum = 0
for i in numbers:
sum = sum + i
total(10, 20)
Output
Total = 30
Total = 50
In this example, the function total() can accept any number of arguments. All the values passed
to the function are stored as a tuple.
Variable length arguments are useful when the number of inputs is not fixed.
Formal arguments act as placeholders, while actual arguments provide the real values.
2. Explain the concept of string manipulation and how it can be used to
find patterns in text.
Python provides many built-in functions and methods that help programmers work efficiently
with strings. These operations allow programs to process large amounts of text data and detect
patterns within strings.
String manipulation refers to the process of changing, analyzing, or retrieving specific parts
of a string using different operations and functions. Since strings are widely used in applications
such as text processing, data analysis, and web development, manipulating strings becomes an
essential programming task.
In Python, characters in a string can be accessed using index numbers. Indexing starts from 0,
meaning the first character in the string has index position 0.
Example
print(text[0])
print(text[6])
Output
Indexing helps in examining specific characters in a string when searching for patterns.
Python allows extraction of a part of a string using slicing. Slicing retrieves a portion of the
string between two index positions.
Syntax
string[start : end]
Example
print(text[0:5])
Output
Hello
Slicing is very useful when extracting specific patterns from a large text.
4. Concatenation of Strings
Concatenation means combining two or more strings together. In Python, the + operator is
used for concatenation.
Example
str1 = "Hello"
str2 = "Python"
print(result)
Output
Hello Python
String manipulation techniques can be used to search for patterns or specific words in a
string. Python provides methods such as find(), count(), and in operator to locate patterns.
The find() method returns the index position of the first occurrence of a substring.
Example:
Output:
The method shows the position where the word programming begins.
The count() method counts the number of times a particular pattern appears in the string.
Example:
print([Link]("apple"))
Output:
Example:
print("Python" in text)
Output:
True
This operation confirms the presence of a pattern in the string.
String manipulation can also be combined with regular expressions to perform advanced pattern
matching. Regular expressions allow programs to detect complex patterns such as phone
numbers, email addresses, or repeated characters.
For example:
import re
pattern = r"\d+"
print(result)
Output:
['9876543210']
Regular expressions provide powerful techniques to search and analyze patterns within text data.
String manipulation techniques are widely used in many applications such as:
● Text processing
● Data analysis
● Web scraping
● Searching keywords in documents
● Data validation (emails, phone numbers)
● Natural language processing
By manipulating strings and identifying patterns, programs can efficiently analyze textual
information.
Object Oriented Programming (OOP) is a programming paradigm that organizes software design
around objects rather than functions and logic. In OOP, programs are designed using objects
that represent real-world entities. Each object contains data and methods that operate on the
data. This approach helps in building programs that are modular, reusable, and easier to
maintain.
● Class
● Object
● Encapsulation
● Inheritance
● Polymorphism
● Abstraction
1. Class
A class is a blueprint or template used to create objects. It defines the structure and behavior of
objects by specifying variables (attributes) and functions (methods).
Syntax
class ClassName:
Example Program
class Student:
name = "Shreyas"
age = 22
s1 = Student()
print([Link])
print([Link])
Output
Shreyas
22
In this example, Student is a class that contains attributes such as name and age.
2. Object
An object is an instance of a class. It represents a real-world entity and contains data and
methods defined by the class.
Objects are created from classes and can access the attributes and methods of that class.
Example Program
class Car:
def start(self):
print("Car started")
c1 = Car()
[Link]()
Output
Car started
Objects allow the program to interact with the data defined in the class.
3. Encapsulation
Encapsulation is the process of binding data and methods together into a single unit. It
protects the internal data of an object from outside interference.
Encapsulation helps in achieving data hiding and improves security of the program.
Example:
class Person:
[Link] = name
p1 = Person("Ravi")
print([Link])
Encapsulation ensures that data can only be accessed through defined methods.
4. Inheritance
Inheritance is a mechanism where one class inherits the properties and methods of another
class. It allows code reusability and helps in building hierarchical relationships between classes.
The class that inherits properties is called the child class (derived class) and the class whose
properties are inherited is called the parent class (base class).
Syntax
class ParentClass:
# parent properties
class ChildClass(ParentClass):
# child properties
Example Program
class Animal:
def speak(self):
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
[Link]()
[Link]()
Output
Dog barks
Here, the Dog class inherits the method of the Animal class.
Polymorphism means “many forms.” It allows a single function or method to behave differently
depending on the object that calls it.
Example Program
class Bird:
def sound(self):
class Sparrow(Bird):
def sound(self):
print("Sparrow chirps")
class Crow(Bird):
def sound(self):
print("Crow caws")
s = Sparrow()
c = Crow()
[Link]()
[Link]()
Output
Sparrow chirps
Crow caws
In this example, the same method sound() behaves differently for different objects.
6. Abstraction
Abstraction means hiding the implementation details and showing only the essential features
of an object.
It allows programmers to focus on what an object does rather than how it works.
Example:
class Calculator:
return a + b
c = Calculator()
print([Link](5, 3))
Output
The user only needs to know how to use the method add(), without understanding the internal
implementation.
Advantages of OOPS
OOP allows programmers to design large and complex applications efficiently by dividing them
into smaller manageable objects.
4. Describe the syntax and key components of a regular expression pattern
in Python.
Regular expressions are a powerful mechanism used for pattern matching and text processing
in Python. They allow programmers to define complex search patterns using a concise syntax.
These expressions are widely used to search for specific words, validate input, extract
information, and perform advanced text-processing tasks. Regular expressions help in
identifying patterns within strings efficiently and accurately.
In Python, regular expressions are supported through the re module, which provides functions
and methods for searching, matching, and manipulating text patterns. A regular expression
pattern is composed of ordinary characters, metacharacters, quantifiers, and special
sequences, which together define the rule used to match a string.
Basic pattern matching refers to the process of searching for a particular sequence of characters
in a given string using regular expressions. Regular expressions combine characters,
metacharacters, and special symbols to create patterns that match specific text.
To work with regular expressions in Python, the re module must first be imported.
Syntax
import re
pattern = "expression"
match = [Link](pattern, text)
Example Program
import re
text = "I have an apple and a banana."
pattern = r"apple"
if match:
print("The word 'apple' is present.")
else:
print("The word 'apple' is not found.")
Output
The word 'apple' is present.
In this example, the regular expression pattern "apple" is used to search for the word apple in the
text. If the pattern is found, the program displays a message indicating that the word is present
The syntax of regular expressions consists of special characters, symbols, and sequences that
represent patterns in text. These elements define how matching should occur within the given
string.
Symbol Meaning
These symbols are known as metacharacters because they have special meanings within a
regular expression.
● * (asterisk)
● + (plus)
● ? (question mark)
● { } (curly braces)
Quantifiers allow flexible pattern matching and help detect repeated patterns in text.
The asterisk (*) symbol matches zero or more occurrences of the preceding character.
Example
import re
text = "abccdeeeeffff"
pattern = r"c*"
print(matches)
Output
['', '', 'ccc', '', '', '', '', '', '', '', '']
In this example, the pattern c* matches zero or more occurrences of the letter 'c'. The findall()
method returns all matches found in the text.
The plus symbol (+) is used to match one or more occurrences of the preceding character.
Example
import re
text = "abccdeeeeffff"
pattern = r"c+"
print(matches)
Output
['ccc']
Here, the pattern c+ matches sequences where the letter c appears one or more times
continuously.
The question mark (?) specifies that the preceding character is optional and may appear zero or
one time.
Example
import re
pattern = r"colou?r"
print(matches)
Output
['color', 'colour']
In this pattern, the letter u is optional. Therefore, both color and colour are matched.
Curly braces are used when a pattern must match a specific number of repetitions.
Example
import re
pattern = r"\d{5,7}"
print(matches)
Output
Character Classes
Character classes are used to define a set or range of characters that should be matched in a
pattern.
Character classes allow patterns to match multiple possible characters instead of a single fixed
character.
Escape Sequences
Escape sequences are used when a character has special meaning in regular expressions but
needs to be treated as a normal character.
For example:
Escape sequences ensure that special characters are interpreted correctly during pattern
matching.
The findall() function of the re module is commonly used to retrieve all occurrences of a
pattern in a string.
Syntax
[Link](pattern, string)
This function returns a list containing all matches found in the text.
Example
import re
text = "abccdeeeeffff"
pattern = r"c+"
print(matches)
Output
['ccc']
The method scans the entire string and returns every occurrence of the matching pattern.
They help developers handle complex text-processing tasks efficiently by using concise and
flexible pattern definitions.