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

Python Programming QP With Answer 2025

The document provides an overview of various Python programming concepts including list operators, dictionaries, functions, inheritance, conditional statements, recursion, loops, and string manipulation. It explains operators like concatenation and repetition for lists, the structure of dictionaries, the difference between built-in and user-defined functions, and types of inheritance. Additionally, it covers control flow with conditional statements, recursion examples, while loops, and the use of break and continue statements in loops.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views92 pages

Python Programming QP With Answer 2025

The document provides an overview of various Python programming concepts including list operators, dictionaries, functions, inheritance, conditional statements, recursion, loops, and string manipulation. It explains operators like concatenation and repetition for lists, the structure of dictionaries, the difference between built-in and user-defined functions, and types of inheritance. Additionally, it covers control flow with conditional statements, recursion examples, while loops, and the use of break and continue statements in loops.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING JUNE - 2025

​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ 4 x 5 = 20
Part A

1.​ Explain any two list operators with example.

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

Concatenation Operator (+)

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]

result = list1 + list2


print(result)

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.

●​ Combining multiple lists


●​ Creating a larger list from smaller lists
●​ Data merging operations
Repetition Operator (*)

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

Where n is the number of times the list will be repeated.

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.

●​ Creating repeated patterns in lists


●​ Generating large datasets quickly
●​ Testing and demonstration purposes

2.​ How do you declare a dictionary in python? Explain.

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

In the above example, student is a dictionary.

●​ "name", "age", and "course" are keys.​

●​ "Rahul", 20, and "MCA" are their corresponding values.​


The key is used to access the related value stored in the dictionary.

Accessing Elements of a Dictionary

Values in a dictionary can be accessed using their keys.

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.

Examples of built-in functions: print(), len(), type(), sum().

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

A user-defined function is a function created by the programmer to perform a specific task.


These functions are defined using the def keyword.

Syntax :

def function_name(parameters):
statements

Example program :

def add(a, b):


result = a + b
return result

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.

Difference between Built-in and User-defined Functions

Built-in Functions User-defined Functions

Already defined in Python. Created by the programmer.

Available directly for use. Must be defined before use.


Example: print(), Example: add(),
len() sum_numbers()

4.​ Briefly explain the types of inheritance in python.

Inheritance is an important concept of object-oriented programming in Python. It allows one


class to acquire the properties and methods of another class. The class that inherits the properties
is called the derived (child) class, and the class whose properties are inherited is called the base
(parent) class. Inheritance helps in code reusability and easy program maintenance.
Types of inheritance

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

class C(A, B):


pass

obj = C()
[Link]()
[Link]()

The C class inherits features from both A and B classes.

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]()

Class C inherits from B, and B inherits from A.

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

class D(B, C):


pass

Here, the inheritance structure combines multiple and hierarchical inheritance, forming hybrid
inheritance.

5.​ Write a note on conditional statement.


A conditional statement in Python is used to perform different actions based on different
conditions. It allows the program to make decisions and execute certain blocks of code only
when a specified condition is true. Conditional statements help control the flow of a program.

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

if marks >= 80:


print("Distinction")
elif marks >= 60:
print("First Class")
else:
print("Pass")

The program checks conditions one by one and executes the corresponding block when the
condition becomes true.

6.​ Define Recursion. Give example.


Recursion is a programming technique in which a function calls itself repeatedly until a
specified condition is satisfied. In recursion, the function solves a problem by breaking it into
smaller sub-problems of the same type. A recursive function must have a base condition to stop
the repeated calls; otherwise, the program will run indefinitely.

Recursion is commonly used to solve problems such as factorial calculation, Fibonacci series,
tree traversal, and mathematical computations.

Syntax of Recursive Function


def function_name(parameters):
if base_condition:
return value
else:
return function_name(arguments)
Example: Factorial Using Recursion
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)

print(factorial(5))

Output:
120

In this program, the function factorial() calls itself.

●​ When n = 5, the function calculates 5 × factorial(4)​

●​ 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

1.​ Explain while loop with example program in python.

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.

Definition of While Loop

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.

Syntax of While Loop

while condition:

statement1

statement2

statement3

Explanation

●​ while → keyword used to start the loop​

●​ condition → expression that is evaluated before each iteration​

●​ statements → block of code that will execute repeatedly​

●​ indentation → used to define the body of the loop​

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.

Flow of Execution (Working of While Loop)


The working of a while loop follows these steps:

●​ The condition is evaluated.


●​ If the condition is True, the loop body executes.
●​ After executing the statements, the condition is checked again.
●​ This process continues repeatedly.
●​ When the condition becomes False, the loop terminates and the program continues with
the next statement after the loop.

Flowchart of While Loop

Start

Initialize variable

Check Condition

/ \

True False

| |

Execute body Exit Loop

Update variable

Go back to condition

Sum of Numbers

sum = 0
i=1

while i <= 5:

sum = sum + i

i=i+1

print("Sum =", sum)

Advantages of While Loop

●​ Used when the number of iterations is not known in advance.


●​ Suitable for condition-based repetition.
●​ Makes programs simpler and more readable.
●​ Useful in many applications such as menu-driven programs and input validation.

2.​ Explain break and continue statements with example program.

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.

●​ break statement → used to terminate the loop immediately.​

●​ 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

for variable in sequence:

statements

if condition:

break

Example program

for i in range(1, 10):

if i == 5:

break

print(i)

Output :

●​ The loop starts printing numbers from 1 to 9.


●​ When i becomes 5, the condition i == 5 becomes true.
●​ The break statement terminates the loop immediately.
●​ Therefore, numbers after 4 are not printed.

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

for variable in sequence:

if condition:

continue

statements

Example Program for Continue Statement

Program

for i in range(1, 6):

if i == 3:
continue

print(i)

Output

Explanation

●​ The loop runs from 1 to 5.


●​ When i becomes 3, the continue statement is executed.
●​ The number 3 is skipped, and the loop continues with the next iteration.
●​ Therefore, 1, 2, 4, 5 are printed.

Break Continue

Terminates the loop immediately Skips current iteration

Control exits the loop Control moves to next iteration

Used to stop loop execution Used to skip certain conditions

Remaining loop iterations are not executed Loop continues normally

3.​ What is indexing and slicing strings? Explain.

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.

Python provides two important concepts for working with strings:

●​ 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.

Example of String Indexing

Consider the string:

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

●​ s[0] returns the first character P


●​ s[3] returns the character h

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.

Slicing allows us to access multiple characters at once.

Syntax of String Slicing

string[start : end]

Where:

●​ start → starting index


●​ end → ending index (not included)

Example Program

s = "Hello Python Programmer"


print(s[0:5])

print(s[6:12])

Output

Hello

Python

Explanation

●​ s[0:5] returns characters from index 0 to 4


●​ s[6:12] returns characters from index 6 to 11

The ending index is not included in the result.

4. Types of Slicing
1. Slicing from Beginning

s = "Python"

print(s[:4])

Output

Pyth

Here the slicing starts from index 0 automatically.

2. Slicing till the End

s = "Python"

print(s[2:])

Output

thon

Here slicing starts from index 2 and continues to the end.

3. Negative Slicing
s = "Python"

print(s[-4:-1])

Output

tho

Negative slicing accesses characters from the end of the string.

Advantages of Indexing and Slicing


●​ Helps to access individual characters easily.
●​ Useful for extracting substrings.
●​ Simplifies text processing operations.
●​ Makes string manipulation easier in Python programs.

4.​ Write a note on types of program error.

Introduction

In programming, an error is a mistake in a program that causes it to produce incorrect results or


prevents the program from running properly. Errors may occur due to incorrect syntax, improper
use of statements, or mistakes in the logic of the program.

Program errors are generally classified into three main types:

●​ Syntax Errors
●​ Semantic Errors
●​ Logical Errors

These errors may occur during compilation or execution of the program.

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.

Examples of Syntax Errors


●​ Missing punctuation
●​ Incorrect spelling of keywords
●​ Missing brackets or quotes

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.

These errors occur due to improper use of variables, operations, or statements.

Examples of Semantic Errors


●​ Using an uninitialized variable
●​ Type mismatch
●​ Invalid operations

Example

a = "Hello"

b=5

c=a-b

Explanation

In this example, subtraction cannot be performed between a string and an integer, so it


produces an error.

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

def sum(a, b):

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.

Errors Based on Time of Detection

Errors can also be classified depending on when they are detected:

1. Compile-time Errors

These errors occur during compilation and include syntax errors and some semantic errors.

2. Runtime Errors

These errors occur while the program is running.

Examples:

●​ Division by zero
●​ File not found
●​ Invalid input​

Example:

a = 10

b=0

c=a/b

This causes a division by zero error during execution.


5.​ Explain user-defined function in python with and without return values

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.

Python provides two types of functions:

●​ Built-in functions (such as print(), len(), input())​

●​ User-defined functions

A user-defined function is a function created by the programmer to perform a particular task in


the program.

Definition

A user-defined function is a function that is written and defined by the user using the def
keyword in Python.

Functions improve code reusability and reduce program complexity.

Syntax of User-Defined Function

def function_name(parameters):

statements

Explanation

●​ def → keyword used to define a function​

●​ function_name → name of the function​

●​ parameters → input values passed to the function​

●​ statements → block of code executed when the function is called

Example:
def greet():

print("Hello Python")

Function Without Return Value


Definition

A function without return value performs a task but does not return any value to the calling
function.

The result is usually displayed using the print() function.

Example Program

def add(a, b):

c=a+b

print("Sum =", c)

add(5, 3)

Output

Sum = 8

Explanation

●​ The function add() receives two values a and b.​

●​ It calculates their sum.​

●​ The result is printed inside the function.​

●​ No value is returned to the calling program.

Function With Return Value


Definition
A function with return value calculates a result and returns the value using the return
statement.

The returned value can be stored in a variable or used in another expression.

Example Program

def add(a, b):

c=a+b

return c

result = add(5, 3)

print("Sum =", result)

Output

Sum = 8

Explanation

●​ The function calculates the sum of two numbers.​

●​ The return statement sends the result back to the calling program.​

●​ The returned value is stored in the variable result.​

Difference Between Functions With and Without Return Values


Function Without Return Function With Return

Does not return any value Returns a value

Uses print() to display output Uses return statement

Result cannot be reused Result can be stored and reused

Used for simple tasks Used for calculations and processing

Advantages of User-Defined Functions


●​ Reduces code repetition​

●​ Improves readability of programs​

●​ Makes debugging easier​

●​ Allows reuse of code in different parts of the program​

●​ Helps divide large programs into smaller modules

PART C

​ ​ ​ ​ ​ ​ ​ ​ ​ ​ 2 x 15 = 30

1.​ Describe data abstraction in python.


Data abstraction is one of the fundamental principles of Object Oriented Programming (OOP).
Python supports object-oriented programming concepts such as classes, objects, inheritance,
polymorphism and abstraction.

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.

Meaning of Data Abstraction

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.

Thus, abstraction helps in separating:


●​ Interface (what the object does)​

●​ Implementation (how the object performs it)​

In Python programming, abstraction is mainly achieved through:

●​ Classes​

●​ Abstract classes​

●​ Abstract methods

Objectives of Data Abstraction

The main objectives of data abstraction are:

●​ Hide unnecessary implementation details​

●​ Reduce programming complexity​

●​ Improve code readability​

●​ Enhance program security​

●​ Allow modification of internal code without affecting users​

●​ Provide clear program structure​

By using abstraction, programmers can design large and complex programs in a simple and
organized way.

Need for Data Abstraction

Data abstraction is very important in software development because it provides the following
advantages:

●​ Simplification of Complex Systems

Large software systems contain many modules and functions. Abstraction simplifies these
systems by hiding unnecessary details.

●​ Improved Code Maintenance


When internal implementation is hidden, programmers can modify the internal code without
affecting the external interface.

●​ Better Security

Sensitive data and implementation logic remain hidden from the user, which improves program
security.

●​ Reusability

Abstract designs allow code to be reused in different applications.

Abstraction in Object Oriented Programming

In object-oriented programming, abstraction is implemented using classes and objects.

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​

●​ Object → Instance of the class

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:

●​ The user only calls start() and stop()​


●​ The internal working of the engine is hidden​

This is an example of data abstraction.

Abstract Classes in Python

Python provides abstraction through abstract classes using the abc module.

The abc module stands for Abstract Base Classes.

An abstract class:

●​ Cannot be instantiated directly​

●​ Contains abstract methods​

●​ Must be implemented in derived classes​

Syntax:

from abc import ABC, abstractmethod

Example:

from abc import ABC, abstractmethod

class Shape(ABC):

@abstractmethod
def area(self):
pass

Here:

●​ Shape is an abstract class​

●​ area() is an abstract method

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:

from abc import ABC, abstractmethod

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:

●​ Shape class defines the abstract method area()​

●​ Rectangle class provides its implementation​

●​ The internal calculation is hidden from the user

Real Life Example of Abstraction

Consider an ATM machine.

A user performs operations such as:


●​ Withdraw money​

●​ Deposit money​

●​ Check balance​

However, the user does not know:

●​ How the banking server processes the request​

●​ How authentication is done​

●​ How transactions are verified​

Thus the ATM system shows only necessary operations while hiding complex internal processes.

This is a real life example of data abstraction.

Advantages of Data Abstraction

Data abstraction provides several benefits in Python programming.

●​ Reduces Complexity

It simplifies program design by hiding unnecessary information.

●​ Improves Security

Sensitive program logic remains hidden.

●​ Enhances Code Reusability

Abstract classes can be reused in multiple programs.

●​ Improves Maintainability

Changes in internal code do not affect the user interface.

●​ Provides Clear Structure

Programs become well organized and easier to understand.


2.​ 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 in Python

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"

match = [Link](pattern, text)

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

Syntax of Regular Expression Patterns

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.

Some common symbols used in regular expression syntax include:

Symbol Meaning

. Matches any single character

^ Matches the start of a string

$ Matches the end of a string

* Matches zero or more occurrences

+ Matches one or more occurrences

? Matches zero or one occurrence

These symbols are known as metacharacters because they have special meanings within a
regular expression.

Quantifiers and Repetition

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.

Common quantifiers include:

●​ * (asterisk)​
●​ + (plus)​

●​ ? (question mark)​

●​ { } (curly braces)​

Quantifiers allow flexible pattern matching and help detect repeated patterns in text.

Asterisk (*) – Match Zero or More Occurrences

The asterisk (*) symbol matches zero or more occurrences of the preceding character.

Example

import re

text = "abccdeeeeffff"

pattern = r"c*"

matches = [Link](pattern, text)

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.

Plus (+) – Match One or More Occurrences

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.

Question Mark (?) – Match Zero or One Occurrence

The question mark (?) specifies that the preceding character is optional and may appear zero or
one time.

Example

import re

text = "color colour"

pattern = r"colou?r"

matches = [Link](pattern, text)

print(matches)

Output

['color', 'colour']

In this pattern, the letter u is optional. Therefore, both color and colour are matched.

Curly Braces {} – Match Specific Number of Occurrences

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}"

matches = [Link](pattern, text)

print(matches)

Output

['12345', '123456', '1234567']

In this example, the pattern \d{5,7} matches numbers containing 5 to 7 digits.

Character Classes

Character classes are used to define a set or range of characters that should be matched in a
pattern.

Common character classes include:

Character Class Meaning

\d Matches any digit

\w Matches alphanumeric characters

\s Matches whitespace characters

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:

●​ \. matches a literal dot​

●​ \* matches an asterisk character​

Escape sequences ensure that special characters are interpreted correctly during pattern
matching.

The findall() Method

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+"

matches = [Link](pattern, text)

print(matches)

Output

['ccc']

The method scans the entire string and returns every occurrence of the matching pattern.

Role of Regular Expressions in Text Processing

Regular expressions are widely used in Python for:


●​ Searching text patterns​

●​ Validating input data​

●​ Extracting useful information from strings​

●​ Processing large text datasets​

●​ Performing automated text manipulation​

They help developers handle complex text-processing tasks efficiently by using concise and
flexible pattern definitions.

3.​ Explain different ways of searching an element in a list.

Searching an element in a list is a common operation in Python programming. A list is an


ordered collection of elements that can store multiple values such as numbers, strings, or other
objects. In many programs, it is necessary to find whether a particular element exists in a list or
to determine its position. Python provides several ways to search for elements in a list using
built-in operators, functions, and loops.

Different techniques can be used to search elements in a list. Some of the commonly used
methods are:

●​ Using the membership operator (in)


●​ Using the list index() method
●​ Using a for loop (Linear Search)
●​ Using enumerate() with loop
●​ Using list comprehension

Searching Using the Membership Operator (in)

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:

print("Element found in the list")

else:

print("Element not found")

Output

Element found in the list

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

Searching Using the index() Method

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

numbers = [5, 10, 15, 20, 25]

position = [Link](15)

print("Element found at index:", position)

Output

Element found at index: 2

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

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

search = 40

found = False

for num in numbers:

if num == search:

found = True

break

if found:

print("Element found in the list")

else:

print("Element not found")

Output

Element found in the list

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.

Searching Using enumerate()

The enumerate() function is used when both the element and its index position are required
during searching.
Example Program

numbers = [12, 24, 36, 48]

for index, value in enumerate(numbers):

if value == 36:

print("Element found at index:", index)

Output

Element found at index: 2

Here, the enumerate function returns both the index and the value of each element while iterating
through the list.

Searching Using List Comprehension

List comprehension can also be used to search elements in a list by filtering values that match the
given condition.

Example Program

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

result = [x for x in numbers if x == 30]

print("Occurrences found:", result)

Output

Occurrences found: [30, 30]

This method creates a new list containing the elements that satisfy the search condition.

4.​ Explain operators available in python .


Operators in Python are special symbols used to perform operations on variables and values.
These operations may include arithmetic calculations, logical comparisons, assignment of values,
and checking relationships between variables. The values on which operators act are called
operands. For example, in the expression a + b, the symbol + is an operator and a and b are
operands.

Python supports several types of operators that help programmers perform different tasks while
writing programs.

The major types of operators available in Python are:

●​ 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.

Operator Meaning Example

+ 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 (Relational) Operators

Comparison operators are used to compare two values. These operators return either True or
False depending on the result of the comparison.

Operator Meaning

> Greater than


< Less than

== Equal to

!= Not equal to

>= Greater than or equal to

<= Less than or equal to

Example Program

x=7

y=3

print("x > y:", x > y)

print("x < y:", x < y)

print("x == y:", x == y)

print("x != y:", x != y)

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 AND

` `

^ Bitwise XOR

~ Bitwise NOT

>> Right shift

<< Left shift

Example Program

x=2

y=7

print("AND:", x & y)

print("OR:", x | y)

print("XOR:", x ^ y)

print("NOT:", ~x)

print("Right Shift:", x >> 1)

print("Left Shift:", x << 2)

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

and True if both conditions are true

or True if at least one condition is true

not Reverses the result

Example Program

x = True

y = False

print("x and y:", x and y)

print("x or y:", x or y)

print("not x:", not x)

Output

x and y: False

x or y: True

not x: False

Logical operators are mainly used in decision-making and control structures.

Assignment Operators

Assignment operators are used to assign values to variables.

The most common assignment operator is =.

Example:
x=5

There are also compound assignment operators.

Operator Example Meaning

= x=5 Assign value

+= 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:

These operators simplify expressions and reduce the length of code.

Membership Operators

Membership operators are used to check whether a value exists in a sequence such as a list,
string, set, or dictionary.

There are two membership operators:


Operator Meaning

in Returns True if value is present

not in Returns True if value is not present

Example Program

x = "Hello Python"

print('H' in x)

print('hello' in x)

Output

True

False

Membership operators help in checking whether elements belong to a collection.

Identity Operators

Identity operators are used to check whether two variables refer to the same memory location.

Operator Meaning

is Returns True if both variables refer to the same object

is not Returns True if variables refer to different objects

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

1.​ Explain super( ) method with example.


The super() method in Python is used to call a method of the parent (base) class from the
child (derived) class. It helps in accessing the parent class methods and properties without
directly referring to the parent class name. The super() method is commonly used in
inheritance to extend or reuse the functionality of the parent class.

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

In the above example:

●​ Parent is the base class and Child is the derived class.​


●​ The display() method in the child class calls the parent class method using
super().display().​

●​ After executing the parent class method, the child class method is executed.​

2.​ With flowchart explain for loop.


A for loop in Python is used to execute a block of statements repeatedly for a fixed number
of times. It is mainly used to iterate over a sequence such as a list, tuple, string, or range of
numbers. The loop continues until all the elements in the sequence are processed.

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:

●​ The program starts.​

●​ The sequence or range of values is initialized.​

●​ The loop checks if the next element is available.​

●​ If the element exists, the statements inside the loop are executed.​

●​ The loop repeats for the next element.​

●​ When no elements remain, the loop ends and the program stops.​

3.​ How do you search an element in a list ? explain.


In Python, searching an element in a list means finding whether a particular element is present
in the list or not. Lists are ordered collections of elements, and searching helps to locate a
specific value within the list. This can be done using the in operator or by using loops to
compare elements one by one.

Method 1: Using in Operator

The in operator checks whether a particular element exists in the list.

Example:

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

if 30 in numbers:
print("Element found in the list")
else:
print("Element not found")
Output:

Element found in the list

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.

Method 2: Using Loop

We can also search an element by checking each element in the list using a for loop.

Example:

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


search = 40

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.

4.​ How do you declare and create a dictionary in python? Explain.

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

Declaring and Creating a Dictionary

A dictionary is declared by assigning key–value pairs inside curly braces.

Syntax:

dictionary_name = {key1:value1, key2:value2, key3:value3}


Example Program
student = {"name":"Ravi", "age":21, "course":"MCA"}

print(student)

Output

{'name': 'Ravi', 'age': 21, 'course': 'MCA'}

Explanation:​
In the above example:

●​ student is the dictionary name.​

●​ "name", "age", and "course" are keys.​

●​ "Ravi", 21, and "MCA" are values.​


Each key is associated with a specific value.​

Accessing Dictionary Elements

Values in a dictionary can be accessed using their keys.

Example:

student = {"name":"Ravi", "age":21, "course":"MCA"}

print(student["name"])

Output

Ravi

5.​ Distinguish between actual and formal arguments.

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:

def add(a, b):

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:

def add(a, b):

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.

Actual Arguments Formal Arguments

Values passed during function call. Parameters defined in function definition.

Provide input to the function. Receive values from actual arguments.


Example: add(5,3) → 5 and 3 Example: def add(a,b) → a and b

6.​ Explain logical errors.

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.

Example of Logical Error

def sum(a, b):

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.

Causes of Logical Errors


Some common causes of logical errors include:

●​ Incorrect formulas or calculations


●​ Wrong conditions in decision statements
●​ Incorrect use of operators
●​ Improper algorithm or program design
PART B

3 x 10 = 30

1.​ Explain method overriding with an example.

Introduction

Python supports Object-Oriented Programming (OOP) concepts such as classes, objects,


inheritance, polymorphism, method overloading and method overriding.​
Method overriding is a feature of inheritance where a child class provides its own
implementation of a method that is already defined in the parent class.

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.

Syntax of Method Overriding

class Parent:

def display(self):

print("This is parent class method")

class Child(Parent):

def display(self):

print("This is child class method")

Here the method display() in the child class overrides the method defined in the parent class.
Example Program

class Animal:

def sound(self):

print("Animals make sound")

class Dog(Animal):

def sound(self):

print("Dog barks")

d = Dog()

[Link]()

Output

Dog barks

Explanation of the Program

●​ A parent class Animal is created with a method sound().​

●​ A child class Dog inherits from the Animal class.​

●​ The Dog class defines the same method sound() again.​

●​ This method overrides the parent class method.​

●​ When the object d calls sound(), the child class method executes instead of the parent
method.​

Advantages of Method Overriding


●​ Allows modification of parent class behavior.​

●​ Helps achieve runtime polymorphism.​

●​ Improves code flexibility.​

●​ Allows child classes to provide their own implementation of methods.​

●​ Supports better code reusability.

2.​ Explain relational operators with example.


Introduction

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.

Types of Relational Operators in Python

Operator Meaning Example

> Greater than a>b

< Less than a<b


== Equal to a == b

!= Not equal to a != b

>= Greater than or equal to a >= b

<= Less than or equal to a <= b

These operators are also called comparison operators.

Example Program

x=7

y=3

print("x > y :", x > y)

print("x < y :", x < y)

print("x == y :", x == y)

print("x != y :", x != y)

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

In the above program:

●​ x > y checks whether 7 is greater than 3, so the result is True.​

●​ x < y checks whether 7 is less than 3, so the result is False.​

●​ x == y checks whether both values are equal.​

●​ x != y checks whether the values are not equal.​

●​ x >= y checks if x is greater than or equal to y.​

●​ x <= y checks if x is less than or equal to y.​

Each comparison returns a Boolean value.

Uses of Relational Operators

Relational operators are mainly used for:

●​ Decision making in if statements​

●​ Controlling loops​

●​ Comparing values in programs​

●​ Logical expressions and conditions​

Example:

a = 10
b=5

if a > b:

print("a is greater than b")

3.​ Write a note on continue and break statements.


Introduction

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​

These statements help control the flow of loop execution.

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

for variable in sequence:

if condition:

break

or

while condition:
if condition:

break

Example Program

for i in range(1, 10):

if i == 5:

break

print(i)

Output

Explanation

●​ The loop starts printing numbers from 1 to 9.


●​ When the value of i becomes 5, the condition i == 5 becomes true.
●​ The break statement stops the loop immediately.
●​ Therefore, the numbers after 4 are not printed.​

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

for i in range(1, 6):

if i == 3:

continue

print(i)

Output

Explanation

●​ The loop runs from 1 to 5.


●​ When i becomes 3, the continue statement is executed.
●​ The number 3 is skipped, and the loop continues with the next iteration.

Difference Between Break and Continue


Break Continue

Terminates the loop completely Skips the current iteration

Control moves outside the loop Control moves to next iteration


Remaining iterations are not executed Loop continues normally

Advantages of Break and Continue

●​ Helps control the flow of loops.​

●​ Allows skipping unwanted iterations.​

●​ Makes programs more efficient and flexible.​

●​ Useful in search operations and conditional loops.

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​

●​ Using the + operator (list concatenation)

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

●​ Initially the list contains 1, 2, 3, 4.


●​ The append(5) method adds 5 at the end of the list.
●​ The new list becomes [1, 2, 3, 4, 5].​

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

●​ The original list contains 1, 2, 3.


●​ The extend() method adds the elements 4, 5, 6 to the end of the list.

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]

list1 = list1 + [4]

print(list1)

Output

[1, 2, 3, 4]

Explanation

The + operator joins two lists and adds the new element at the end.

Method Description

append() Adds a single element at the end of the list

extend() Adds multiple elements at the end of the list

+ operator Combines lists and adds elements at the end


5.​ With an example, explain the different ways of traversing a dictionary.
Introduction

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.

Python provides several ways to traverse a dictionary such as:

●​ Traversing using keys()


●​ Traversing using values()
●​ Traversing using items()
●​ Traversing using for loop

Traversing Using Keys

The keys() method returns all the keys present in the dictionary.

Example Program

student = {"name": "Rahul", "age": 21, "course": "MCA"}

for key in [Link]():

print(key)

Output

name

age

course

Explanation

The loop accesses each key in the dictionary and prints it.

Traversing Using Values


The values() method returns all the values stored in the dictionary.

Example Program

student = {"name": "Rahul", "age": 21, "course": "MCA"}

for value in [Link]():

print(value)

Output

Rahul

21

MCA

Explanation

The loop accesses each value in the dictionary and prints it.

Traversing Using Items

The items() method returns both keys and values as pairs.

Example Program

student = {"name": "Rahul", "age": 21, "course": "MCA"}

for key, value in [Link]():

print(key, ":", value)

Output

name : Rahul
age : 21

course : MCA

Explanation

The loop retrieves both the key and value together and prints them.

Traversing Using For Loop

We can also traverse the dictionary directly using a for loop.

Example Program

student = {"name": "Rahul", "age": 21, "course": "MCA"}

for key in student:

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

keys() Used to traverse dictionary keys

values() Used to traverse dictionary values

items() Used to traverse key-value pairs

for loop Used to access keys and values directly


PART C

2 X 15 = 30

1.​ Explain different types of actual arguments passed to a user-defined


function.

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

def add(a, b):


c=a+b

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

def display(name, age):

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.

Keyword arguments improve the readability and clarity of function calls.

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.

Default arguments help in making functions flexible and easier to use.

4. Variable Length Arguments

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

print("Total =", sum)

total(10, 20)

total(5, 10, 15, 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.

Difference Between Formal and Actual Arguments


Formal Arguments Actual Arguments

Parameters defined in function definition Values passed during function call

Used to receive data Used to send data

Example: def add(a, b) Example: add(5, 10)

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.

String manipulation is an important concept in Python programming used to modify, analyze,


and process strings. A string is a sequence of characters such as letters, numbers, or symbols
enclosed within single quotes (' ') or double quotes (" "). String manipulation involves
performing various operations on strings such as accessing characters, modifying text, searching
for substrings, and extracting information from 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.

1. Concept of String Manipulation

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.

Some common string manipulation operations include:

●​ Accessing characters in a string


●​ Extracting substrings
●​ Concatenating strings
●​ Searching for patterns
●​ Replacing characters
●​ Splitting and joining strings
Through these operations, programmers can efficiently process and analyze text.

2. Accessing Characters Using Indexing

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

text = "Hello Python"

print(text[0])

print(text[6])

Output

Here, the first character H has index 0 and P has index 6.

Indexing helps in examining specific characters in a string when searching for patterns.

3. Extracting Substrings Using Slicing

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

text = "Hello Python"

print(text[0:5])
Output

Hello

In this example, characters from index 0 to 4 are extracted.

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"

result = str1 + " " + str2

print(result)

Output

Hello Python

Concatenation helps in forming new strings while manipulating text data.

5. Searching for Patterns in Text

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.

Using find() Method

The find() method returns the index position of the first occurrence of a substring.

Example:

text = "Python programming is easy"


print([Link]("programming"))

Output:

The method shows the position where the word programming begins.

Using count() Method

The count() method counts the number of times a particular pattern appears in the string.

Example:

text = "apple apple banana apple"

print([Link]("apple"))

Output:

This method helps in identifying repeated patterns in text.

Using Membership Operator

The membership operator in checks whether a specific substring exists in a string.

Example:

text = "Python programming"

print("Python" in text)

Output:

True
This operation confirms the presence of a pattern in the string.

6. Pattern Matching Using Regular Expressions

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

text = "My phone number is 9876543210"

pattern = r"\d+"

result = [Link](pattern, text)

print(result)

Output:

['9876543210']

In this example, the pattern \d+ matches a sequence of digits.

Regular expressions provide powerful techniques to search and analyze patterns within text data.

Applications of String Manipulation in Pattern Searching

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.

3.​ Describe oops concept in detail with an example.

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.

Python supports object-oriented programming features such as classes, objects, inheritance,


polymorphism, abstraction, and encapsulation. These concepts help in structuring large
programs effectively.

The important concepts of OOP are:

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

In Python, a class is created using the keyword class.

Syntax

class ClassName:

# attributes and methods

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

Here, c1 is an object of the class Car.

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:

def __init__(self, name):

[Link] = name

p1 = Person("Ravi")

print([Link])

In this example, the variable name is encapsulated within the class.

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

print("Animal makes sound")

class Dog(Animal):

def bark(self):

print("Dog barks")

d = Dog()

[Link]()

[Link]()

Output

Animal makes sound

Dog barks

Here, the Dog class inherits the method of the Animal class.

Inheritance reduces duplication of code and improves program organization.


5. Polymorphism

Polymorphism means “many forms.” It allows a single function or method to behave differently
depending on the object that calls it.

In Python, polymorphism can be achieved through method overriding or method overloading.

Example Program

class Bird:

def sound(self):

print("Bird makes sound")

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.

Polymorphism increases flexibility in programs.

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:

def add(self, a, b):

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.

Abstraction simplifies complex systems and makes programs easier to use.

Advantages of OOPS

Object Oriented Programming provides several advantages:


●​ Improves code reusability
●​ Enhances modularity
●​ Makes programs easier to maintain
●​ Helps in data security through encapsulation
●​ Supports flexibility and scalability

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 in Python

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"

match = [Link](pattern, text)

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

Syntax of Regular Expression Patterns

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.

Some common symbols used in regular expression syntax include:

Symbol Meaning

. Matches any single character

^ Matches the start of a string

$ Matches the end of a string

* Matches zero or more occurrences

+ Matches one or more occurrences

? Matches zero or one occurrence

These symbols are known as metacharacters because they have special meanings within a
regular expression.

Quantifiers and Repetition


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.

Common quantifiers include:

●​ * (asterisk)​

●​ + (plus)​

●​ ? (question mark)​

●​ { } (curly braces)​

Quantifiers allow flexible pattern matching and help detect repeated patterns in text.

Asterisk (*) – Match Zero or More Occurrences

The asterisk (*) symbol matches zero or more occurrences of the preceding character.

Example

import re

text = "abccdeeeeffff"

pattern = r"c*"

matches = [Link](pattern, text)

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.

Plus (+) – Match One or More Occurrences

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.

Question Mark (?) – Match Zero or One Occurrence

The question mark (?) specifies that the preceding character is optional and may appear zero or
one time.

Example

import re

text = "color colour"

pattern = r"colou?r"

matches = [Link](pattern, text)

print(matches)

Output

['color', 'colour']

In this pattern, the letter u is optional. Therefore, both color and colour are matched.

Curly Braces {} – Match Specific Number of Occurrences

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}"

matches = [Link](pattern, text)

print(matches)

Output

['12345', '123456', '1234567']

In this example, the pattern \d{5,7} matches numbers containing 5 to 7 digits.

Character Classes

Character classes are used to define a set or range of characters that should be matched in a
pattern.

Common character classes include:

Character Class Meaning

\d Matches any digit

\w Matches alphanumeric characters

\s Matches whitespace characters

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:

●​ \. matches a literal dot​

●​ \* matches an asterisk character​

Escape sequences ensure that special characters are interpreted correctly during pattern
matching.

The findall() Method

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+"

matches = [Link](pattern, text)

print(matches)

Output

['ccc']

The method scans the entire string and returns every occurrence of the matching pattern.

Role of Regular Expressions in Text Processing


Regular expressions are widely used in Python for:

●​ Searching text patterns​

●​ Validating input data​

●​ Extracting useful information from strings​

●​ Processing large text datasets​

●​ Performing automated text manipulation​

They help developers handle complex text-processing tasks efficiently by using concise and
flexible pattern definitions.

You might also like