PROGRAMMING IN PYTHON
UNIT- I INTRODUCTION TO PYTHON PROGRAMMING AND CONTROL STRUCTURES
PART A ( 2 Marks)
1. What is Python programming?
Python is a high-level, interpreted programming language known for its simple syntax and ease of
use.
It is widely used in web development, data science, artificial intelligence, automation, and more.
2. Benefits of Tuple over List:
Immutability: Tuples are immutable, making them faster and safer for data that should not be
changed.
Memory Efficiency: Tuples consume less memory than lists, improving performance.
Hashable: Tuples can be used as dictionary keys, whereas lists cannot.
3. Define an Identifier:
An identifier is the name given to variables, functions, classes, and objects in Python.
It must start with a letter (A-Z or a-z) or an underscore (_) followed by letters, digits (0-9), or
underscores.
4. Difference Between While and For Loop:
For Loop: Used when the number of iterations is known. It iterates over a sequence (list, tuple,
range, etc.).
While Loop: Used when the number of iterations is unknown and runs until a condition becomes
False.
5. Difference Between break, continue, and pass:
break: Exits the loop completely.
continue: Skips the current iteration and moves to the next one.
pass: Does nothing; acts as a placeholder in code.
6. Purpose of Indentation in Python:
Python uses indentation to define code blocks instead of braces {} like in other languages.
It improves readability and is mandatory for proper execution.
7. Factorial of a Number Using For Loop:
num = int(input("Enter a number: "))
fact = 1
for i in range(1, num + 1):
fact *= i
print("Factorial:", fact)
8. Two Distinct Python Modes:
Interactive Mode: Allows executing code line by line in the Python shell.
o Benefit: Useful for testing small code snippets.
o Drawback: Not suitable for writing large programs.
Script Mode: Runs Python programs saved in files (.py).
o Benefit: Suitable for writing large applications.
o Drawback: Does not allow immediate feedback like interactive mode.
9. Python Program to Exchange Two Variable Values:
a=5
b = 10
a, b = b, a
print("After swapping: a =", a, ", b =", b)
10. Concept of Type Casting in Python:
Type casting converts one data type into another.
Syntax & Examples:
Implicit Casting (done automatically):
x=5
y = 2.5
z = x + y # Python automatically converts int to float
print(z) # Output: 7.5
Explicit Casting (manually using functions):
x = "10"
y = int(x) # Converts string to integer
print(y + 5) # Output: 15
Descriptive Questions ( 16 Marks)
1. What are the types of operators? Explain types of operator in detail with an example.
Types of Operators in Python
Operators in Python are special symbols used to perform operations on variables and values. Python
has several types of operators:
1. Arithmetic Operators
Arithmetic operators perform mathematical operations.
Operator Description Example
+ Addition 5+3=8
- Subtraction 10 - 4 = 6
* Multiplication 6 * 2 = 12
/ Division 9 / 2 = 4.5
// Floor Division 9 // 2 = 4
% Modulus (Remainder) 10 % 3 = 1
** Exponentiation 2 ** 3 = 8
Example:
a = 10
b=3
print(a + b) # Output: 13
print(a % b) # Output: 1
2. Assignment Operators
Assignment operators assign values to variables.
Operator Example Equivalent to
= x=5 Assigns 5 to x
+= x += 3 x=x+3
-= x -= 2 x=x-2
*= x *= 4 x=x*4
/= x /= 2 x=x/2
%= x %= 3 x=x%3
Example:
x = 10
x += 5 # Same as x = x + 5
print(x) # Output: 15
3. Comparison Operators
Comparison operators compare two values and return True or False.
Operator Description Example
== Equal to 5 == 5 → True
!= Not equal to 5 != 3 → True
> Greater than 10 > 5 → True
< Less than 3 < 8 → True
>= Greater than or equal to 6 >= 6 → True
<= Less than or equal to 4 <= 7 → True
Example:
a = 10
b = 20
print(a > b) # Output: False
4. Logical Operators
Logical operators combine multiple conditions.
Operator Description Example
and Returns True if both conditions (5 > 3) and (8 > 6) → True
are true
or Returns True if at least one (5 > 3) or (8 < 6) → True
condition is true
not Reverses the result not(5 > 3) → False
Example:
x=5
y = 10
print(x > 3 and y > 8) # Output: True
5. Bitwise Operators
Bitwise operators work at the binary level.
Operator Description Example (Binary)
& AND 5 & 3 → 1 (101 & 011 = 001)
` ` OR
^ XOR 5 ^ 3 → 6 (101 ^ 011 = 110)
~ NOT ~5 → -6
<< Left Shift 5 << 1 → 10 (101 → 1010)
>> Right Shift 5 >> 1 → 2 (101 → 010)
Example:
a = 5 # Binary: 101
b = 3 # Binary: 011
print(a & b) # Output: 1
6. Identity Operators
Identity operators check if two variables refer to the same memory location.
Operator Description Example
is Returns True if both variables are x is y
the same object
is not Returns True if they are different x is not y
objects
Example:
a = [1, 2, 3]
b=a
print(a is b) # Output: True
7. Membership Operators
Membership operators check whether a value exists in a sequence (like a list or string).
Operator Description Example
in Returns True if the value is "a" in "apple" → True
present
not in Returns True if the value is not "x" not in "apple" → True
present
Example:
numbers = [1, 2, 3, 4]
print(3 in numbers) # Output: True
print(5 not in numbers) # Output: True
2. i)Write a program to find sum of digits of an integer. ii) Write a Python program that asks the user
to guess an integer within a given range and provides hints.
i) Program to Find the Sum of Digits of an Integer
# Function to calculate the sum of digits of an integer
def sum_of_digits(number):
# Convert negative numbers to positive
number = abs(number)
# Initialize sum variable
total = 0
# Loop through each digit
while number > 0:
digit = number % 10 # Extract the last digit
total += digit # Add the digit to the total sum
number //= 10 # Remove the last digit from the number
return total
# Input from user
num = int(input("Enter an integer: "))
# Calling the function and displaying the result
result = sum_of_digits(num)
print(f"The sum of the digits of {num} is: {result}")
Explanation of the Code:
1. Function Definition:
o The function sum_of_digits(number) is defined to take an integer as input.
o If the input number is negative, abs(number) is used to convert it to a positive number.
2. Processing the Digits:
o The total variable is initialized to 0 to store the sum.
o A while loop runs as long as number > 0, extracting and adding each digit to total:
number % 10 extracts the last digit.
The extracted digit is added to total.
number //= 10 removes the last digit from number by performing integer division.
3. User Input & Output:
o The user is prompted to enter an integer.
o The function is called with this input, and the sum of its digits is displayed.
Example Runs:
Case 1: Positive Number
Enter an integer: 1234
The sum of the digits of 1234 is: 10
(1 + 2 + 3 + 4 = 10)
Case 2: Negative Number
Enter an integer: -567
The sum of the digits of -567 is: 18
(5 + 6 + 7 = 18)
ii) Guess the Number Game with Hints
This program generates a random number within a given range and asks the user to guess it. It provides hints
if the guess is too high or too low.
import random
# Generate a random number between 1 and 100
secret_number = [Link](1, 100)
print("Guess a number between 1 and 100!")
while True:
guess = int(input("Enter your guess: "))
if guess < secret_number:
print("Too low! Try again.")
elif guess > secret_number:
print("Too high! Try again.")
else:
print("Congratulations! You guessed it right.")
break
Example Output:
Guess a number between 1 and 100!
Enter your guess: 50
Too high! Try again.
Enter your guess: 25
Too low! Try again.
Enter your guess: 37
Congratulations! You guessed it right.
3. Explain the various looping constructs by giving example.
Looping Constructs in Python
Loops in Python are used to execute a block of code multiple times. Python provides three types of loops:
1. For Loop
The for loop is used when the number of iterations is known. It iterates over a sequence (list, tuple,
string, range, etc.).
Syntax:
for variable in sequence:
# Code block
Example: (Using range())
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Example: (Iterating Over a List)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
2. While Loop
The while loop is used when the number of iterations is not known and the loop runs until a specific
condition becomes False.
Syntax:
while condition:
# Code block
Example: (Print numbers from 1 to 5)
i=1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Example: (Using While Loop to Find Sum of Digits)
num = 123
sum_digits = 0
while num > 0:
sum_digits += num % 10
num //= 10
print("Sum of digits:", sum_digits)
Output:
Sum of digits: 6
3. Nested Loops
A loop inside another loop is called a nested loop. It is useful for working with matrices or patterns.
Example: (Printing a Pattern)
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Output:
11
12
13
21
22
23
31
32
33
4. Loop Control Statements
Python provides special statements to control loops:
Break Statement
The break statement exits the loop completely when a condition is met.
for i in range(1, 6):
if i == 4:
break
print(i)
Output:
1
2
3
Continue Statement
The continue statement skips the current iteration and moves to the next one.
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
Pass Statement
The pass statement does nothing; it is used as a placeholder.
for i in range(1, 4):
if i == 2:
pass
print(i)
Output:
1
2
3
4. i)Write a python program to find minimum in a list. ii)Write a python program for circulate the
values of n variables.
i) Python Program to Find the Minimum Value in a List
# Function to find the minimum value in a list
def find_minimum(numbers):
if not numbers: # Check if the list is empty
return "⚠️ List is empty! Please enter valid numbers."
minimum = numbers[0] # Assume the first element is the smallest
# Iterate through the list to find the smallest element
for num in numbers:
if num < minimum:
minimum = num
return minimum
# Taking user input
try:
# Ask user to enter numbers separated by spaces
user_input = input("Enter numbers separated by spaces: ")
# Convert input string to a list of integers
num_list = [int(x) for x in user_input.split()]
# Call function and display result
result = find_minimum(num_list)
print(f"The minimum value in the list is: {result}")
except ValueError:
print("⚠️ Invalid input! Please enter only numbers.")
Explanation of the Code:
1. Function find_minimum(numbers):
o Checks if the list is empty. If empty, returns an error message.
o Assumes the first element is the smallest.
o Iterates through the list and updates minimum if a smaller number is found.
o Returns the smallest number.
2. User Input Handling:
o The user enters numbers separated by spaces.
o split() is used to break the input into a list of strings.
o List comprehension [int(x) for x in user_input.split()] converts the strings into integers.
3. Error Handling:
o If the user enters non-numeric values, a ValueError is caught, and an error message is
displayed.
Example Runs:
Run 1 (Normal Case)
Enter numbers separated by spaces: 5 2 8 1 9 3
The minimum value in the list is: 1
Run 2 (Single Element)
Enter numbers separated by spaces: 7
The minimum value in the list is: 7
Run 3 (Negative Numbers)
Enter numbers separated by spaces: -3 -7 -1 -10 5
The minimum value in the list is: -10
Run 4 (Empty Input)
Enter numbers separated by spaces:
⚠️ Invalid input! Please enter only numbers.
ii) Python Program to Circulate the Values of N Variables
Circulating means shifting values such that the last value moves to the first position, and all others move
forward.
# Function to circulate values in a list
def circulate_values(lst):
if not lst:
return "⚠️ The list is empty! Please enter valid numbers."
# Circulating the values (shifting right)
last_element = [Link]() # Remove the last element
[Link](0, last_element) # Insert it at the beginning
return lst # Return the modified list
# Taking user input
try:
user_input = input("Enter values separated by spaces: ")
# Convert input string to a list of integers
values = [int(x) for x in user_input.split()]
print(f"Original List: {values}")
# Call the function and display result
result = circulate_values(values)
print(f"Circulated List: {result}")
except ValueError:
print("⚠️ Invalid input! Please enter only numbers.")
Explanation of the Code:
1. Function circulate_values(lst):
o First, it checks if the list is empty. If so, it returns a warning message.
o The last element is removed using .pop().
o It is then inserted at the beginning of the list using .insert(0, last_element).
o The modified list is returned.
2. User Input Handling:
o The user is asked to enter numbers separated by spaces.
o The input is converted into a list of integers.
3. Error Handling:
o If the user enters non-numeric input, a ValueError is caught, and an error message is
displayed.
Example Runs:
Run 1 (Normal Case)
Enter values separated by spaces: 1 2 3 4 5
Original List: [1, 2, 3, 4, 5]
Circulated List: [5, 1, 2, 3, 4]
Run 2 (Negative Numbers)
Enter values separated by spaces: -10 -20 -30 -40
Original List: [-10, -20, -30, -40]
Circulated List: [-40, -10, -20, -30]
Run 3 (Single Element)
Enter values separated by spaces: 100
Original List: [100]
Circulated List: [100]
Run 4 (Empty Input)
Enter values separated by spaces:
⚠️ Invalid input! Please enter only numbers.
5. Describe the data types in python? With an example.
Data types in Python define the kind of values a variable can store. Python provides several built-in
data types, categorized as follows:
1. Numeric Data Types
Used to store numerical values.
i) Integer (int)
Stores whole numbers, positive or negative.
Example:
x = 10
print(type(x)) # Output: <class 'int'>
ii) Float (float)
Stores decimal (floating-point) numbers.
Example:
y = 10.5
print(type(y)) # Output: <class 'float'>
iii) Complex (complex)
Stores complex numbers in the form a + bj.
Example:
z = 3 + 4j
print(type(z)) # Output: <class 'complex'>
2. Sequence Data Types
Used to store ordered collections of items.
i) String (str)
Stores a sequence of characters.
Example:
name = "Python"
print(type(name)) # Output: <class 'str'>
ii) List (list)
Stores an ordered collection of items (mutable).
Example:
fruits = ["apple", "banana", "cherry"]
print(type(fruits)) # Output: <class 'list'>
iii) Tuple (tuple)
Stores an ordered collection of items (immutable).
Example:
colors = ("red", "green", "blue")
print(type(colors)) # Output: <class 'tuple'>
iv) Range (range)
Generates a sequence of numbers.
Example:
nums = range(1, 6)
print(list(nums)) # Output: [1, 2, 3, 4, 5]
3. Set Data Types
Used to store unordered collections of unique items.
i) Set (set)
Stores unique elements in an unordered way.
Example:
my_set = {1, 2, 3, 4, 4}
print(my_set) # Output: {1, 2, 3, 4}
ii) Frozen Set (frozenset)
Immutable version of a set.
Example:
fset = frozenset({1, 2, 3})
print(type(fset)) # Output: <class 'frozenset'>
4. Mapping Data Type
Dictionary (dict)
Stores key-value pairs.
Example:
student = {"name": "Alice", "age": 20, "grade": "A"}
print(type(student)) # Output: <class 'dict'>
5. Boolean Data Type (bool)
Stores True or False values.
Example:
is_python_easy = True
print(type(is_python_easy)) # Output: <class 'bool'>
6. Binary Data Types
Used for handling binary data.
i) Bytes (bytes)
Immutable sequence of bytes.
Example:
b = b"Hello"
print(type(b)) # Output: <class 'bytes'>
ii) Byte Array (bytearray)
Mutable sequence of bytes.
Example:
ba = bytearray([65, 66, 67])
print(type(ba)) # Output: <class 'bytearray'>
iii) Memory View (memoryview)
Allows direct memory access.
Example:
mv = memoryview(bytes(5))
print(type(mv)) # Output: <class 'memoryview'>
7. None Type (NoneType)
Represents the absence of a value.
Example:
x = None
print(type(x)) # Output: <class 'NoneType'>
6. Write about operator precedence in python? with an example.
Operator precedence determines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated before those with lower precedence.
Order of Precedence (Highest to Lowest)
Precedence Operators Description
1 (Highest) () Parentheses (Used for grouping)
2 ** Exponentiation
3 +x, -x, ~x Unary plus, Unary minus, Bitwise
NOT
4 *, /, //, % Multiplication, Division, Floor
Division, Modulus
5 +, - Addition, Subtraction
6 <<, >> Bitwise Shift Operators
7 & Bitwise AND
8 ^ Bitwise XOR
9 ` `
10 ==, !=, >, <, >=, <= Comparison Operators
11 not Logical NOT
12 and Logical AND
13 (Lowest) or Logical OR
Example:
result = 10 + 3 * 2 ** 2 - (5 / 5)
print(result)
Step-by-step Evaluation:
1. 2 ** 2 → Exponentiation first → 4
2. 3 * 4 → Multiplication → 12
3. 5 / 5 → Division → 1.0
4. 10 + 12 - 1.0 → Addition and Subtraction (Left to Right) → 21.0
Output:
21.0
Using Parentheses to Change Precedence
Parentheses () can be used to change the default order of operations.
Example:
result = (10 + 3) * 2 ** (2 - 1)
print(result)
Evaluation:
1. (10 + 3) → 13
2. (2 - 1) → 1
3. 2 ** 1 → 2
4. 13 * 2 → 26
Output:
26
7. Analyze the role of the range() function in python loops. Provide examples of different ways to use
range().
Role of range() Function in Python Loops
The range() function is commonly used in loops, especially in for loops, to generate a sequence of
numbers. It helps control the number of iterations efficiently.
Syntax of range()
range(start, stop, step)
start → (Optional) The beginning value (default is 0).
stop → The end value (not included in the sequence).
step → (Optional) The difference between consecutive values (default is 1).
Different Ways to Use range()
1. Using range(stop): Starts from 0 (Default)
for i in range(5):
print(i)
Output:
0
1
2
3
4
2. Using range(start, stop): Custom Start and Stop
for i in range(2, 7):
print(i)
Output:
2
3
4
5
6
3. Using range(start, stop, step): Custom Step Value
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
4. Using range() with Negative Step (Reverse Order)
for i in range(10, 3, -2):
print(i)
Output:
10
8
6
4
5. Using range() in a while Loop (Converting to List)
nums = list(range(3, 10, 2))
print(nums)
Output:
[3, 5, 7, 9]
# 1. Simple use of range(): Print numbers from 0 to 4
print("Example 1: Printing numbers from 0 to 4")
for i in range(5): # Default start is 0, step is 1
print(i)
print("-" * 30)
# 2. Using range(start, stop): Print numbers from 2 to 6
print("Example 2: Printing numbers from 2 to 6")
for i in range(2, 7):
print(i)
print("-" * 30)
# 3. Using range(start, stop, step): Print even numbers from 2 to 10
print("Example 3: Printing even numbers from 2 to 10")
for i in range(2, 11, 2):
print(i)
print("-" * 30)
# 4. Using range() in reverse order: Print numbers from 10 to 1
print("Example 4: Printing numbers from 10 to 1")
for i in range(10, 0, -1):
print(i)
print("-" * 30)
# 5. Using range() to generate a list of numbers
print("Example 5: Creating a list using range()")
numbers = list(range(1, 6))
print(numbers)
print("-" * 30)
# 6. Using range() with step to print multiples of 3 from 3 to 18
print("Example 6: Printing multiples of 3 from 3 to 18")
for i in range(3, 19, 3):
print(i)
print("-" * 30)
# 7. Using range() with len() to loop through a list
print("Example 7: Looping through a list using range() and len()")
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")
print("-" * 30)
Example Output
Example 1: Printing numbers from 0 to 4
0
1
2
3
4
------------------------------
Example 2: Printing numbers from 2 to 6
2
3
4
5
6
------------------------------
Example 3: Printing even numbers from 2 to 10
2
4
6
8
10
------------------------------
Example 4: Printing numbers from 10 to 1
10
9
8
7
6
5
4
3
2
1
------------------------------
Example 5: Creating a list using range()
[1, 2, 3, 4, 5]
------------------------------
Example 6: Printing multiples of 3 from 3 to 18
3
6
9
12
15
18
------------------------------
Example 7: Looping through a list using range() and len()
Index 0: apple
Index 1: banana
Index 2: cherry
------------------------------
8. Explain break, continue, and pass statements with examples.
Break, Continue, and Pass Statements in Python
Python provides three control statements that alter the flow of loops:
Statement Purpose
break Exits the loop immediately
continue Skips the current iteration and moves to the next one
pass Does nothing, used as a placeholder
1. break Statement
The break statement stops the loop when a certain condition is met.
Example: Stop the loop when i == 3
for i in range(1, 6):
if i == 3:
break
print(i)
Output:
1
2
2. continue Statement
The continue statement skips the current iteration and moves to the next one.
Example: Skip i == 3
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
3. pass Statement
The pass statement does nothing. It is used as a placeholder when a loop or function is required
syntactically but not implemented yet.
Example: Placeholder in a Loop
for i in range(1, 6):
if i == 3:
pass # Placeholder for future code
print(i)
Output:
1
2
3
4
5
Complete Code Demonstrating break, continue, and pass
print("Example 1: Using break to exit loop")
for i in range(1, 11):
if i == 6:
print("Breaking at", i)
break
print(i)
print("-" * 30)
print("Example 2: Using continue to skip even numbers")
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
print("-" * 30)
print("Example 3: Using pass as a placeholder")
for i in range(1, 6):
if i == 3:
pass
else:
print(i)
print("-" * 30)
Example Output
Example 1: Using break to exit loop
1
2
3
4
5
Breaking at 6
------------------------------
Example 2: Using continue to skip even numbers
1
3
5
7
9
------------------------------
Example 3: Using pass as a placeholder
1
2
4
5
------------------------------
Key Differences
Statement Effect
break Exits the loop immediately
continue Skips the current iteration and moves to the next
pass Does nothing, used as a placeholder
9. Discuss the different tokens in Python with examples.
Tokens in Python
Tokens are the smallest building blocks of a Python program. They are the basic components that
the Python interpreter recognizes while executing a script.
1. Keywords
Python has reserved words that cannot be used as variable names.
Example: Using Keywords
if True:
print("Python has 35+ keywords!")
Common Python Keywords
if, else, for, while, def, return, import, class, try, except, with, etc.
2. Identifiers
Identifiers are user-defined names for variables, functions, and classes.
Rules for Identifiers:
Must start with a letter (A-Z, a-z) or _
Can contain numbers (0-9) after the first letter
Cannot be a keyword
Cannot contain spaces or special characters (@, $, %)
Example: Valid and Invalid Identifiers
# Valid identifiers
student_name = "Alice"
_age = 20
PI = 3.14
# Invalid identifiers
2name = "Bob"
class = "Math"
3. Literals
Literals are fixed values assigned to variables.
Types of Literals
Type Example
String "Hello", 'Python'
Integer 10, -25
Float 3.14, -0.75
Boolean True, False
None Type None
Example: Using Literals
name = "Python"
age = 25
pi = 3.14
is_active = True
value = None
4. Operators
Operators perform arithmetic, logical, or bitwise operations.
Types of Operators
Operator Type Example
Arithmetic +, -, *, /
Comparison ==, !=, >, <
Logical and, or, not
Bitwise `&,
Example: Using Operators
x = 10 + 5
y = x > 10
z = (x > 5) and (y < 20)
5. Punctuators (Special Symbols)
Punctuators are symbols used in Python syntax.
Common Punctuators
Symbol Usage
() Function calls, tuples
{} Dictionaries, sets
[] Lists, indexing
: Loop & function definitions
, Separates values
Example: Using Punctuators
def greet():
print("Hello, Python!")
greet()
10. i)Write a python program for armstrong number ii)Write a python program for find the distance
between two points.
i) Python Program for Armstrong Number
An Armstrong number (also called a narcissistic number) is a number where the sum of its digits
raised to the power of the number of digits is equal to the original number.
Example:
Python Program:
# Function to check if a number is an Armstrong number
def is_armstrong(num):
# Convert number to string to get the number of digits
num_str = str(num)
num_digits = len(num_str) # Count number of digits
# Calculate the sum of digits raised to the power of the number of digits
armstrong_sum = sum(int(digit) ** num_digits for digit in num_str)
# Check if the sum equals the original number
return armstrong_sum == num
# Taking user input
try:
num = int(input("Enter a number to check if it's an Armstrong number: "))
# Call the function and display the result
if is_armstrong(num):
print(f"{num} is an Armstrong number!")
else:
print(f"{num} is NOT an Armstrong number.")
except ValueError:
print("Invalid input! Please enter a valid integer.")
How the Program Works
1. User inputs a number.
2. Function is_armstrong(num) checks if the number is an Armstrong number:
o Converts the number to a string to find the number of digits.
o Iterates through each digit, raises it to the power of the total digits, and sums it.
o Compares the sum with the original number.
3. Displays the result (Armstrong number or Not an Armstrong number).
4. Handles invalid input (non-numeric values) using try-except.
Example Runs
Run 1 (Armstrong Number)
Enter a number to check if it's an Armstrong number: 9474
9474 is an Armstrong number!
Run 2 (Not an Armstrong Number)
Enter a number to check if it's an Armstrong number: 123
123 is NOT an Armstrong number.
Run 3 (Single-digit Armstrong Number)
Enter a number to check if it's an Armstrong number: 5
5 is an Armstrong number!
Run 4 (Invalid Input)
Enter a number to check if it's an Armstrong number: abc
Invalid input! Please enter a valid integer.
.
ii) Python Program to Find Distance Between Two Points
The distance between two points (x1, y1) and (x2, y2) in a 2D plane is given by:
Python Program:
import math # Import math module for square root function
# Function to calculate the distance between two points
def calculate_distance(x1, y1, x2, y2):
distance = [Link]((x2 - x1) ** 2 + (y2 - y1) ** 2)
return distance
# Taking user input for two points
try:
print("Enter coordinates of the first point (x1, y1):")
x1 = float(input("x1: "))
y1 = float(input("y1: "))
print("Enter coordinates of the second point (x2, y2):")
x2 = float(input("x2: "))
y2 = float(input("y2: "))
# Calculate the distance
distance = calculate_distance(x1, y1, x2, y2)
# Display the result
print(f"\n The distance between ({x1}, {y1}) and ({x2}, {y2}) is: {distance:.2f}")
except ValueError:
print("Invalid input! Please enter numerical values.")
Example Runs
Run 1 (Normal Case)
Enter coordinates of the first point (x1, y1):
x1: 3
y1: 4
Enter coordinates of the second point (x2, y2):
x2: 7
y2: 1
The distance between (3.0, 4.0) and (7.0, 1.0) is: 5.00
Correctly calculates the distance between (3,4) and (7,1).
Run 2 (Negative Coordinates)
Enter coordinates of the first point (x1, y1):
x1: -2
y1: -3
Enter coordinates of the second point (x2, y2):
x2: 4
y2: 1
The distance between (-2.0, -3.0) and (4.0, 1.0) is: 7.21
Works for negative numbers as well.
Run 3 (Same Points)
Enter coordinates of the first point (x1, y1):
x1: 5
y1: 5
Enter coordinates of the second point (x2, y2):
x2: 5
y2: 5
The distance between (5.0, 5.0) and (5.0, 5.0) is: 0.00
Distance is 0 because the points are the same.
Run 4 (Invalid Input)
Enter coordinates of the first point (x1, y1):
x1: abc
Invalid input! Please enter numerical values.
Part – C (15 marks)
1. Elaborate the conditional statements with necessary example.
Conditional Statements in Python
What are Conditional Statements?
Conditional statements allow a program to make decisions based on specific conditions. They execute
different blocks of code depending on whether a condition evaluates to True or False.
Python supports three main conditional statements:
1. if statement
2. if-else statement
3. if-elif-else statement
1. if Statement
The if statement executes a block of code only if the condition is True.
Syntax:
if condition:
# Code to execute if condition is True
Example: Checking if a number is positive
num = 10
if num > 0:
print("The number is positive.")
Output: The number is positive.
2. if-else Statement
The if-else statement executes one block if the condition is True and another block if the condition is False.
Syntax:
if condition:
# Code if condition is True
else:
# Code if condition is False
Example: Checking even or odd
num = 7
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Output: Odd number
3. if-elif-else Statement
The if-elif-else statement checks multiple conditions in sequence.
Syntax:
if condition1:
# Code if condition1 is True
elif condition2:
# Code if condition2 is True
else:
# Code if all conditions are False
Example: Checking grade based on marks
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F")
Output: Grade: B
4. Nested if Statements
An if statement inside another if statement is called nested if.
Example: Checking if a number is positive and even
num = 12
if num > 0:
if num % 2 == 0:
print("Positive and Even")
else:
print("Positive but Odd")
Output: Positive and Even
5. Short-Hand if (Ternary Operator)
Python allows writing if-else in one line.
Example: Finding the maximum of two numbers
a, b = 10, 20
max_value = a if a > b else b
print("Maximum:", max_value)
Output: Maximum: 20
2. Demonstrate the concept of recursion and write a Python program to solve the Towers of Hanoi
problem.
Recursion is a programming technique where a function calls itself to solve a problem in smaller
parts until it reaches a base case.
Key Components of Recursion:
1. Base Case → The condition where recursion stops.
2. Recursive Case → The function calls itself with a modified parameter.
Example: Factorial using Recursion
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
return n * factorial(n - 1) # Recursive case
print(factorial(5)) # Output: 120
Towers of Hanoi Problem
A tower of Hanoi is a mathematical puzzle with three rods and n number of discs.
The mission is to move all the disks to some another tower without violating the
sequence of arrangement.
A few rules to be followed for Tower of Hanoi are −
❖ Only one disk can be moved among the towers at any given time.
❖ Only the "top" disk can be removed.
❖ No large disk can sit over a small disk.
No of efficient moves = 2 n – 1
Steps for algorithm:
Step 1 − Move n-1 disks from source to aux
Step 2 − Moventh disk from source to dest
Step 3 − Move n-1 disks from aux to dest
Python Program for Towers of Hanoi
def hanoi(n, source, auxiliary, target):
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
hanoi(n - 1, source, target, auxiliary) # Move n-1 disks to auxiliary
print(f"Move disk {n} from {source} to {target}") # Move nth disk to target
hanoi(n - 1, auxiliary, source, target) # Move n-1 disks to target
# Example: Solve for 3 disks
num_disks = 3
hanoi(num_disks, 'A', 'B', 'C')
Explanation for 3 Disks:
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
Recursive Approach:
Moves n-1 disks to an auxiliary peg.
Moves the largest disk to the target peg.
Moves n-1 disks from the auxiliary peg to the target peg.
Time Complexity
T(n) = 2T(n-1) + 1
Time Complexity: O(2ⁿ - 1) (Exponential)
UNIT- II FUNCTIONS AND STRINGS
PART A ( 2 Marks)
1. Define Function and Give Its Advantages.
A function in Python is a block of reusable code that performs a specific task. Functions help in code
modularity and reusability.
Advantages:
Reduces code duplication
Improves readability and organization
Allows easier debugging
Supports modular programming
2. What Do You Mean by Variable Length Arguments?
A variable-length argument allows a function to accept an arbitrary number of arguments using *args
(non-keyword) and **kwargs (keyword arguments).
Example:
def add_numbers(*args):
return sum(args)
print(add_numbers(2, 4, 6, 8)) # Output: 20
*args allows multiple inputs without defining the exact number.
3. Define User-Defined and Built-in Functions with Examples.
User-Defined Function: A function created by the programmer.
Example:
def greet(name):
return "Hello, " + name
print(greet("Alice"))
Built-in Function: A predefined function in Python.
Example:
print(len("Python")) # Output: 6
4. What is the Purpose of Lambda Function?
A lambda function is an anonymous function that is defined in a single line. It is used for short, simple
functions.
Example:
square = lambda x: x * x
print(square(5)) # Output: 25
Useful in short calculations, sorting, and filtering data.
5. List Out Operations in String.
Some common string operations are:
Concatenation: "Hello" + " World" → "Hello World"
Repetition: "Hi" * 3 → "HiHiHi"
Slicing: "Python"[0:3] → "Pyt"
Length: len("Python") → 6
Case Conversion: "hello".upper() → "HELLO"
Find & Replace: "Python".replace("P", "J") → "Jython"
6. Differentiate Between Iteration and Recursion.
Feature Iteration Recursion
Definition Looping using for or while A function calling itself
Memory Use Less memory Uses stack memory
Speed Faster Slower due to function calls
Example for i in range(5): print(i) def fact(n): return 1 if n==0 else n*fact(n-1)
7. Differentiate Between Local and Global Variables.
Feature Local Variable Global Variable
Scope Inside a function Accessible throughout the program
Defined using Inside a function Outside all functions
Feature Local Variable Global Variable
Example def f(): x = 5 x = 10; def f(): print(x)
Example:
x = 10
def my_function():
x=5
print("Local:", x)
my_function()
print("Global:", x)
Output:
Local: 5
Global: 10
8. Is String Immutable? Justify.
Yes, strings are immutable in Python.
Once a string is created, it cannot be changed in memory.
Example:
s = "Hello"
s[0] = "J" # Error: Strings cannot be modified
To modify a string, we create a new one:
s = "Hello"
s = "J" + s[1:] # "Jello"
9. Write a Python Program to Reverse a String.
def reverse_string(s):
return s[::-1]
print(reverse_string("Python")) # Output: "nohtyP"
Uses string slicing [::-1] to reverse the string.
10. Write About Fruitful, Anonymous, and Void Functions.
Fruitful Function: Returns a value.
def add(a, b):
return a + b
print(add(3, 4)) # Output: 7
Anonymous Function (Lambda): Defined using lambda.
square = lambda x: x*x
print(square(4)) # Output: 16
Void Function: Does not return a value.
def greet():
print("Hello!")
greet() # Output: Hello!
Descriptive Questions ( 13 Marks)
1. Write a python program to find whether the given string is symmetrical of palindrome.
A palindrome is a string that reads the same forward and backward (e.g., "madam").
A symmetrical string has two equal halves that are mirror images (e.g., "abbaabba").
# Function to check if a string is palindrome
def is_palindrome(s):
return s == s[::-1] # Reverse and compare
# Function to check if a string is symmetrical
def is_symmetrical(s):
length = len(s)
mid = length // 2 # Find the middle index
if length % 2 == 0:
first_half = s[:mid]
second_half = s[mid:]
else:
first_half = s[:mid]
second_half = s[mid+1:] # Skip the middle character for odd-length strings
return first_half == second_half # Check if both halves are equal
# Taking user input
string = input("Enter a string to check: ")
# Checking both conditions
palindrome_result = is_palindrome(string)
symmetrical_result = is_symmetrical(string)
# Display results
if palindrome_result and symmetrical_result:
print(f" '{string}' is BOTH a Palindrome and Symmetrical!")
elif palindrome_result:
print(f" '{string}' is a Palindrome but NOT Symmetrical.")
elif symmetrical_result:
print(f" '{string}' is Symmetrical but NOT a Palindrome.")
else:
print(f" '{string}' is NEITHER a Palindrome NOR Symmetrical.")
How the Program Works
1. is_palindrome(s):
o Reverses the string using s[::-1].
o Compares with the original string.
o Returns True if both are equal.
2. is_symmetrical(s):
o Splits the string into two halves.
o If the length is even, the halves are equal-sized.
o If the length is odd, it ignores the middle character.
o Compares both halves and returns True if they match.
3. Takes user input and checks both conditions.
4. Displays the result based on the findings.
Output:
Run 1 (Palindrome & Symmetrical)
Enter a string to check: abba
'abba' is BOTH a Palindrome and Symmetrical!
Run 2 (Only Palindrome)
Enter a string to check: abcba
'abcba' is a Palindrome but NOT Symmetrical.
Run 3 (Only Symmetrical)
Enter a string to check: aaaabaaa
'aaaabaaa' is Symmetrical but NOT a Palindrome.
Run 4 (Neither)
Enter a string to check: abcdef
'abcdef' is NEITHER a Palindrome NOR Symmetrical.
2. Write a python program to convert the given string from lowercase characters to uppercase and
uppercase to lowercase.
Python provides .swapcase() for this.
Approach 1: Using swapcase() (Built-in Method)
Python provides a built-in function swapcase(), which automatically converts lowercase letters to uppercase
and vice versa.
Python Program:
# Function to swap case of characters
def swap_case(s):
swapped_string = "" # Initialize an empty string to store result
for char in s:
if [Link](): # If lowercase, convert to uppercase
swapped_string += [Link]()
elif [Link](): # If uppercase, convert to lowercase
swapped_string += [Link]()
else:
swapped_string += char # Keep non-alphabet characters unchanged
return swapped_string
# Taking user input
input_string = input("Enter a string to swap case: ")
# Convert the string
result = swap_case(input_string)
# Display the result
print(f"\n Swapped case string: {result}")
Output:
Run 1 (Mixed Case)
Enter a string to swap case: Hello World
Swapped case string: hELLO wORLD
Run 2 (Random Case)
Enter a string to swap case: PyThOn
Swapped case string: pYtHoN
Run 3 (Numbers and Symbols)
Enter a string to swap case: 123 @Test!
Swapped case string: 123 @tEST!
How the Program Works
1. The swap_case(s) function:
o Iterates through each character of the string.
o If the character is lowercase, it converts it to uppercase.
o If the character is uppercase, it converts it to lowercase.
o If it's a non-alphabet character (digits, symbols, spaces), it remains unchanged.
o Constructs a new modified string.
2. The program takes user input and calls the function.
3. It prints the modified string.
Approach 2: Using for Loop and isupper() / islower()
We can manually check each character and change its case.
Python Program:
def convert_case_manual(s):
converted = ''
for char in s:
if [Link]():
converted += [Link]()
elif [Link]():
converted += [Link]()
else:
converted += char # Keep numbers & special characters unchanged
return converted
# Example Usage
input_string = "PyThOn 123 ProGrAm"
converted_string = convert_case_manual(input_string)
print("Original String:", input_string)
print("Converted String:", converted_string)
Output:
Original String: PyThOn 123 ProGrAm
Converted String: pYtHoN 123 pROgRaM
3. Write about scope of variables with example program.
The scope of a variable defines where in the program a variable can be accessed or modified. Python has
four types of variable scopes:
Local Scope – Declared inside a function
Global Scope – Declared outside functions
Enclosed Scope – Nested functions
Built-in Scope – Predefined Python variables/functions
1. Local Scope (Function Scope)
Variables declared inside a function belong to the local scope.
These variables cannot be accessed outside the function.
Example:
def local_scope_example():
x = 10 # Local variable
print("Inside function:", x)
local_scope_example()
# print(x) # This will cause an error because 'x' is local to the function.
Output:
Inside function: 10
2. Global Scope
Variables declared outside any function have a global scope.
They can be accessed inside and outside functions.
Example:
x = 100 # Global variable
def global_scope_example():
print("Inside function:", x) # Accessing global variable
global_scope_example()
print("Outside function:", x) # Global variable accessible anywhere
Output:
Inside function: 100
Outside function: 100
Modifying Global Variables Inside a Function
To modify a global variable inside a function, use the global keyword.
y = 50 # Global variable
def modify_global():
global y # Declaring 'y' as global
y = y + 10 # Modifying global variable
print("Inside function:", y)
modify_global()
print("Outside function:", y) # Modified globally
Output:
Inside function: 60
Outside function: 60
3. Enclosed (Nonlocal) Scope
When a function is nested inside another function, variables from the outer function are enclosed.
Use the nonlocal keyword to modify them.
Example:
def outer_function():
a = 20 # Enclosed variable
def inner_function():
nonlocal a # Accessing the variable from outer function
a=a+5
print("Inside inner function:", a)
inner_function()
print("Inside outer function:", a)
outer_function()
Output:
Inside inner function: 25
Inside outer function: 25
4. Built-in Scope
These are predefined variables and functions in Python.
Examples: print(), len(), sum(), etc.
Example:
print("Hello, World!") # print() is a built-in function
print(len("Python")) # len() is also built-in
Output:
Hello, World!
6
Complete Program Demonstrating All Scopes
x = "Global" # Global variable
def outer():
x = "Enclosed" # Enclosed variable
def inner():
nonlocal x # Using 'nonlocal' to modify enclosed variable
x = "Modified Enclosed"
print("Inside inner:", x)
inner()
print("Inside outer:", x) # Prints modified enclosed variable
def global_example():
global x # Using 'global' to modify global variable
x = "Modified Global"
outer()
print("Outside function:", x) # Prints global variable
global_example()
print("After modifying global variable:", x) # Shows the modified global variable
Output:
pgsql
CopyEdit
Inside inner: Modified Enclosed
Inside outer: Modified Enclosed
Outside function: Global
After modifying global variable: Modified Global
4. Explain in detail about recursion with an example.
Introduction
Recursion is a programming technique where a function calls itself repeatedly until a base condition is
met. It is commonly used to solve problems that can be broken down into smaller subproblems of the same
type.
Key Features of Recursion
A function calls itself.
There must be a base case to stop recursion.
Each recursive call solves a smaller subproblem.
Types of Recursion
1. Direct Recursion – A function calls itself directly.
2. Indirect Recursion – A function calls another function, which eventually calls the original function.
Basic Example: Printing Numbers Using Recursion
def print_numbers(n):
if n == 0: # Base condition
return
print(n)
print_numbers(n - 1) # Recursive call with a smaller problem
print_numbers(5)
Output:
5
4
3
2
1
Explanation:
The function keeps calling itself with n-1 until n == 0, stopping recursion.
Working of Recursion (Call Stack)
Each recursive call is stored in the function call stack. When a base condition is met, the stack starts
unwinding.
Example (Tracing Recursive Calls)
For print_numbers(3), the execution will be:
1. print_numbers(3) → Calls print_numbers(2)
2. print_numbers(2) → Calls print_numbers(1)
3. print_numbers(1) → Calls print_numbers(0) (Base case, stops recursion)
4. Returns back to print_numbers(1), print_numbers(2), print_numbers(3) (unwinding phase)
Example 1: Factorial Using Recursion
Factorial of n is defined as:
n!=n×(n−1)!n! = n \times (n-1)!n!=n×(n−1)!
Python Program:
def factorial(n):
if n == 0 or n == 1: # Base case
return 1
return n * factorial(n - 1) # Recursive call
print("Factorial of 5 is:", factorial(5))
Output:
Factorial of 5 is: 120
Explanation:
factorial(5) calls factorial(4), factorial(4) calls factorial(3), and so on.
When factorial(1) returns 1, the stack unwinds, computing 5 * 4 * 3 * 2 * 1 = 120.
Example 2: Fibonacci Series Using Recursion
Fibonacci series:
F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)F(n)=F(n−1)+F(n−2)
With base cases:
F(0)=0,F(1)=1F(0) = 0, \quad F(1) = 1F(0)=0,F(1)=1
Python Program:
def fibonacci(n):
if n == 0: # Base case 1
return 0
elif n == 1: # Base case 2
return 1
return fibonacci(n - 1) + fibonacci(n - 2) # Recursive call
# Printing first 6 Fibonacci numbers
for i in range(6):
print(fibonacci(i), end=" ")
Output:
011235
Explanation:
Each Fibonacci number is computed using previous two numbers recursively.
Example 3: Sum of Digits Using Recursion
Python Program:
def sum_of_digits(n):
if n == 0: # Base case
return 0
return (n % 10) + sum_of_digits(n // 10) # Recursive call
print("Sum of digits of 1234:", sum_of_digits(1234))
Output:
Sum of digits of 1234: 10
Explanation:
sum_of_digits(1234) → (4) + sum_of_digits(123)
This continues until sum_of_digits(0), where recursion stops.
Advantages of Recursion
Solves Complex Problems Easily – Problems like tree traversal, Fibonacci series, and backtracking are
easily implemented.
Reduces Code Length – Compared to iterative approaches, recursion provides cleaner and more readable
code.
Uses Function Call Stack – Automatically handles subproblems, reducing the need for explicit loops.
Disadvantages of Recursion
Consumes More Memory – Each function call is stored in the call stack, which may lead to stack
overflow for very large values.
Can Be Slower – Recursive solutions are sometimes less efficient than iterative solutions.
Difficult to Debug – Tracing recursive calls can be more challenging than loops.
Difference Between Recursion and Iteration
Feature Recursion Iteration
Definition Function calls itself Loop repeats instructions
Use Case Suitable for tree traversal, backtracking Best for simple loops
Memory Usage Uses call stack Uses a single loop variable
Performance Can be slow Usually faster
Complete Recursive Program with Multiple Functions
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
def sum_of_digits(n):
if n == 0:
return 0
return (n % 10) + sum_of_digits(n // 10)
# Calling functions
print("Factorial of 5:", factorial(5))
print("Fibonacci series:", [fibonacci(i) for i in range(6)])
print("Sum of digits of 456:", sum_of_digits(456))
Output:
Factorial of 5: 120
Fibonacci series: [0, 1, 1, 2, 3, 5]
Sum of digits of 456: 15
5. Describe in detail about function parameters with its types by giving example.
A function parameter is a variable that is used inside a function to receive values from the caller. In Python,
functions allow different types of parameters, making them flexible and reusable.
Types of Function Parameters in Python
Python supports four types of function parameters:
Positional Parameters
Default Parameters
Keyword Arguments
Variable-Length Arguments (*args and **kwargs)
Positional Parameters
Arguments must be passed in the correct order.
The number of arguments must match the function definition.
Example:
def add(a, b):
return a + b
print(add(5, 10)) # Output: 15
print(add(10, 5)) # Output: 15 (Order matters!)
The function expects two arguments, and their order is important.
Default Parameters
If an argument is not passed, the default value is used.
If an argument is passed, it overrides the default value.
Example:
def greet(name="Guest"):
print(f"Hello, {name}!")
greet() # Output: Hello, Guest!
greet("Alice") # Output: Hello, Alice!
Default values make functions more flexible by handling missing arguments.
Keyword Arguments
Arguments are passed using parameter names.
The order of arguments does not matter.
Example:
def student_info(name, age, course):
print(f"Name: {name}, Age: {age}, Course: {course}")
student_info(age=20, name="Emma", course="Python")
Output:
Name: Emma, Age: 20, Course: Python
Keyword arguments allow named inputs, making functions easier to understand.
Variable-Length Arguments
Python allows functions to accept a variable number of arguments using:
*args (Non-keyword arguments)
**kwargs (Keyword arguments)
Using *args (Multiple Positional Arguments)
Used when the number of arguments is unknown.
Arguments are stored as a tuple.
Example:
def add_numbers(*args):
return sum(args)
print(add_numbers(5, 10, 15)) # Output: 30
print(add_numbers(3, 6, 9, 12, 15)) # Output: 45
*args allows multiple values as function input.
Using **kwargs (Multiple Keyword Arguments)
Used when the number of keyword arguments is unknown.
Arguments are stored as a dictionary.
Example:
def student_details(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
student_details(name="Sophia", age=22, course="Data Science")
Output:
name: Sophia
age: 22
course: Data Science
**kwargs allows dynamic keyword arguments.
Combining All Parameter Types
Python allows mixing all parameter types in a function.
Example:
def employee_details(name, age=30, *skills, **info):
print(f"Name: {name}, Age: {age}")
print("Skills:", skills)
print("Additional Info:", info)
employee_details("Alice", 25, "Python", "Java", department="IT", salary=50000)
Output:
Name: Alice, Age: 25
Skills: ('Python', 'Java')
Additional Info: {'department': 'IT', 'salary': 50000}
Key Point:
name, age → Positional and default parameters
*skills → Multiple positional arguments
**info → Multiple keyword arguments
Comparison Table: Different Parameter Types
Parameter Type Definition Example
Positional Order matters func(5, 10)
Default Uses a default value if no argument is provided func(a, b=10)
Keyword Arguments passed with names (order doesn’t matter) func(b=10, a=5)
*args Accepts multiple positional arguments func(1, 2, 3, 4)
**kwargs Accepts multiple keyword arguments func(name="John", age=25)
Example Program: Function with Different Parameters
def calculator(a, b, operation="add"):
if operation == "add":
return a + b
elif operation == "subtract":
return a - b
elif operation == "multiply":
return a * b
elif operation == "divide":
return a / b
else:
return "Invalid operation"
print(calculator(10, 5)) # Uses default operation (addition)
print(calculator(10, 5, operation="multiply")) # Uses keyword argument
Output:
15
50
Key Point: The function supports multiple operations using parameters.
Advantages of Function Parameters
Code Reusability – Functions make the code modular.
Flexibility – Parameters allow dynamic values in functions.
Reduced Complexity – No need to define new functions for each input.
Readability – Code becomes more structured and readable.
6. i) Write about lambda [Link] a python program to find fibonacci series using lambda
function. ii) Write a python program to find power of a number .
A lambda function is an anonymous function.
(i) Lambda Function and Fibonacci Series using Lambda
What is a Lambda Function?
A lambda function is an anonymous function (a function without a name).
It can have multiple parameters but only one expression.
The syntax is:
python
CopyEdit
lambda arguments: expression
It is mainly used for short, simple functions where a full function definition is unnecessary.
Example of Lambda Function:
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
Python Program: Fibonacci Series using Lambda
from functools import reduce
# Lambda function to generate Fibonacci series
fib_series = lambda n: reduce(lambda x, _: x + [x[-1] + x[-2]], range(n - 2), [0, 1])
# Get input from user
n = int(input("Enter the number of Fibonacci terms: "))
print(f"Fibonacci Series: {fib_series(n)}")
Example Output:
Enter the number of Fibonacci terms: 10
Fibonacci Series: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Explanation:
reduce(lambda x, _: x + [x[-1] + x[-2]], range(n - 2), [0, 1]) generates the Fibonacci sequence.
The reduce function accumulates the series step by step.
(ii) Python Program to Find the Power of a Number
Using lambda and pow() function
Method 1: Using Lambda Function
power = lambda base, exp: base ** exp
# Get input from user
base = int(input("Enter base number: "))
exp = int(input("Enter exponent: "))
print(f"{base}^{exp} = {power(base, exp)}")
Example Output:
Enter base number: 2
Enter exponent: 5
2^5 = 32
Method 2: Using pow() Function
# Get input from user
base = int(input("Enter base number: "))
exp = int(input("Enter exponent: "))
# Using pow() function
result = pow(base, exp)
print(f"{base}^{exp} = {result}")
Example Output:
Enter base number: 3
Enter exponent: 4
3^4 = 81
Key Points:
lambda base, exp: base ** exp → Short function for power calculation.
pow(base, exp) → Built-in function that calculates base^exp.
7. Discuss string manipulation techniques in Python, including string formatting, comparison, slicing,
and negative indexing.
Python provides powerful tools for working with strings. The key techniques include:
String Formatting
String Comparison
String Slicing
Negative Indexing
1. String Formatting
String formatting allows inserting values into a string dynamically.
Methods of String Formatting
Python provides four types of string formatting methods:
1. Old-style % Formatting
2. [Link]() Method
3. F-strings (Formatted String Literals, f"string")
4. Template Strings ([Link])
Let's explore each with examples.
1. Old-style % Formatting (C-style Formatting)
This method uses placeholders (%s, %d, %f) to insert values into a string.
name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
Output:
pgsql
My name is Alice and I am 25 years old.
Common Placeholders:
Placeholder Description
%s String
%d Integer
%f Float
%.2f Float with 2 decimal places
Example:
pi = 3.14159
print("Pi value: %.2f" % pi) # Output: "Pi value: 3.14"
2. [Link]() Method
Introduced in Python 3, this method uses {} placeholders.
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
Output:
My name is Alice and I am 25 years old.
Positional and Keyword Arguments
print("I love {1} and {0}".format("Java", "Python")) # "I love Python and Java"
print("My name is {name} and I am {age}.".format(name="Alice", age=25))
3. F-strings (f"string") [Recommended]
Introduced in Python 3.6, f-strings allow embedding expressions inside curly brackets {}.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Output:
My name is Alice and I am 25 years old.
Mathematical Expressions & Function Calls
num = 5
print(f"5 squared is {num ** 2}") # "5 squared is 25"
Formatting Numbers
pi = 3.14159
print(f"Pi value: {pi:.2f}") # "Pi value: 3.14"
4. Template Strings ([Link])
Uses $variable placeholders.
Safer when working with user inputs (e.g., avoiding injection attacks in web apps).
from string import Template
t = Template("Hello, my name is $name and I am $age years old.")
print([Link](name="Alice", age=25))
Output:
Hello, my name is Alice and I am 25 years old.
2. String Comparison
Python allows comparing strings using comparison operators (==, !=, >, <, >=, <=).
Example:
str1 = "apple"
str2 = "banana"
print(str1 == str2) # False (apple is not equal to banana)
print(str1 < str2) # True (apple comes before banana in dictionary order)
Explanation:
"apple" < "banana" is True because 'a' comes before 'b' in ASCII order.
Key Point: String comparison in Python is case-sensitive. "Apple" != "apple".
3. String Slicing
String slicing is used to extract a substring from a given string.
Syntax:
string[start:end:step]
start → Starting index (inclusive)
end → Ending index (exclusive)
step → Number of steps to move (default = 1)
Example:
text = "PythonProgramming"
print(text[0:6]) # Output: Python
print(text[:6]) # Output: Python (start is default)
print(text[6:]) # Output: Programming (till the end)
print(text[::2]) # Output: PtoPormig (every second character)
Key Point: If start or end is omitted, Python assumes start = 0 and end = length of string.
4. Negative Indexing
Negative indexing helps access elements from the end of the string.
The last character is indexed as -1, the second-last as -2, and so on.
Example:
text = "Python"
print(text[-1]) # Output: n (last character)
print(text[-3]) # Output: h (third-last character)
print(text[::-1]) # Output: nohtyP (reverse string)
Key Point: [::-1] is a quick way to reverse a string in Python.
Example Program Using All Techniques
# String Formatting
name = "Alice"
age = 25
formatted_string = f"My name is {name} and I am {age} years old."
# String Comparison
str1 = "hello"
str2 = "Hello"
comparison = str1 == str2 # False (case-sensitive)
# String Slicing
text = "PythonProgramming"
substring = text[6:12] # "Progra"
# Negative Indexing
last_char = text[-1] # "g"
reversed_text = text[::-1] # "gnimmargorPnohtyP"
# Output Results
print(formatted_string)
print("Are strings equal?", comparison)
print("Substring:", substring)
print("Last character:", last_char)
print("Reversed String:", reversed_text)
Output:
My name is Alice and I am 25 years old.
Are strings equal? False
Substring: Progra
Last character: g
Reversed String: gnimmargorPnohtyP
8. Explain in detail about built in functions with example.
Python provides built-in functions that perform common operations without requiring additional
code. These functions help in mathematical operations, string manipulations, type conversions,
input/output handling, and more.
Categories of Built-in Functions
Python has several built-in functions, categorized as follows:
Mathematical Functions
Type Conversion Functions
String Functions
List and Tuple Functions
Input/Output Functions
Logical and Comparison Functions
Miscellaneous Functions
Let's explore each category with examples.
1. Mathematical Functions
These functions perform arithmetic and mathematical operations.
Function Description Example
abs(x) Returns the absolute value of x abs(-10) → 10
pow(x, y) Returns x raised to the power of y pow(2, 3) → 8
round(x, n) Rounds x to n decimal places round(3.14159, 2) → 3.14
max(a, b, c, ..) Returns the maximum value max(5, 9, 2) → 9
min(a, b, c, ..) Returns the minimum value min(5, 9, 2) → 2
Example:
print(abs(-7)) # Output: 7
print(pow(2, 4)) # Output: 16
print(round(3.14159, 3)) # Output: 3.142
print(max(10, 20, 5)) # Output: 20
print(min(10, 20, 5)) # Output: 5
2. Type Conversion Functions
These functions convert data types.
Function Description Example
int(x) Converts x to an integer int(3.9) → 3
float(x) Converts x to a floating-point number float(5) → 5.0
str(x) Converts x to a string str(10) → "10"
bool(x) Converts x to a Boolean bool(0) → False
Example:
num = "25"
num_int = int(num)
print(num_int) # Output: 25 (integer)
print(float(5)) # Output: 5.0 (float)
print(str(100)) # Output: "100" (string)
print(bool("")) # Output: False (empty string is False)
3. String Functions
Python provides functions to manipulate strings.
Function Description Example
len(s) Returns the length of a string len("hello") → 5
upper() Converts to uppercase "hello".upper() → "HELLO"
lower() Converts to lowercase "HELLO".lower() → "hello"
replace(a, b) Replaces a with b "hello".replace("l", "z") → "hezzo"
Example:
s = "Python"
print(len(s)) # Output: 6
print([Link]()) # Output: PYTHON
print([Link]()) # Output: python
print([Link]("y", "i")) # Output: Pithon
[Link] and Tuple Functions
These functions operate on lists and tuples.
Function Description Example
len(lst) Returns the length of a list len([1,2,3]) → 3
sum(lst) Returns the sum of elements sum([1,2,3]) → 6
sorted(lst) Returns a sorted list sorted([3,1,2]) → [1,2,3]
list(tuple) Converts a tuple to a list list((1,2,3)) → [1,2,3]
Example:
numbers = [4, 2, 8, 6]
print(len(numbers)) # Output: 4
print(sum(numbers)) # Output: 20
print(sorted(numbers)) # Output: [2, 4, 6, 8]
5. Input/Output Functions
These functions handle user input and output.
Function Description Example
input() Reads user input name = input("Enter name: ")
print() Prints to console print("Hello World")
Example:
name = input("Enter your name: ")
print("Hello, " + name + "!")
6. Logical and Comparison Functions
These functions handle Boolean logic and comparisons.
Function Description Example
all(iterable) Returns True if all elements are True all([True, False]) → False
any(iterable) Returns True if any element is True any([False, True]) → True
Example:
values = [True, True, False]
print(all(values)) # Output: False
print(any(values)) # Output: True
7. Miscellaneous Functions
Other useful functions include:
Function Description Example
id(x) Returns memory address of x id(5)
type(x) Returns type of x type(5) → <class 'int'>
dir(x) Lists all attributes/methods of x dir(str)
help(x) Displays help on x help(print)
Example:
x = 100
print(type(x)) # Output: <class 'int'>
print(id(x)) # Output: Memory address of x
Example Program Using Multiple Built-in Functions
# Mathematical Functions
print(abs(-10)) # Output: 10
print(pow(3, 2)) # Output: 9
# Type Conversion
num = "100"
num_int = int(num)
print(num_int) # Output: 100
# String Functions
s = "Python"
print(len(s)) # Output: 6
print([Link]()) # Output: PYTHON
# List Functions
numbers = [3, 1, 4, 2]
print(sorted(numbers)) # Output: [1, 2, 3, 4]
# Logical Functions
values = [True, True, False]
print(any(values)) # Output: True
9. i) Write a Python program sum of n numbers using recursion. ii) Write a Python program to find
factorial of n number using recursion.
i) Python Program to Find Sum of N Numbers Using Recursion
def sum_of_numbers(n):
"""Recursive function to calculate the sum of first n natural numbers."""
if n == 0: # Base case
return 0
else:
return n + sum_of_numbers(n - 1) # Recursive call
# Taking input from the user
n = int(input("Enter a positive integer: "))
# Checking if the input is valid
if n < 0:
print("Please enter a positive integer.")
else:
result = sum_of_numbers(n)
print(f"The sum of first {n} natural numbers is: {result}")
Explanation of the Program
1. Function Definition (sum_of_numbers(n))
This function calculates the sum of the first n natural numbers using recursion.
Base Case: If n == 0, return 0 (stopping condition).
Recursive Case: If n > 0, return n + sum_of_numbers(n-1) (calls itself with n-1).
2. Input from User
The program asks the user to enter a positive integer.
It ensures the user enters a valid non-negative number.
3. Function Execution
If n = 5, the function works as follows:
sum_of_numbers(5) = 5 + sum_of_numbers(4)
sum_of_numbers(4) = 4 + sum_of_numbers(3)
sum_of_numbers(3) = 3 + sum_of_numbers(2)
sum_of_numbers(2) = 2 + sum_of_numbers(1)
sum_of_numbers(1) = 1 + sum_of_numbers(0)
sum_of_numbers(0) = 0 (Base case reached)
Now, the values return in reverse order:
sum_of_numbers(1) = 1 + 0 = 1
sum_of_numbers(2) = 2 + 1 = 3
sum_of_numbers(3) = 3 + 3 = 6
sum_of_numbers(4) = 4 + 6 = 10
sum_of_numbers(5) = 5 + 10 = 15
4. Final Output
If the user inputs n = 5, the program prints:
The sum of first 5 natural numbers is: 15
ii) Python Program to Find Factorial of a Number Using Recursion
def factorial(n):
"""Recursive function to find the factorial of a number."""
if n == 0 or n == 1: # Base case
return 1
else:
return n * factorial(n - 1) # Recursive call
# Taking input from the user
n = int(input("Enter a non-negative integer: "))
# Checking if the input is valid
if n < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(n)
print(f"The factorial of {n} is: {result}")
Explanation of the Program
1. Function Definition (factorial(n))
The function calculates the factorial of n recursively.
Base Case:
o If n == 0 or n == 1, return 1. (Since 0! = 1! = 1)
Recursive Case:
o If n > 1, return n * factorial(n-1).
o This means the function calls itself with n-1 until it reaches the base case.
2. Input from the User
The program asks the user to enter a non-negative integer.
If the user enters a negative number, it prints an error message.
3. Function Execution
If n = 5, the recursive calls work like this:
factorial(5) = 5 * factorial(4)
factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1 (Base case reached)
Now, the values return in reverse order:
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
factorial(4) = 4 * 6 = 24
factorial(5) = 5 * 24 = 120
So, factorial(5) = 120.
4. Final Output
Example Run 1 (Valid Input)
Enter a non-negative integer: 5
The factorial of 5 is: 120
Example Run 2 (Invalid Input)
Enter a non-negative integer: -3
Factorial is not defined for negative numbers.
10. Explain about function composition with example program.
Function composition is a technique where one function is called inside another function. It allows
the output of one function to be used as the input of another, creating a chain of function calls.
Benefits of Function Composition:
Code Reusability – Functions can be reused multiple times.
Modularity – Complex logic is divided into smaller, manageable parts.
Readability – Improves code clarity by avoiding redundant calculations.
Example 1: Simple Function Composition
def square(x):
return x * x
def double(y):
return 2 * y
# Composing functions
def square_then_double(n):
return double(square(n))
# Taking input from user
num = int(input("Enter a number: "))
print("Result:", square_then_double(num))
Sample Output:
Enter a number: 3
Result: 18
Example 2: Using Function Composition in a Math Expression
def add(a, b):
return a + b
def multiply(x, y):
return x * y
# Function composition
def add_then_multiply(a, b, c):
return multiply(add(a, b), c)
# Taking input from user
result = add_then_multiply(2, 3, 4)
print("Result:", result)
Sample Output:
Result: 20
Example 3: Function Composition with Built-in Functions
# Using built-in functions with function composition
num = -10
result = abs(int(str(num)))
print("Result:", result)
Sample Output:
Result: 10
Part – C (15 marks)
[Link] about selection sorting with necessary example and write about regular expression.
Selection Sort
🔹 What is Selection Sort?
Selection Sort is a simple and efficient comparison-based sorting algorithm. It works by repeatedly
selecting the smallest (or largest) element from the unsorted part of the list and moving it to the sorted
part.
🔹 How Selection Sort Works?
The selection sort algorithm divides the list into two parts:
1. Sorted Part (on the left)
2. Unsorted Part (on the right)
Steps to Perform Selection Sort:
1. Find the smallest element in the unsorted part.
2. Swap it with the first element of the unsorted part.
3. Move the boundary between sorted and unsorted parts one step right.
4. Repeat until the list is sorted.
🔹 Example Walkthrough
Consider an unsorted array:
[64, 25, 12, 22, 11]
Step-by-Step Execution:
Pass Array State Smallest Element Found Swap
1 [64, 25, 12, 22, 11] 11 Swap 64 and 11 → [11, 25, 12, 22, 64]
2 [11, 25, 12, 22, 64] 12 Swap 25 and 12 → [11, 12, 25, 22, 64]
3 [11, 12, 25, 22, 64] 22 Swap 25 and 22 → [11, 12, 22, 25, 64]
4 [11, 12, 22, 25, 64] 25 No swap needed
5 [11, 12, 22, 25, 64] Sorted! ✅
📌 Final Sorted List: [11, 12, 22, 25, 64]
🔹 Python Program for Selection Sort
# Function to perform Selection Sort
def selection_sort(arr):
n = len(arr)
for i in range(n - 1): # Loop through each element
min_index = i # Assume first element is the minimum
for j in range(i + 1, n): # Find the smallest element in the unsorted part
if arr[j] < arr[min_index]:
min_index = j # Update the index of the smallest element
# Swap the smallest element with the first element of the unsorted part
arr[i], arr[min_index] = arr[min_index], arr[i]
print(f"Step {i+1}: {arr}") # Print each step for better understanding
# Input list
arr = [64, 25, 12, 22, 11]
print("Original array:", arr)
selection_sort(arr) # Call function
print("Sorted array:", arr)
🔹 Output of the Program
Original array: [64, 25, 12, 22, 11]
Step 1: [11, 25, 12, 22, 64]
Step 2: [11, 12, 25, 22, 64]
Step 3: [11, 12, 22, 25, 64]
Step 4: [11, 12, 22, 25, 64]
Sorted array: [11, 12, 22, 25, 64]
🔹 Time Complexity of Selection Sort
Case Time Complexity
Best Case (Already Sorted) O(n²)
Worst Case (Reverse Sorted) O(n²)
Average Case O(n²)
✔ Selection sort always runs in O(n²) time complexity, even if the list is already sorted.
🔹 Advantages of Selection Sort
Simple & easy to understand
Works well for small datasets
In-place sorting (does not use extra space)
🔹 Disadvantages of Selection Sort
Inefficient for large lists (O(n²) complexity)
Slow compared to modern sorting algorithms like QuickSort, MergeSort
🔹 When to Use Selection Sort?
🔹 When the list size is small
🔹 When memory space is limited (since it's an in-place algorithm)
🔹 When simplicity is preferred over performance
Regular Expressions in Python
Regular Expressions (regex) are used to search, match, and manipulate strings based on patterns.
Common Regex Functions in Python (re Module)
Function Description
[Link]() Checks for a match only at the beginning of a string.
[Link]() Searches for a match anywhere in the string.
[Link]() Returns all matches as a list.
[Link]() Replaces matches with a specified string.
Example: Using Regular Expressions
import re
# Match example
text = "Hello, my email is example@[Link]"
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
match = [Link](pattern, text)
if match:
print("Found email:", [Link]())
Output:
Found email: example@[Link]
[Link] about various string built in methods with example.
Python provides many built-in string methods that help in manipulating and processing strings efficiently.
These methods do not modify the original string (since strings in Python are immutable) but return new
modified strings.
1. Case Conversion Methods
These methods are used to change the case of strings.
upper() – Converts to Uppercase
text = "hello world"
print([Link]()) # Output: "HELLO WORLD"
lower() – Converts to Lowercase
text = "HELLO WORLD"
print([Link]()) # Output: "hello world"
title() – Converts to Title Case (First letter of each word is capitalized)
text = "hello world python"
print([Link]()) # Output: "Hello World Python"
capitalize() – Capitalizes First Letter of the String
text = "hello world"
print([Link]()) # Output: "Hello world"
swapcase() – Swaps Lowercase to Uppercase and Vice Versa
text = "Hello World"
print([Link]()) # Output: "hELLO wORLD"
2. String Checking Methods
These methods check if a string satisfies certain conditions.
isalpha() – Checks if String Contains Only Alphabets
text = "Hello"
print([Link]()) # Output: True
text = "Hello123"
print([Link]()) # Output: False
isdigit() – Checks if String Contains Only Digits
text = "12345"
print([Link]()) # Output: True
text = "123abc"
print([Link]()) # Output: False
isalnum() – Checks if String Contains Only Alphabets and Numbers
text = "Hello123"
print([Link]()) # Output: True
text = "Hello 123"
print([Link]()) # Output: False (Space is not alphanumeric)
isspace() – Checks if String Contains Only Whitespaces
text = " "
print([Link]()) # Output: True
text = " Hello "
print([Link]()) # Output: False
startswith() – Checks if String Starts with a Specific Substring
text = "Hello World"
print([Link]("Hello")) # Output: True
print([Link]("World")) # Output: False
endswith() – Checks if String Ends with a Specific Substring
text = "Hello World"
print([Link]("World")) # Output: True
print([Link]("Hello")) # Output: False
3. String Modification Methods
These methods modify the string by removing or replacing characters.
strip() – Removes Leading and Trailing Whitespaces
text = " Hello World "
print([Link]()) # Output: "Hello World"
lstrip() – Removes Leading Whitespaces Only
text = " Hello World "
print([Link]()) # Output: "Hello World "
rstrip() – Removes Trailing Whitespaces Only
text = " Hello World "
print([Link]()) # Output: " Hello World"
replace() – Replaces Substring with Another Substring
text = "Hello World"
print([Link]("World", "Python")) # Output: "Hello Python"
4. String Splitting and Joining Methods
These methods help split or join strings.
split() – Splits String into a List
text = "apple,banana,grapes"
print([Link](",")) # Output: ['apple', 'banana', 'grapes']
splitlines() – Splits String at Line Breaks (\n)
text = "Hello\nWorld\nPython"
print([Link]()) # Output: ['Hello', 'World', 'Python']
join() – Joins a List of Strings into a Single String
words = ["Hello", "World", "Python"]
print(" ".join(words)) # Output: "Hello World Python"
5. String Finding and Counting Methods
These methods help find substrings or count occurrences.
find() – Returns Index of First Occurrence of a Substring
text = "Hello World"
print([Link]("World")) # Output: 6
print([Link]("Python")) # Output: -1 (Not Found)
index() – Like find(), But Raises Error if Not Found
text = "Hello World"
print([Link]("World")) # Output: 6
# print([Link]("Python")) # Raises ValueError: substring not found
count() – Counts Occurrences of a Substring
text = "banana banana banana"
print([Link]("banana")) # Output: 3
6. String Formatting Methods
These methods format strings in different ways.
format() – Formats a String Using Placeholders
name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# Output: "My name is Alice and I am 25 years old."
f-string – Best Way to Format Strings (Python 3.6+)
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# Output: "My name is Alice and I am 25 years old."
7. Miscellaneous Methods
zfill() – Pads String with Zeros
text = "42"
print([Link](5)) # Output: "00042"
7center() – Centers the String Within a Given Width
text = "Python"
print([Link](10, "*")) # Output: "**Python**"
ljust() and rjust() – Aligns String to Left/Right
text = "Python"
print([Link](10, "*")) # Output: "Python****"
print([Link](10, "*")) # Output: "****Python"
Conclusion
Method Type Examples
Case Conversion upper(), lower(), title(), capitalize(), swapcase()
String Checking isalpha(), isdigit(), isalnum(), isspace(), startswith(), endswith()
Modification strip(), replace(), lstrip(), rstrip()
Splitting & Joining split(), join(), splitlines()
Finding & Counting find(), index(), count()
Formatting format(), f-string, zfill(), center(), ljust(), rjust()
UNIT- III- COLLECTIONS
PART A ( 2 Marks)
1. Define List with example.
A list in Python is a mutable, ordered collection of elements that can hold different data types, such as
numbers, strings, or even other lists. Lists are created using square brackets [], and elements are separated
by commas.
Syntax:
list_name = [element1, element2, element3, ...]
2. What do you mean by list comprehension?
List comprehension is a concise way to create lists in Python using a single line of code. It provides a
shorter syntax for creating a new list by applying an expression to each item in an iterable (like a list,
range, or string).
Syntax:
new_list = [expression for item in iterable if condition]
expression → Defines how each element is transformed.
item → Represents each value from the iterable.
iterable → The sequence (list, range, string, etc.) being looped through.
condition (optional) → Filters elements before applying the expression.
3. Write about membership operator.
Membership operators in and not in are used to check whether a value exists in a sequence (like a list,
tuple, string, dictionary, or set). They return True if the value is present and False if not.
1. in Operator
Checks if a value is present in a sequence.
Returns True if found.
Returns False if not found.
Example:
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("grape" in fruits) # False
2. not in Operator
🔹 Checks if a value is NOT present in a sequence.
Returns True if the value is not found.
Returns False if found.
Example:
numbers = [1, 2, 3, 4, 5]
print(10 not in numbers) # True
print(3 not in numbers) # False
4. What are the different operations performed on a dictionary.
A dictionary in Python supports various operations such as accessing, modifying, adding, deleting, and
looping through key-value pairs. Below are the key operations performed on dictionaries:
Operation Method Example
Accessing Elements [], get() student["name"], [Link]("age")
Adding/Updating dict[key] = value student["city"] = "NY"
Removing Elements pop(), del, popitem(), clear() [Link]("age")
Getting Keys/Values keys(), values(), items() [Link]()
Looping for key, value in [Link]() Iterating through dictionary
Merging update() [Link](extra_info)
Copying copy() new_dict = [Link]()
Operation Method Example
Dictionary Comprehension {k: v for k, v in iterable} {x: x**2 for x in range(1, 6)}
[Link] the set methods with an example.
A set in Python is an unordered, mutable collection that does not allow duplicate values. Python
provides several built-in methods to perform operations on sets.
Method Description Example
add() Adds an element to the set [Link](10)
update() Adds multiple elements from an iterable [Link]([6, 7, 8])
remove() Removes an element; raises KeyError if not found [Link](3)
Removes an element; does not raise an error if not
discard() [Link](3)
found
pop() Removes and returns a random element [Link]()
clear() Removes all elements from the set [Link]()
union() Returns a new set with all elements from both sets [Link](s2)
intersection() Returns a new set with common elements [Link](s2)
difference() Returns a new set with elements only in the first set [Link](s2)
Returns a new set with elements in either set but not
symmetric_difference() s1.symmetric_difference(s2)
both
issubset() Checks if a set is a subset of another [Link](s2)
issuperset() Checks if a set is a superset of another [Link](s2)
isdisjoint() Checks if two sets have no common elements [Link](s2)
copy() Returns a shallow copy of the set s2 = [Link]()
6. Give the operations on tuple.
A tuple is an immutable and ordered collection of elements in Python. It supports various operations.
Operation Description Example
Indexing Access an element by position tup[1] → 20
Slicing Extract a sub-tuple tup[1:3] → (20, 30)
Concatenation Join two tuples (1,2) + (3,4) → (1,2,3,4)
Repetition Repeat elements tup * 2 → (10,20,10,20)
Length Count elements len(tup) → 4
Membership Check if an element exists 10 in tup → True
Iteration Loop through elements for x in tup:
Finding Elements Get index & count [Link](30), [Link](10)
Packing/Unpacking Assign multiple values a, b = (10, 20)
7. How do you add or replace a value in a dictionary in Python?
In Python, dictionaries are mutable, meaning we can add new key-value pairs or update existing values
easily.
Operation Syntax Example
Add a New Key-Value Pair dict[key] = value student["grade"] = "A"
Replace an Existing Value dict[key] = new_value student["age"] = 21
Update Multiple Values [Link]({key: value}) [Link]({"age": 22, "city": "NY"})
8. How to convert a list in to tuple and tuple into a list.
ython provides built-in functions tuple() and list() to convert between lists and tuples.
Conversion Function Used Example
List → Tuple tuple(list_name) tuple([1, 2, 3]) → (1, 2, 3)
Tuple → List list(tuple_name) list((10, 20, 30)) → [10, 20, 30]
my_list = [1, 2, 3, 4] my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list) my_tuple = tuple(my_list)
print(my_tuple) print(my_tuple)
9. Write a python program to find the maximum and minimum n elements in a tuple.
def find_max_min_n_elements(tup, n):
sorted_tup = sorted(tup) # Sort the tuple in ascending order
min_elements = sorted_tup[:n] # First 'n' elements (smallest)
max_elements = sorted_tup[-n:] # Last 'n' elements (largest)
return min_elements, max_elements
# Example Tuple
numbers = (10, 5, 3, 8, 12, 15, 7, 20)
# Find 3 Minimum and Maximum Elements
n=3
min_n, max_n = find_max_min_n_elements(numbers, n)
print("Minimum", n, "Elements:", min_n)
print("Maximum", n, "Elements:", max_n)
10. Write about packing and unpacking in a tuple with example.
Python allows packing multiple values into a tuple and unpacking them into separate variables.
Packing means assigning multiple values into a single tuple.
Unpacking means extracting values from a tuple into separate variables.
If there are more values than variables, we can use * to store extra values in a list.
Operation Description Example
Packing Storing multiple values in a tuple tup = (10, 20, 30)
Unpacking Extracting values from a tuple a, b, c = (10, 20, 30)
Extended Unpacking (*) Stores extra values in a list a, *b = (1, 2, 3, 4)
Descriptive Questions ( 13 Marks)
1. Compare list, tuple and dictionary with its salient features.
Feature List Tuple Dictionary
Feature List Tuple Dictionary
Ordered collection of Ordered, immutable Unordered collection of key-
Definition
elements collection value pairs
Mutable? Yes (modifiable) No (immutable) Yes (modifiable)
Syntax list = [1, 2, 3] tuple = (1, 2, 3) dict = {"a": 1, "b": 2}
Indexing Supported Supported Keys act as indexes
Duplicates
Yes Yes No (Keys must be unique)
Allowed?
Operations Append, Remove, Sort Indexing, Slicing Add, Update, Remove
Faster (due to
Performance Slower (due to mutability) Efficient key-based access
immutability)
When modification is When fixed data is When key-value mapping is
Use Case
needed required required
# 1. List (Ordered & Mutable)
fruits = ["apple", "banana", "cherry"]
[Link]("mango") # Adding element
print("List:", fruits)
# 2. Tuple (Ordered & Immutable)
colors = ("red", "green", "blue")
print("Tuple:", colors)
print("Accessing Tuple Element:", colors[1]) # Accessing element
# 3. Dictionary (Key-Value Pair)
student = {"name": "John", "age": 20}
student["age"] = 21 # Updating value
student["grade"] = "A" # Adding new key-value pair
print("Dictionary:", student)
# 4. Accessing Elements
print("First fruit in list:", fruits[0]) # List indexing
print("First color in tuple:", colors[0]) # Tuple indexing
print("Student Name:", student["name"]) # Dictionary key access
# 5. Iterating Through Each
print("\nIterating through list:")
for fruit in fruits:
print(fruit)
print("\nIterating through tuple:")
for color in colors:
print(color)
print("\nIterating through dictionary (keys & values):")
for key, value in [Link]():
print(key, ":", value)
OUTPUT
List: ['apple', 'banana', 'cherry', 'mango']
Tuple: ('red', 'green', 'blue')
Accessing Tuple Element: green
Dictionary: {'name': 'John', 'age': 21, 'grade': 'A'}
First fruit in list: apple
First color in tuple: red
Student Name: John
Iterating through list:
apple
banana
cherry
mango
Iterating through tuple:
red
green
blue
Iterating through dictionary (keys & values):
name : John
age : 21
grade : A
2. Explain all the list methods with an example?
Python provides several built-in list methods to perform operations like adding, removing, and modifying
elements. Below is a detailed explanation with examples.
1. Adding Elements to a List
Method Description Example
append(value) Adds an element to the end of the list. [Link](6)
insert(index, value) Inserts an element at a specific position. [Link](2, 10)
extend(iterable) Adds multiple elements from another iterable (list, tuple, etc.). [Link]([7, 8])
Example Code:
numbers = [1, 2, 3]
[Link](4) # Adds 4 at the end
[Link](1, 10) # Inserts 10 at index 1
[Link]([5, 6]) # Adds multiple elements
print(numbers)
Output:
[1, 10, 2, 3, 4, 5, 6]
2. Removing Elements from a List
Method Description Example
remove(value) Removes the first occurrence of the value. [Link](3)
Method Description Example
pop(index) Removes and returns the element at the given index. [Link](2)
clear() Removes all elements from the list. [Link]()
Example Code:
fruits = ["apple", "banana", "cherry", "banana"]
[Link]("banana") # Removes the first 'banana'
print(fruits)
numbers = [10, 20, 30, 40]
popped_value = [Link](1) # Removes element at index 1
print(numbers, "Popped:", popped_value)
[Link]() # Removes all elements
print(numbers)
Output:
['apple', 'cherry', 'banana']
[10, 30, 40] Popped: 20
[]
3. Sorting & Reversing a List
Method Description Example
sort(reverse=False) Sorts the list in ascending order. [Link]()
sort(key=len) Sorts the list using a custom key (e.g., by length). [Link](key=len)
reverse() Reverses the order of elements in the list. [Link]()
Example Code:
nums = [4, 1, 3, 2]
[Link]() # Sorts in ascending order
print(nums)
words = ["apple", "kiwi", "banana"]
[Link](key=len) # Sorts by word length
print(words)
[Link]() # Reverses the order
print(nums)
Output:
[1, 2, 3, 4]
['kiwi', 'apple', 'banana']
[4, 3, 2, 1]
4. Searching & Counting Elements
Method Description Example
index(value) Returns the index of the first occurrence. [Link](5)
count(value) Counts the occurrences of a value. [Link](3)
Example Code:
nums = [10, 20, 30, 10, 40]
print([Link](30)) # Finds index of 30
print([Link](10)) # Counts occurrences of 10
Output:
2
2
5. Copying a List
Method Description Example
copy() Returns a shallow copy of the list. new_list = [Link]()
Example Code:
original = [1, 2, 3]
copied = [Link]()
print(copied)
Output:
[1, 2, 3]
Summary Table of List Methods
Method Description
append(value) Adds an element to the end of the list.
insert(index, value) Inserts an element at a specific index.
extend(iterable) Adds multiple elements from another iterable.
remove(value) Removes the first occurrence of a value.
pop(index) Removes and returns the element at a given index.
clear() Removes all elements from the list.
sort(reverse=False, key=None) Sorts the list (ascending by default).
reverse() Reverses the order of elements.
index(value) Returns the index of the first occurrence of a value.
count(value) Counts how many times a value appears.
copy() Returns a copy of the list.
3. Enumerate all the details about the dictionaries with its relevant methods.
In Python, a dictionary is an unordered, mutable collection of key-value pairs. It is defined using curly
braces {} or the dict() constructor.
1. Dictionary Characteristics
Unordered (before Python 3.7) but maintains insertion order (from Python 3.7+).
Mutable (can be modified after creation).
Key-Value Pair Structure (key: value).
Keys Must Be Unique (no duplicates allowed).
Keys Must Be Immutable (strings, numbers, or tuples but not lists or other dictionaries).
Values Can Be Any Data Type (strings, lists, dictionaries, etc.).
2. Creating a Dictionary
# Using curly braces
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
# Using the dict() constructor
my_dict2 = dict(name='Alice', age=25, city='New York')
# Using dict() with a list of tuples
my_dict3 = dict([('name', 'Alice'), ('age', 25), ('city', 'New York')])
3. Dictionary Methods
Python provides various built-in methods for dictionaries:
Method Description Example
[Link]() Removes all items from the dictionary. my_dict.clear()
[Link]() Returns a shallow copy of the dictionary. new_dict = my_dict.copy()
Returns the value for the given key. If the key
[Link](key, default) my_dict.get('age', 0)
is not found, returns the specified default value.
Returns a view object of dictionary’s key-value
[Link]() my_dict.items()
pairs.
[Link]() Returns a view object of all dictionary keys. my_dict.keys()
[Link]() Returns a view object of all dictionary values. my_dict.values()
Removes and returns the value of the given
[Link](key, default) key. If the key is not found, returns the default my_dict.pop('age', 0)
value.
Removes and returns the last inserted key-
[Link]() value pair as a tuple. (In Python 3.7+, it follows my_dict.popitem()
insertion order).
[Link](key, Returns the value of the key. If the key does my_dict.setdefault('gender',
default) not exist, inserts it with the given default value. 'Female')
Merges another dictionary into the current
my_dict.update({'age': 26,
[Link](other_dict) dictionary, updating existing keys and adding
'country': 'USA'})
new ones.
[Link](iterable, Creates a dictionary with keys from an iterable new_dict = [Link](['a', 'b',
value) and assigns them all the given value. 'c'], 0)
4. Dictionary Operations
Accessing Elements
print(my_dict['name']) # Access by key
print(my_dict.get('age')) # Using get() method
Adding & Updating Elements
my_dict['age'] = 26 # Updating a value
my_dict['gender'] = 'Female' # Adding a new key-value pair
Removing Elements
del my_dict['age'] # Deletes key-value pair
value = my_dict.pop('city') # Removes and returns value
my_dict.popitem() # Removes and returns the last key-value pair
Dictionary Comprehension
squared_numbers = {x: x**2 for x in range(1, 6)}
5. Dictionary Iteration
# Iterating over keys
for key in my_dict.keys():
print(key)
# Iterating over values
for value in my_dict.values():
print(value)
# Iterating over key-value pairs
for key, value in my_dict.items():
print(f"{key}: {value}")
6. Nesting Dictionaries
students = {
'Alice': {'age': 25, 'city': 'New York'},
'Bob': {'age': 27, 'city': 'Chicago'}
}
print(students['Alice']['age']) # Access nested dictionary
4. Explain set operations with an example.
Set Operations in Python
A set is an unordered collection of unique elements. Python provides several operations that can be
performed on sets, such as union, intersection, difference, and symmetric difference.
1. Creating a Set
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
2. Set Operations
Operation Method Symbol Description Example
Returns all unique elements from
Union [Link]() ` `
both sets.
Returns common A & B or [Link](B) →
Intersection [Link]() &
elements in both sets. {4, 5}
Returns elements in A - B or [Link](B) → {1,
Difference [Link]() -
A but not in B. 2, 3}
Returns elements in A ^ B or
Symmetric
set.symmetric_difference() ^ either A or B, but not A.symmetric_difference(B) →
Difference
both. {1, 2, 3, 6, 7, 8}
Returns True if all
Subset [Link]() - elements of A are in {1, 2}.issubset(A) → True
B.
Returns True if A
Superset [Link]() - contains all elements [Link]({1, 2}) → True
of B.
Operation Method Symbol Description Example
Returns True if A
Disjoint [Link]() - and B have no {9, 10}.isdisjoint(A) → True
elements in common.
3. Example Code
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print("Union:", A | B) # {1, 2, 3, 4, 5, 6, 7, 8}
print("Intersection:", A & B) # {4, 5}
print("Difference (A - B):", A - B) # {1, 2, 3}
print("Difference (B - A):", B - A) # {6, 7, 8}
print("Symmetric Difference:", A ^ B) # {1, 2, 3, 6, 7, 8}
print("Is A a subset of B?", [Link](B)) # False
print("Is A a superset of B?", [Link](B)) # False
5. Explain about list slicing, aliasing and cloning with example.
List Slicing, Aliasing, and Cloning in Python
1. List Slicing
List slicing allows you to extract a part of a list without modifying the original list. It uses the syntax:
list[start:stop:step]
start → Index where the slice begins (default is 0).
stop → Index where the slice ends (excluded).
step → Step size for skipping elements (default is 1).
Example of List Slicing
numbers = [10, 20, 30, 40, 50, 60, 70, 80]
# Basic Slicing
print(numbers[1:5]) # [20, 30, 40, 50] (from index 1 to 4)
# Omitting Start or Stop
print(numbers[:4]) # [10, 20, 30, 40] (from start to index 3)
print(numbers[3:]) # [40, 50, 60, 70, 80] (from index 3 to end)
# Using Step
print(numbers[::2]) # [10, 30, 50, 70] (every second element)
# Reversing a List
print(numbers[::-1]) # [80, 70, 60, 50, 40, 30, 20, 10]
# Slicing with Negative Indices
print(numbers[-5:-2]) # [40, 50, 60] (from index -5 to -3)
A negative index means counting from the end (-1 is the last element).
The step value determines how elements are selected.
2. List Aliasing
Aliasing means assigning an existing list to a new variable without creating a copy. Both variables point to
the same memory location, so modifying one affects the other.
Example of List Aliasing
list1 = [1, 2, 3, 4]
list2 = list1 # Aliasing: list2 refers to the same object as list1
[Link](5)
print(list1) # [1, 2, 3, 4, 5] (Changes reflect in list1)
print(list2) # [1, 2, 3, 4, 5] (Both lists are the same)
print(id(list1)) # Memory address of list1
print(id(list2)) # Same memory address as list1
Aliasing does not create a new list.
Both lists share the same memory address.
Any change in one affects the other.
3. List Cloning
Cloning creates a new copy of the list with a different memory location.
Methods of Cloning:
1. Using Slicing ([:])
list1 = [1, 2, 3, 4]
list2 = list1[:] # Cloning
[Link](5)
print(list1) # [1, 2, 3, 4] (Original list remains unchanged)
print(list2) # [1, 2, 3, 4, 5]
2. Using copy() Method
list1 = [1, 2, 3, 4]
list2 = [Link]()
3. Using list() Constructor
list1 = [1, 2, 3, 4]
list2 = list(list1)
4. Using [Link]() for Nested Lists
import copy
list1 = [[1, 2], [3, 4]]
list2 = [Link](list1)
Affects Original Works for Nested
Concept Description
List? Lists?
List Slicing ([:]) Extracts part of a list No Yes
Creates a new reference to the
Aliasing (=) Yes Yes
same list
No (nested lists remain
Copy (copy()) Creates a shallow copy No
linked)
Deep Copy
Creates a full, independent copy No Yes
([Link]())
[Link] about tuple as return value with example program
Tuple as Return Value
Definition:
In Python, a function can return multiple values. These values are usually returned as a tuple. A tuple is an
immutable data structure that can hold a collection of items. Returning a tuple is useful when we need to
send more than one value from a function to the caller.
Why use a Tuple as a Return Value?
Tuples group multiple return values into a single object.
It allows us to return different data types together.
Tuples are easy to unpack and use.
Simplifies code readability and reusability.
Syntax:
def function_name():
return value1, value2, value3 # Returns a tuple implicitly
Example Program:
Problem: Write a Python function that takes two numbers and returns their sum, difference, and
product as a tuple.
# Function to return sum, difference, and product
def calculate(a, b):
sum_result = a + b
diff_result = a - b
prod_result = a * b
return sum_result, diff_result, prod_result # returns as a tuple
# Calling the function
result = calculate(10, 5)
# Displaying the result
print("Returned Tuple:", result)
# Unpacking the tuple
sum_val, diff_val, prod_val = result
print("Sum:", sum_val)
print("Difference:", diff_val)
print("Product:", prod_val)
Explanation:
The function calculate() computes the sum, difference, and product of two numbers.
These three values are returned as a tuple.
The result is stored in a variable result and later unpacked into individual variables.
Advantages of Using Tuple as Return Value:
Efficient way to return multiple results.
Saves the need to create a class or multiple return statements.
Clean and concise syntax.
[Link] about linear search and write a python program to perform linear search on a list.
Linear Search
Definition:
Linear Search is a simple searching algorithm used to find the position of an element in a list or array. It
checks each element one by one from the beginning until the desired element is found or the list ends.
Characteristics of Linear Search:
Also known as Sequential Search.
Works on unsorted or sorted lists.
Best case: When the element is found at the beginning.
Worst case: When the element is not present or is at the end.
Algorithm Steps:
1. Start from the first element of the list.
2. Compare each element with the target (search element).
3. If a match is found, return the index.
4. If no match is found after checking all elements, return -1 (or element not found).
Time Complexity:
Best Case: O(1)
Worst Case: O(n)
Average Case: O(n)
Example Python Program:
# Function to perform linear search
def linear_search(lst, target):
for index in range(len(lst)):
if lst[index] == target:
return index # Return index if found
return -1 # Return -1 if not found
# Input list
numbers = [10, 25, 35, 40, 55, 65]
# Element to search
search_element = int(input("Enter the element to search: "))
# Function call
position = linear_search(numbers, search_element)
# Display result
if position != -1:
print(f"Element {search_element} found at index {position}.")
else:
print(f"Element {search_element} not found in the list.")
Sample Output:
Enter the element to search: 40
Element 40 found at index 3.
Explanation:
The function linear_search() checks each element of the list.
If the target value is found, it returns the index.
If the loop ends without a match, -1 is returned.
Advantages of Linear Search:
Simple and easy to implement.
No need for sorted data.
Works on both arrays and lists.
Disadvantages:
Inefficient for large datasets.
Takes more time as it checks each element one by one.
8. (i)Write a python program to create a histogram from a given list of integers.
Definition of Histogram:
A histogram is a graphical representation that uses symbols (commonly stars *) to represent the frequency
or value of items.
In Python, we can create a simple text-based histogram using loops by printing stars corresponding to each
integer value.
Program to Create a Histogram:
# Function to create a histogram
def create_histogram(lst):
print("Histogram:")
for num in lst:
print('*' * num)
# Example list of integers
numbers = [4, 7, 1, 5]
# Function call
create_histogram(numbers)
Output:
Histogram:
****
*******
*
Explanation:
The function create_histogram() takes a list of integers as input.
For each number in the list, it prints that many asterisks *.
'*' * num creates a string with num number of stars.
Use Cases:
Visual representation of numerical data.
Used in console applications for simple data analysis.
Advantages:
Simple and easy to understand.
Gives a quick visual representation.
Can be modified to show values or labels.
Modified Version (with number labels):
def create_histogram(lst):
print("Histogram:")
for num in lst:
print(f"{num}: {'*' * num}")
# Test list
numbers = [4, 7, 1, 5]
create_histogram(numbers)
Output:
Histogram:
4: ****
7: *******
1: *
5: *****
(ii)Write a python program for transpose of a given matrix.
Definition:
The transpose of a matrix is a new matrix obtained by swapping the rows and columns.
If a matrix is of size m × n, its transpose will be of size n × m.
Example:
Original Matrix:
1 2 3
4 5 6
Transpose:
1 4
2 5
3 6
Python Program Using Nested Loops:
# Function to transpose a matrix
def transpose_matrix(matrix):
rows = len(matrix)
cols = len(matrix[0])
# Creating an empty transpose matrix
transpose = []
for i in range(cols):
row = []
for j in range(rows):
[Link](matrix[j][i]) # Swapping rows with columns
[Link](row)
return transpose
# Original matrix
matrix = [
[1, 2, 3],
[4, 5, 6]
]
# Transpose the matrix
transposed = transpose_matrix(matrix)
# Displaying the result
print("Original Matrix:")
for row in matrix:
print(row)
print("\nTransposed Matrix:")
for row in transposed:
print(row)
Output:
Original Matrix:
[1, 2, 3]
[4, 5, 6]
Transposed Matrix:
[1, 4]
[2, 5]
[3, 6]
Explanation:
The function transpose_matrix() uses two nested loops.
Outer loop iterates through columns.
Inner loop collects the elements from each row at that column index.
These collected values form the transposed matrix.
Alternate Method Using List Comprehension:
matrix = [
[1, 2, 3],
[4, 5, 6]
]
# Transpose using zip() and list comprehension
transpose = [list(row) for row in zip(*matrix)]
# Output
print("Transposed Matrix:")
for row in transpose:
print(row)
9. (i)Write a program to interchange the first and last element in a list.
Definition:
Interchanging the first and last elements of a list means swapping the values at index 0 and index -1.
Example:
Before Swapping:
[10, 20, 30, 40, 50]
After Swapping:
[50, 20, 30, 40, 10]
Python Program:
# Function to swap first and last elements
def swap_first_last(lst):
# Check if list has at least two elements
if len(lst) >= 2:
lst[0], lst[-1] = lst[-1], lst[0] # Swapping using tuple unpacking
return lst
# Example list
numbers = [10, 20, 30, 40, 50]
# Call the function
result = swap_first_last(numbers)
# Display result
print("List after swapping first and last elements:", result)
Output:
List after swapping first and last elements: [50, 20, 30, 40, 10]
Explanation:
lst[0] refers to the first element.
lst[-1] refers to the last element.
We use lst[0], lst[-1] = lst[-1], lst[0] to swap the values directly.
Alternate Version (Using Temporary Variable):
def swap_first_last(lst):
if len(lst) >= 2:
temp = lst[0]
lst[0] = lst[-1]
lst[-1] = temp
return lst
(ii)Write a python program to sort a dictionary by key or value.
Definition:
In Python, a dictionary is an unordered collection of key-value pairs.
We can sort a dictionary either by:
Keys
Values
Sorted dictionaries are often needed for better readability or structured output.
Python Program to Sort by Key and Value:
# Sample dictionary
my_dict = {'banana': 3, 'apple': 5, 'cherry': 2, 'date': 4}
# Sort dictionary by keys
sorted_by_keys = dict(sorted(my_dict.items()))
# Sort dictionary by values
sorted_by_values = dict(sorted(my_dict.items(), key=lambda item: item[1]))
# Display results
print("Original Dictionary:", my_dict)
print("Sorted by Keys:", sorted_by_keys)
print("Sorted by Values:", sorted_by_values)
Output:
Original Dictionary: {'banana': 3, 'apple': 5, 'cherry': 2, 'date': 4}
Sorted by Keys: {'apple': 5, 'banana': 3, 'cherry': 2, 'date': 4}
Sorted by Values: {'cherry': 2, 'banana': 3, 'date': 4, 'apple': 5}
Explanation:
sorted(my_dict.items()) → sorts based on keys (default).
sorted(my_dict.items(), key=lambda item: item[1]) → sorts based on values.
dict() → converts the sorted list of tuples back to a dictionary.
10. . i) How can you determine the size of a set in Python?
Definition of Set:
A set in Python is an unordered collection of unique elements. It is defined using curly braces {} or the
set() function.
Finding the Size of a Set:
To determine how many elements are present in a set, we use the len() function.
Syntax:
len(set_name)
This returns the number of elements in the set.
Example Program:
# Creating a set
fruits = {'apple', 'banana', 'cherry', 'mango'}
# Finding the size of the set
size = len(fruits)
# Display the result
print("The size of the set is:", size)
Output:
The size of the set is: 4
Explanation:
The set fruits contains 4 unique items.
len(fruits) counts these elements and returns 4.
Important Notes:
Duplicate elements are automatically removed in sets.
So even if you try to add duplicates, the size won't increase.
Example:
s = {'a', 'b', 'a', 'c'}
print(len(s)) # Output: 3, not 4
ii) Discuss about calendar program supported by python.
Introduction:
Python provides a built-in module called calendar that allows programmers to perform various calendar-
related operations.
This module can display calendars, handle leap years, get weekday information, and more.
Features of calendar Module:
Displays monthly and yearly calendars.
Checks if a year is leap year or not.
Gets the weekday of a specific date.
Provides text and HTML calendar formats.
Supports custom first day of the week (Monday/Sunday).
How to Import:
import calendar
Commonly Used Functions in calendar:
Function Description
[Link](year, month) Returns a multi-line string of the month's calendar
[Link](year) Returns the full calendar for a year
[Link](year) Returns True if the year is a leap year
Function Description
[Link](start, end) Returns number of leap years between two years
[Link](year, month, day) Returns the weekday (0=Monday, 6=Sunday)
[Link](weekday) Sets the first day of the week (default is Monday)
Example 1: Display Month Calendar
import calendar
# Display calendar for March 2025
print([Link](2025, 3))
Output:
March 2025
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Example 2: Check Leap Year
import calendar
year = 2024
if [Link](year):
print(year, "is a Leap Year")
else:
print(year, "is not a Leap Year")
Example 3: Find Weekday
import calendar
# What day is 26th January 2025?
day = [Link](2025, 1, 26)
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print("26th January 2025 falls on a", days[day])
Output:
26th January 2025 falls on a Sunday
PART – C (15 MARKS)
1. Demonstrate python nested list and give the example programs for matrix addition, subtraction
and multiplication.
What is a Nested List?
A nested list in Python means a list inside another list. It is commonly used to represent matrices or 2D
arrays.
Syntax:
What is a Nested List?
A nested list in Python means a list inside another list. It is commonly used to represent matrices or 2D
arrays.
Syntax:
matrix = [
[1, 2, 3],
[4, 5, 6]
]
Here, matrix[0] is [1, 2, 3], and matrix[1][2] is 6.
Matrix Addition
Formula:
C[i][j] = A[i][j] + B[i][j]
Example Program:
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
# Result matrix
result = [[0, 0], [0, 0]]
# Adding matrices
for i in range(len(A)):
for j in range(len(A[0])):
result[i][j] = A[i][j] + B[i][j]
# Display result
print("Matrix Addition:")
for r in result:
print(r)
Output:
Matrix Addition:
[6, 8]
[10, 12]
Matrix Subtraction
Formula:
C[i][j] = A[i][j] - B[i][j]
Example Program:
A = [[10, 5], [6, 7]]
B = [[3, 2], [1, 4]]
result = [[0, 0], [0, 0]]
# Subtracting matrices
for i in range(len(A)):
for j in range(len(A[0])):
result[i][j] = A[i][j] - B[i][j]
# Display result
print("Matrix Subtraction:")
for r in result:
print(r)
Output:
Matrix Subtraction:
[7, 3]
[5, 3]
Matrix Multiplication
Formula:
C[i][j] = A[i][0]*B[0][j] + A[i][1]*B[1][j] + ...
Example Program:
A = [[1, 2], [3, 4]]
B = [[2, 0], [1, 2]]
result = [[0, 0], [0, 0]]
# Multiplying matrices
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
# Display result
print("Matrix Multiplication:")
for r in result:
print(r)
Output:
Matrix Multiplication:
[4, 4]
[10, 8]
2. a. How can lists, tuples, and dictionaries handle mixed data types? Provide examples for each.
Introduction
In Python, lists, tuples, and dictionaries are versatile data structures.
They can store different data types in a single object, such as strings, integers, floats, booleans, and even
other collections.
1. List with Mixed Data Types
A list is an ordered, mutable (changeable) collection.
Example:
my_list = [10, "apple", 3.14, True, [1, 2]]
Explanation:
10 → Integer
"apple" → String
3.14 → Float
True → Boolean
[1, 2] → Nested list
Accessing Elements:
print(my_list[1]) # Output: apple
2. Tuple with Mixed Data Types
A tuple is an ordered, immutable (unchangeable) collection.
Example:
my_tuple = ("John", 25, 5.8, False)
Explanation:
"John" → String
25 → Integer
5.8 → Float
False → Boolean
Accessing Elements:
print(my_tuple[0]) # Output: John
3. Dictionary with Mixed Data Types
A dictionary is an unordered collection of key-value pairs.
Example:
my_dict = {
"name": "Alice",
"age": 30,
"is_student": False,
"marks": [85, 90, 78],
"info": ("[Link]", 2023)
}
Explanation:
Keys are strings: "name", "age", etc.
Values include string, integer, boolean, list, and tuple.
Accessing Elements:
print(my_dict["marks"]) # Output: [85, 90, 78]
Summary Table
Data Structure Allows Mixed Types Mutable Example
List ✅ Yes ✅ Yes [10, "hi", 3.14]
Tuple ✅ Yes ✅ No ("hi", 20, True)
Dictionary ✅ Yes (in values) ✅ Yes {"a": 1, "b": [2, 3]}
b. Discuss about tuple assignment and write a python program for swapping of two numbers using
tuple assignment.
What is Tuple Assignment?
Tuple assignment in Python is a method that allows multiple variables to be assigned values from a tuple in
a single statement.
It uses a feature called "tuple unpacking".
Syntax:
a, b = value1, value2
Here, a is assigned value1 and b is assigned value2 in one step.
This technique is extremely useful when dealing with swapping values, extracting multiple values from a
tuple, or assigning multiple variables.
Swapping Two Numbers Using Tuple Assignment
In Python, swapping two numbers is simple using tuple assignment. It eliminates the need for a temporary
variable.
Swapping Process:
We can directly assign the values of a and b as follows:
a, b = b, a
This swaps the values of a and b in one line using tuple unpacking.
Python Program for Swapping Two Numbers Using Tuple Assignment
# Initial values
a=5
b = 10
# Swapping using tuple assignment
a, b = b, a
# Display the swapped values
print("After swapping:")
print("a =", a)
print("b =", b)
Output:
After swapping:
a = 10
b=5
Explanation:
Initially, a = 5 and b = 10.
The statement a, b = b, a swaps the values:
o The right side (b, a) creates a tuple (10, 5).
o The left side (a, b) unpacks this tuple and assigns a = 10 and b = 5.
Thus, the values are swapped in a clean, efficient way without needing a temporary variable.
Advantages of Tuple Assignment:
1. Concise and Efficient: Allows swapping or multiple assignments in a single statement.
2. No Temporary Variables: In cases like swapping, there's no need for an additional variable.
3. Readable: The code is easier to understand and maintain.
UNIT- IV- FILES AND EXCEPTION HANDLING
PART A ( 2 Marks)
1. Define a file and give its advantages.
➔ A file is a named location on storage media to store data permanently.
Advantages:
Stores large amounts of data permanently.
Easy to access and modify anytime.
2. Differentiate text file and binary file.
Text File Binary File
Stores data as readable characters. Stores data in binary (0s and 1s).
Can be opened and read easily in text editors. Needs special programs to read and edit.
3. Write the difference between ftell() and fseek().
ftell(): Returns the current file pointer position.
fseek(): Moves the file pointer to a specified location.
4. What is command line argument? Give its purposes.
➔ Arguments passed to a Python script while running it from the command line.
Purpose:
Provides input without hardcoding.
Automates and controls script execution.
5. Name the different modes used in file handling.
➔ Modes are:
'r' (read)
'w' (write)
'a' (append)
'b' (binary)
'+' (read and write)
6. List down some inbuilt exception.
➔ Examples:
ZeroDivisionError
IndexError
TypeError
ValueError
FileNotFoundError
7. What are the distinctions between append and write modes?
Write ('w') mode: Overwrites the file if it exists.
Append ('a') mode: Adds data at the end of the file without deleting existing content.
8. What is exception chaining in python? Provide an example.
➔ Exception chaining links one exception to another using raise ... from ....
Example:
try:
x=1/0
except ZeroDivisionError as e:
raise ValueError("Invalid input") from e
9. How do you define a user-defined exception in Python? Write a basic example.
➔ Create a class inheriting from Exception.
Example:
class MyError(Exception):
pass
raise MyError("This is a user-defined error")
10. What is clean-up actions in exception handling? [BL4] [CO4] [2]
➔ Clean-up actions are tasks performed to release resources (like closing files or database connections)
even if an error occurs.
Done using finally block.
Descriptive Questions ( 13 Marks)
1. How can you read and write data in a file using Python? provide source code
examples for both operations.
File Reading and Writing in Python
In Python, file operations like reading and writing are performed using built-in functions.
The important steps are:
1. Open the file (open() function)
2. Read/Write the file
3. Close the file (close() function)
The open() function syntax is:
open(filename, mode)
filename: Name of the file.
mode: Mode of opening ('r' - read, 'w' - write, 'a' - append, 'b' - binary etc.)
Writing Data to a File (Write Operation)
Source Code:
# Open a file in write mode
file = open("[Link]", "w")
# Write data into the file
[Link]("Hello, this is my first file!\n")
[Link]("Python makes file handling easy.\n")
# Close the file
[Link]()
print("Data written successfully.")
Explanation:
open("[Link]", "w") → Opens (creates if not exist) a file in write mode.
write() → Writes string data to the file.
close() → Safely closes the file after writing.
Note: If [Link] already exists, it will overwrite the old content.
Reading Data from a File (Read Operation)
Source Code:
# Open the file in read mode
file = open("[Link]", "r")
# Read entire content of the file
content = [Link]()
# Print the content
print("The file content is:\n")
print(content)
# Close the file
[Link]()
Explanation:
open("[Link]", "r") → Opens the file for reading.
read() → Reads the entire file data as a single string.
print() → Displays the data on the screen.
close() → Safely closes the file after reading.
Alternative: Using with Statement (Best Practice)
Python provides a better way using with which automatically closes the file:
Writing Example:
with open("[Link]", "w") as file:
[Link]("This is written using with statement.\n")
[Link]("No need to manually close the file.")
Reading Example:
with open("[Link]", "r") as file:
content = [Link]()
print(content)
Advantages of with:
Automatically closes the file.
Cleaner and more readable code.
No need to explicitly call close().
2. What are the ftell() and fseek() methods in file handling? Explain with suitable
examples.
ftell() and fseek() Methods in File Handling
In Python, while working with file objects, sometimes you need to:
Find where you are currently reading/writing inside a file.
Move to a specific position inside the file.
This is where ftell() and fseek() functions come into play.
1. ftell() Method
➔ The ftell() method returns the current position of the file pointer (cursor) from the beginning of the file,
measured in bytes.
Syntax:
file_object.tell()
➔ tell() is the function we use in Python (equivalent of C's ftell()).
Example:
# Open a file in write mode
file = open("[Link]", "w")
[Link]("Hello World")
# Check the current file pointer position
position = [Link]()
print("Current file pointer position:", position)
[Link]()
Output:
Current file pointer position: 11
Explanation:
After writing "Hello World", the pointer moves 11 bytes forward (each character = 1 byte).
tell() returns the current byte position.
2. fseek() Method
➔ In Python, seek() function is used to move the file pointer to a specific position.
Syntax:
file_object.seek(offset, whence)
offset → Number of bytes to move.
whence → Reference point:
o 0 → Beginning of file (default)
o 1 → Current file position
o 2 → End of file
Example:
# Open a file in read mode
file = open("[Link]", "r")
# Move to the 6th byte
[Link](6)
# Read the rest of the file
data = [Link]()
print("Data after seeking:", data)
[Link]()
Output:
Data after seeking: World
Explanation:
seek(6) moves the file pointer after "Hello " (including space).
Reading from there gives "World".
Full Working Program Combining Both
# Create a file and write some data into it
with open("[Link]", "w") as file:
[Link]("Hello World! Welcome to Python file handling.")
# Now open the file for reading
with open("[Link]", "r") as file:
# 1. Find and print the initial pointer position
position = [Link]()
print("Initial Position:", position)
# 2. Read first 5 characters
data = [Link](5)
print("Data read:", data)
# 3. Find and print the pointer position after reading
position = [Link]()
print("Position after reading 5 characters:", position)
# 4. Move the pointer to 13th byte
[Link](13)
print("Position after seeking to 13:", [Link]())
# 5. Read next 7 characters from current position
data = [Link](7)
print("Data after seeking:", data)
# 6. Find final position
position = [Link]()
print("Final Position:", position)
Sample Output:
Initial Position: 0
Data read: Hello
Position after reading 5 characters: 5
Position after seeking to 13: 13
Data after seeking: Welcome
Final Position: 20
3. Write a python program to count the number of words in a given text file.
Python Program to Count Number of Words in a Text File
# Step 1: Open the file in read mode
with open("[Link]", "r") as file:
# Step 2: Read the content of the file
content = [Link]()
# Step 3: Split the content into words
words = [Link]()
# Step 4: Count the number of words
word_count = len(words)
# Step 5: Display the word count
print("Total number of words in the file:", word_count)
Sample Content inside [Link]:
Python is a powerful programming language. It is easy to learn and fun to use.
Sample Output:
Total number of words in the file: 14
Explanation:
Step Action
1 Open the file [Link] in read mode using with (so it closes automatically).
2 Read the whole file content using read().
3 Split the text into words using split() (by default it splits at spaces).
4 Use len() function to count total words.
5 Print the word count result.
Key Points to Score Full Marks:
Using with open(...) → Good coding practice.
Using split() → Correct method to separate words.
Closing file automatically (no close() needed after with).
Output must be printed clearly.
Extra Tip (Optional for High Score):
You can handle exceptions too, like checking if file exists!
Example with exception handling:
try:
with open("[Link]", "r") as file:
content = [Link]()
words = [Link]()
word_count = len(words)
print("Total number of words in the file:", word_count)
except FileNotFoundError:
print("The file does not exist!")
4. Write a python program to copy the contents of one file to another file and
display the contents.
Copy Contents of One File to Another and Display
# Step 1: Open the source file in read mode
with open("[Link]", "r") as source_file:
# Step 2: Read the content of source file
content = source_file.read()
# Step 3: Open the destination file in write mode
with open("[Link]", "w") as destination_file:
# Step 4: Write the content into destination file
destination_file.write(content)
# Step 5: Open the destination file again to display contents
with open("[Link]", "r") as destination_file:
print("Contents of destination file:")
print(destination_file.read())
Suppose your [Link] has this content:
Learning Python is fun.
Practice makes you perfect.
Sample Output:
Contents of destination file:
Learning Python is fun.
Practice makes you perfect.
Explanation:
Step Action
1 Open the source file in read mode.
2 Read the full content of the source file.
3 Open/create a destination file in write mode.
4 Write the read content into the destination file.
5 Open the destination file in read mode and display its contents.
Important Points:
Use with open(...) to handle files properly (auto-closes file).
Always read content first before writing to another file.
Open the destination file again if you want to display its content freshly.
5. Explain the concept of command-line arguments in python and demonstrate
their usage with an example program.
Concept of Command-Line Arguments in Python
Command-line arguments are the inputs given to a Python program when it is run from the
command line (like terminal, command prompt).
These arguments allow the user to pass information directly to the program without modifying the
code.
In Python, the sys module is used to access command-line arguments.
All the arguments are stored in a list called [Link]:
o [Link][0] → Name of the Python script.
o [Link][1] → First argument.
o [Link][2] → Second argument, and so on.
Key Points about [Link]:
It is a list that contains command-line arguments.
The first element ([Link][0]) is always the script name.
The arguments are received as strings (even if you enter numbers).
Example Python Program using Command-Line Arguments
# Import sys module
import sys
# Display the number of command-line arguments
print("Total arguments passed:", len([Link]))
# Display the list of arguments
print("List of arguments:", [Link])
# Access individual arguments
print("Script name:", [Link][0])
# Check if user provided at least two arguments
if len([Link]) > 2:
print("First argument:", [Link][1])
print("Second argument:", [Link][2])
else:
print("Not enough arguments provided!")
How to Run This Program (Command Line Execution)
Suppose you saved this program as demo_args.py.
You can run it like this in your terminal/command prompt:
python demo_args.py apple banana
Sample Output:
Total arguments passed: 3
List of arguments: ['demo_args.py', 'apple', 'banana']
Script name: demo_args.py
First argument: apple
Second argument: banana
Explanation:
Element Meaning
[Link][0] Script name (demo_args.py)
[Link][1] First argument (apple)
[Link][2] Second argument (banana)
Python treats all command-line arguments as strings. If you need numbers, you have to manually convert
them using int() or float().
Advantages of Command-Line Arguments:
Dynamic program behavior without changing code.
Useful in automation, scripting, and batch processing.
Helps pass filenames, numbers, options, etc., at runtime.
6. Discuss syntax errors and exceptions in python, providing examples to illustrate
their differences.
Syntax Errors vs Exceptions in Python
Python errors are mainly divided into two categories:
→ Syntax Errors
→ Exceptions (Runtime Errors)
They are different in when and why they occur.
1. Syntax Errors
➔ Syntax errors occur when you write code that does not follow Python’s rules.
➔ These are detected at compile time, before the program runs.
Example of Syntax Error:
# Missing colon (:) after if condition
if 5 > 2
print("Five is greater than two")
Output:
SyntaxError: expected ':'
Explanation:
Python expects a colon : after if 5 > 2.
Program won't even start until the syntax is corrected.
Other Common Syntax Errors:
Missing parentheses.
Incorrect indentation.
Misspelled keywords.
2. Exceptions (Runtime Errors)
➔ Exceptions occur while the program is running.
➔ Syntax is correct, but some problem happens during execution (like dividing by zero, file not found,
etc.).
Example of Exception:
# Division by zero
a = 10
b=0
print(a / b)
Output:
ZeroDivisionError: division by zero
Explanation:
Syntax is correct.
But during execution, division by zero is mathematically not allowed.
Other Common Exceptions:
ZeroDivisionError
ValueError
FileNotFoundError
IndexError
TypeError
Comparison Table: Syntax Error vs Exception
Feature Syntax Error Exception
When it occurs During compilation During runtime
Reason Code structure is wrong Logical error during execution
Example Missing colon, wrong indentation Division by zero, file not found
Handling Must fix before running Can be handled using try-except block
Example Handling Exception using try-except
try:
a=5
b=0
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero!")
Output:
Cannot divide by zero!
7. What is exception handling in Python, and how does the try-except block work?
provide an example.
What is Exception Handling in Python?
➔ Exception handling is the process of responding to runtime errors (exceptions) gracefully, without
crashing the program.
➔ In Python, we handle exceptions using the try-except block.
Why exception handling?
To avoid program crashes.
To give user-friendly error messages.
To continue running the program even if an error occurs.
How does the try-except block work?
try block: Write the code that may raise an exception inside this block.
except block: Write the code to handle the exception if it occurs.
If no error occurs, except block is skipped.
Basic Syntax of try-except:
try:
# Code that might cause an exception
except ExceptionType:
# Code to handle the exception
Important:
You can have multiple except blocks for different errors.
You can use a generic except to catch all errors.
Example Program of try-except
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Please enter only numbers.")
Sample Outputs:
Case 1: (Normal Input)
Enter a number: 10
Enter another number: 2
Result: 5.0
Case 2: (Division by Zero)
Enter a number: 10
Enter another number: 0
Error: Cannot divide by zero!
Case 3: (Invalid Input)
Enter a number: ten
Error: Please enter only numbers.
Explanation:
Step Action
1 Code inside try block is executed.
2 If an error happens, Python jumps to the matching except block.
3 Error message is shown instead of crashing the program.
4 If no error, program continues normally.
8. Explain about raising exceptions with an example program.
Raising Exceptions in Python
Sometimes, you want to manually raise an error in your program based on a certain condition.
In Python, you can raise exceptions using the raise keyword.
Why raise exceptions?
To stop the program when something wrong happens.
To alert the user with a proper error message.
To maintain correctness and security of the program.
Syntax of Raising an Exception:
raise ExceptionType("Custom error message")
You can raise built-in exceptions like ValueError, TypeError, etc.,
or even create your own user-defined exceptions.
Example Program: Raising Exception
def check_age(age):
if age < 0:
# Raise an exception if age is negative
raise ValueError("Age cannot be negative!")
else:
print("Age is valid:", age)
try:
user_age = int(input("Enter your age: "))
check_age(user_age)
except ValueError as e:
print("Error:", e)
Sample Outputs:
Case 1: Valid Input
yaml
CopyEdit
Enter your age: 25
Age is valid: 25
Case 2: Invalid Input (Negative Age)
Enter your age: -5
Error: Age cannot be negative!
Explanation:
Step Action
1 The check_age function checks if the age is negative.
2 If yes, it raises a ValueError manually with a custom message.
3 The try-except block catches the raised error and prints it nicely.
Thus, the program does not crash, and user gets a meaningful error message.
Important Points about raise:
You must specify the type of Exception you want to raise.
You can also create custom exceptions using classes.
raise immediately stops the normal flow of the program and jumps to except block.
Conclusion:
Raising exceptions helps to control the flow of programs when unexpected conditions occur.
It improves program reliability, readability, and debugging.
9. Discuss about various operations performed in a file by giving examples.
File Operations in Python
In Python, files are used to store data. File handling operations in Python are performed using the open()
function and different file methods. You can read, write, and perform other operations on files like closing
them, appending, or even renaming them.
Basic File Operations in Python
1. Opening a File
o The open() function is used to open a file in various modes:
'r' → Read mode (default, if not specified)
'w' → Write mode
'a' → Append mode
'rb' → Read mode in binary
'wb' → Write mode in binary
'x' → Exclusive creation (fails if the file exists)
Syntax:
file = open("[Link]", "mode")
2. Reading from a File
o You can read the contents of a file using the following methods:
read(): Reads the entire file content.
readline(): Reads one line at a time.
readlines(): Returns a list of lines.
Example:
with open("[Link]", "r") as file:
content = [Link]()
print(content)
3. Writing to a File
o To write to a file, you can use the write() or writelines() methods.
o write() writes a string to the file.
o writelines() writes a list of strings.
Example:
with open("[Link]", "w") as file:
[Link]("Hello, Python!\nWelcome to File Handling.")
4. Appending to a File
o Use the a mode to add content to the end of the file without overwriting the existing content.
Example:
with open("[Link]", "a") as file:
[Link]("\nAdding this new line to the file.")
5. Closing a File
o After performing any operation on a file, it's important to close the file using the close()
method.
o If you use with open(), the file is automatically closed after the block of code is executed.
Example:
file = open("[Link]", "r")
content = [Link]()
[Link]() # Closing the file
6. Renaming a File
o You can rename a file using the [Link]() method.
Example:
import os
[Link]("[Link]", "[Link]")
7. Removing a File
o The [Link]() method allows you to delete a file.
Example:
import os
[Link]("[Link]")
8. File Seeking (Moving the File Pointer)
o You can use the seek() method to move the file pointer to a specific position.
Example:
with open("[Link]", "r") as file:
[Link](10) # Move to the 10th byte
print([Link]()) # Read from that position onward
9. File Positioning (tell)
o You can use the tell() method to get the current position of the file pointer.
Example:
with open("[Link]", "r") as file:
[Link](5) # Read first 5 characters
print([Link]()) # Prints the current position of the file pointer
10. Checking if a File Exists
o Use [Link]() to check whether a file exists.
Example:
import os
if [Link]("[Link]"):
print("File exists")
else:
print("File does not exist")
Example of Multiple File Operations
import os
# Create a file and write some text
with open("[Link]", "w") as file:
[Link]("Python file handling example.\n")
[Link]("This is a second line.\n")
# Append to the file
with open("[Link]", "a") as file:
[Link]("This is an appended line.")
# Read and display the content of the file
with open("[Link]", "r") as file:
content = [Link]()
print(content)
# Get the current position of the file pointer
with open("[Link]", "r") as file:
print("Current position:", [Link]())
[Link](10)
print("New position after reading 10 characters:", [Link]())
# Rename the file
[Link]("[Link]", "renamed_sample.txt")
Sample Output:
Python file handling example.
This is a second line.
This is an appended line.
Current position: 0
New position after reading 10 characters: 10
10. Explain about exception chaining in python with an example program.
Exception Chaining in Python
Exception Chaining refers to the process of propagating an original exception while raising a new
exception. This allows you to raise a new exception and preserve the context of the original exception. It
helps to provide additional information or a custom message while maintaining the original traceback.
In Python, exception chaining is done using the raise keyword in the except block with the from keyword.
Syntax for Exception Chaining:
try:
# Some code that may raise an exception
except SomeException as e:
raise NewException("Custom error message") from e
from e allows the original exception (e) to be associated with the new exception, which makes it
easier to debug by tracking the sequence of exceptions.
Example Program Demonstrating Exception Chaining
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError as e:
raise ValueError("Custom error: Division by zero is not allowed!") from e
except TypeError as e:
raise ValueError("Custom error: Both inputs should be numbers!") from e
return result
try:
print(divide_numbers(10, 0)) # This will raise a ZeroDivisionError
except ValueError as e:
print("Error caught:", e)
print("Original exception:", e.__cause__) # Shows the original exception (ZeroDivisionError)
Explanation of Code:
1. divide_numbers() function:
o Attempts to divide two numbers.
o If a ZeroDivisionError or TypeError occurs, a new ValueError is raised with a custom
message, and the original exception is chained to it using from e.
2. In the try-except block:
o The ValueError is caught, and the original exception (like ZeroDivisionError) is accessed
using the __cause__ attribute.
Sample Output:
Error caught: Custom error: Division by zero is not allowed!
Original exception: division by zero
Explanation of Output:
When a ZeroDivisionError occurs, the ValueError is raised with a custom message.
The original exception (ZeroDivisionError) is chained and can be accessed via e.__cause__.
Why Use Exception Chaining?
Improved Error Debugging: It helps in maintaining the traceback and context of the original
exception, making debugging easier.
Custom Error Messages: You can raise a new exception with a custom error message while
preserving the original exception's details.
Clearer Exception Handling: It makes it easier to differentiate between different errors and take
appropriate action.
Part – C (15 marks)
1. Discuss the python codes to print try, except and finally block
statements.
Understanding Try, Except, and Finally in Python
In Python, exception handling is done using the try, except, and finally blocks. These blocks allow you to
handle errors gracefully and ensure that certain code always runs, regardless of whether an exception
occurred.
Syntax of Try, Except, and Finally:
try:
# Code that might raise an exception
except SomeException as e:
# Code to handle the exception
finally:
# Code that will always run (used for cleanup actions)
Explanation of Each Block:
1. try Block:
o This block contains the code that may raise an exception.
o If no exception occurs, the program executes the code normally.
2. except Block:
o This block is executed if an exception occurs in the try block.
o You can specify different exception types to handle different errors.
3. finally Block:
o This block contains code that will always run, whether an exception occurs or not.
o It is typically used for cleanup actions, like closing files or releasing resources.
Example Program Demonstrating Try, Except, and Finally
def division(a, b):
try:
print("Trying to divide", a, "by", b)
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except TypeError:
print("Error: Both inputs should be numbers!")
finally:
print("This block always runs, regardless of an exception.")
# Example 1: Normal division
print("Example 1:")
division(10, 2)
# Example 2: Division by zero
print("\nExample 2:")
division(10, 0)
# Example 3: Invalid input (string instead of number)
print("\nExample 3:")
division(10, "a")
Explanation of Code:
try Block:
o Tries to divide a by b. If b is zero, a ZeroDivisionError occurs.
o If a or b is not a number, a TypeError will occur.
except Blocks:
o If a ZeroDivisionError occurs, it will print a specific error message.
o If a TypeError occurs, it will print a different error message.
finally Block:
o This block will always run after the try and except blocks, regardless of whether an exception
occurred or not. It's used here to print a cleanup message.
Sample Output:
Example 1:
Trying to divide 10 by 2
This block always runs, regardless of an exception.
Example 2:
Trying to divide 10 by 0
Error: Cannot divide by zero!
This block always runs, regardless of an exception.
Example 3:
Trying to divide 10 by a
Error: Both inputs should be numbers!
This block always runs, regardless of an exception.
Explanation of Output:
1. In Example 1, the division works fine, and the finally block is executed after the division.
2. In Example 2, since we're dividing by zero, a ZeroDivisionError is caught, and the finally block is
executed after the error message is printed.
3. In Example 3, a TypeError occurs (since we're dividing a number by a string), and the finally block
is executed after the error message.
Key Points:
The finally block is guaranteed to run, even if an exception occurs.
You can have multiple except blocks for different types of exceptions.
If no exception occurs, both try and finally will execute, and the except block will be skipped.
2. Write a python program that prompts the user to enter an integer and raises a ValueError if the
input is not a valid integer.
Python program that prompts the user to enter an integer and raises a ValueError if the input is not a valid
integer:
def get_integer_input():
try:
# Prompt user for input
user_input = input("Please enter an integer: ")
# Try converting input to an integer
number = int(user_input)
print(f"You entered the integer: {number}")
except ValueError:
# Raise ValueError if input is not a valid integer
print("Error: The input is not a valid integer!")
raise ValueError("Invalid input: Please enter a valid integer.")
# Call the function to get user input
get_integer_input()
Explanation:
1. The input() function prompts the user to enter a value.
2. The int() function tries to convert the entered value to an integer.
o If the conversion is successful, it prints the integer.
3. If the input cannot be converted to an integer (e.g., the user enters a string), a ValueError is raised,
and an error message is displayed.
4. The raise ValueError() explicitly raises a ValueError if the input is invalid.
Sample Output:
Valid Input:
Please enter an integer: 42
You entered the integer: 42
Invalid Input (String):
Please enter an integer: hello
Error: The input is not a valid integer!
Traceback (most recent call last):
File "[Link]", line 12, in <module>
get_integer_input()
File "[Link]", line 8, in get_integer_input
raise ValueError("Invalid input: Please enter a valid integer.")
ValueError: Invalid input: Please enter a valid integer.
3. Write a python program that reads a file and handles a FileNotFoundError if the file does not exist.
Python program that reads a file and handles a FileNotFoundError if the file does not exist:
def read_file(filename):
try:
# Try to open and read the file
with open(filename, 'r') as file:
content = [Link]()
print("File content:\n", content)
except FileNotFoundError:
# Handle the case where the file does not exist
print(f"Error: The file '{filename}' does not exist!")
raise FileNotFoundError(f"The file '{filename}' was not found.")
# Ask the user for the file name
file_name = input("Please enter the file name to read: ")
read_file(file_name)
Explanation:
1. The function read_file(filename) tries to open the specified file in read mode ('r').
2. If the file exists, the content is read and printed.
3. If the file doesn't exist, a FileNotFoundError is raised, and an appropriate error message is
displayed.
Sample Output:
Case 1: File exists:
Please enter the file name to read: [Link]
File content:
This is an example file.
Here is some content in it.
Case 2: File does not exist:
Please enter the file name to read: non_existing_file.txt
Error: The file 'non_existing_file.txt' does not exist!
Traceback (most recent call last):
File "[Link]", line 15, in <module>
read_file(file_name)
File "[Link]", line 9, in read_file
raise FileNotFoundError(f"The file '{filename}' was not found.")
FileNotFoundError: The file 'non_existing_file.txt' was not found.
Explanation of the Output:
Case 1: The file exists, so the program reads and prints its content.
Case 2: The file does not exist, so a FileNotFoundError is raised, and an error message is displayed.
4. Write a Python program that attempts to access an index in a list and handles an IndexError
exception if the index is out of range.
Python program that attempts to access an index in a list and handles an IndexError exception if the index
is out of range:
def access_list_element(my_list, index):
try:
# Try to access the element at the specified index
element = my_list[index]
print(f"The element at index {index} is: {element}")
except IndexError:
# Handle the case where the index is out of range
print(f"Error: Index {index} is out of range for the list!")
raise IndexError(f"Index {index} is out of range for the list.")
# Sample list
sample_list = [10, 20, 30, 40, 50]
# Ask the user for an index
index = int(input("Enter the index to access: "))
access_list_element(sample_list, index)
Explanation:
1. access_list_element() function takes a list and an index as input.
2. The program attempts to access the element at the specified index.
3. If the index is valid, it prints the element at that index.
4. If the index is out of range (i.e., greater than the list length), an IndexError is raised, and an error
message is displayed.
Sample Output:
Case 1: Valid Index
Enter the index to access: 2
The element at index 2 is: 30
Case 2: Invalid Index (Out of Range)
Enter the index to access: 7
Error: Index 7 is out of range for the list!
Traceback (most recent call last):
File "[Link]", line 14, in <module>
access_list_element(sample_list, index)
File "[Link]", line 7, in access_list_element
raise IndexError(f"Index {index} is out of range for the list.")
IndexError: Index 7 is out of range for the list.
Explanation of the Output:
Case 1: When a valid index (e.g., 2) is entered, it correctly displays the element at that index.
Case 2: When an invalid index (e.g., 7) is entered, an IndexError is raised, and an error message is
displayed.
UNIT- V PACKAGES & GUI
PART A ( 2 Marks)
1. Write about packages in Python.
Packages in Python are directories that contain multiple modules (Python files). A package must contain a special file
named __init__.py to be recognized as a package. Packages help in organizing related modules together and promote
code reusability.
2. Define NumPy and give its features.
NumPy (Numerical Python) is a library used for numerical computations in Python.
Features:
Supports multi-dimensional arrays (ndarrays)
Fast mathematical operations
Functions for linear algebra, Fourier transforms, and random numbers
3. What function is used in Matplotlib to plot a basic line graph? Provide an example.
The function plot() is used to draw a line graph in Matplotlib.
Example:
import [Link] as plt
[Link]([1, 2, 3], [4, 5, 1])
[Link]()
4. Write about pandas in Python.
Pandas is a Python library used for data manipulation and analysis. It provides two main data structures: Series (1D)
and DataFrame (2D). It helps in handling large data sets efficiently.
5. Which Python library is commonly used for creating GUI applications?
Tkinter is the standard Python library used for creating GUI (Graphical User Interface) applications. It provides
various widgets like buttons, labels, and text boxes.
6. Write a simple code snippet to create and display a bar chart using Matplotlib.
import [Link] as plt
x = ['A', 'B', 'C']
y = [10, 20, 15]
[Link](x, y)
[Link]()
7. Name any four Tkinter widgets and their purposes.
Label – Displays text
Button – Triggers an action
Entry – Accepts user input
Text – Multi-line text input area
8. Write about Matplotlib.
Matplotlib is a data visualization library in Python. It allows users to create static, animated, and interactive plots such
as line charts, bar charts, scatter plots, and histograms.
9. What is the purpose of the mainloop() method in Tkinter?
The mainloop() method starts the GUI event loop. It waits for user actions like clicks or key presses and updates the
GUI accordingly.
10. Define Tkinter programming.
Tkinter programming is the use of the Tkinter library in Python to create GUI applications. It includes creating
windows, adding widgets, and handling user events.
DESCRIPTIVE QUESTIONS ( 13 MARKS)
1. Explain the use of built-in functions from the Matplotlib package and write a Python program to create a
simple line graph plot.
Introduction to Matplotlib:
Matplotlib is a powerful data visualization library in Python used to create static, animated, and interactive plots. It
is especially useful in presenting data through various graphical formats like line charts, bar charts, histograms,
scatter plots, and more.
Key Built-in Functions in Matplotlib:
Matplotlib has a module called pyplot which is commonly used. Below are some important built-in functions from the
[Link] module:
Function Description
plot() Draws a line graph based on x and y values.
xlabel() Adds a label to the x-axis.
ylabel() Adds a label to the y-axis.
title() Adds a title to the graph.
grid() Displays grid lines on the graph.
legend() Shows the legend when multiple plots are used.
show() Displays the final output graph window.
figure() Creates a new figure for plotting multiple graphs.
bar() Used to create bar charts.
hist() Creates histogram plots.
scatter() Plots a scatter plot using x and y coordinates.
Python Program to Create a Simple Line Graph:
# Import the pyplot module from matplotlib
import [Link] as plt
# Define x and y coordinates
x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 8, 7]
# Create a line plot
[Link](x, y, color='blue', marker='o', linestyle='--', label='Data Line')
# Add labels and title
[Link]('X-axis')
[Link]('Y-axis')
[Link]('Simple Line Graph')
# Add grid and legend
[Link](True)
[Link]()
# Show the graph
[Link]()
Explanation of the Code:
[Link]() – plots a line graph connecting points (x, y).
color='blue', marker='o', linestyle='--' – optional arguments to customize the graph.
xlabel() and ylabel() – label the axes.
title() – gives the graph a heading.
grid(True) – displays background grid lines.
legend() – shows the label in the graph.
show() – displays the final graphical output.
Y-axis
^
| o
| o -- Dashed line connects all points
| o
|
|
| o
|
| o
+---------------------------------> X-axis
1 2 3 4 5
2. Write a Python program to create and manipulate a NumPy array with mathematical operations.
Introduction to NumPy:
NumPy (Numerical Python) is a powerful Python library used for numerical computing. It provides support for
multi-dimensional arrays and many mathematical functions to operate on arrays efficiently.
Features of NumPy:
Fast and memory-efficient operations
Vectorized computations (no need for loops)
Supports broadcasting
Provides functions for linear algebra, statistical operations, and more
Python Program to Create and Manipulate a NumPy Array:
import numpy as np
# Creating a 1D NumPy array
arr = [Link]([10, 20, 30, 40, 50])
print("Original Array:", arr)
# Basic Mathematical Operations
print("Array + 5:", arr + 5) # Add 5 to each element
print("Array * 2:", arr * 2) # Multiply each element by 2
print("Array squared:", arr ** 2) # Square of each element
# Statistical operations
print("Sum of elements:", [Link](arr))
print("Mean of array:", [Link](arr))
print("Max value:", [Link](arr))
print("Min value:", [Link](arr))
# Create a 2D NumPy array
arr2 = [Link]([[1, 2], [3, 4]])
print("2D Array:\n", arr2)
# Matrix multiplication
result = [Link](arr2, arr2)
print("Matrix multiplication result:\n", result)
# Transpose of the array
print("Transpose of 2D array:\n", [Link](arr2))
Explanation of the Code:
[Link](): Creates NumPy arrays (1D and 2D).
arr + 5: Adds 5 to every element (vectorized operation).
arr * 2: Multiplies every element by 2.
arr ** 2: Squares every element in the array.
[Link]() / [Link](): Performs statistical calculations.
[Link](): Used for matrix multiplication.
[Link](): Transposes rows and columns in a 2D array.
Sample Output:
Original Array: [10 20 30 40 50]
Array + 5: [15 25 35 45 55]
Array * 2: [ 20 40 60 80 100]
Array squared: [ 100 400 900 1600 2500]
Sum of elements: 150
Mean of array: 30.0
Max value: 50
Min value: 10
2D Array:
[[1 2]
[3 4]]
Matrix multiplication result:
[[ 7 10]
[15 22]]
Transpose of 2D array:
[[1 3]
[2 4]]
3. Write a Python program to create a Pandas DataFrame using a 2D list and perform basic data
manipulations.
Introduction to Pandas:
Pandas is a powerful data analysis and manipulation library in Python. It provides two primary data structures:
Series – one-dimensional labeled array
DataFrame – two-dimensional labeled table (like Excel)
A DataFrame is similar to a table with rows and columns.
Python Program: Create DataFrame from a 2D list and manipulate it
import pandas as pd
# Step 1: Create a 2D list
data = [
[101, 'Alice', 85],
[102, 'Bob', 90],
[103, 'Charlie', 78],
[104, 'David', 92]
]
# Step 2: Define column names
columns = ['ID', 'Name', 'Marks']
# Step 3: Create DataFrame
df = [Link](data, columns=columns)
print("Original DataFrame:")
print(df)
# Step 4: Add a new column
df['Grade'] = ['B', 'A', 'C', 'A']
print("\nDataFrame after adding 'Grade' column:")
print(df)
# Step 5: Filter students with Marks > 80
high_scorers = df[df['Marks'] > 80]
print("\nStudents with Marks > 80:")
print(high_scorers)
# Step 6: Update a value
[Link][df['Name'] == 'Charlie', 'Marks'] = 88
print("\nDataFrame after updating Charlie's marks:")
print(df)
# Step 7: Sort by Marks
sorted_df = df.sort_values(by='Marks', ascending=False)
print("\nDataFrame sorted by Marks (descending):")
print(sorted_df)
Explanation of Code:
[Link]() – creates the DataFrame using a 2D list and column names
df['Grade'] = ... – adds a new column
df[df['Marks'] > 80] – filters rows using a condition
[Link][...] = ... – updates a specific value
sort_values() – sorts the DataFrame based on a column
Sample Output:
Original DataFrame:
ID Name Marks
0 101 Alice 85
1 102 Bob 90
2 103 Charlie 78
3 104 David 92
DataFrame after adding 'Grade' column:
ID Name Marks Grade
0 101 Alice 85 B
1 102 Bob 90 A
2 103 Charlie 78 C
3 104 David 92 A
Students with Marks > 80:
ID Name Marks Grade
0 101 Alice 85 B
1 102 Bob 90 A
3 104 David 92 A
DataFrame after updating Charlie's marks:
ID Name Marks Grade
0 101 Alice 85 B
1 102 Bob 90 A
2 103 Charlie 88 C
3 104 David 92 A
DataFrame sorted by Marks (descending):
ID Name Marks Grade
3 104 David 92 A
1 102 Bob 90 A
2 103 Charlie 88 C
0 101 Alice 85 B
4. Explain the use of Matplotlib, write a Python program for plotting a histogram using Matplotlib.
Introduction to Matplotlib:
Matplotlib is a widely used Python library for creating visualizations like line charts, bar graphs, scatter plots,
histograms, pie charts, and more.
It helps in visualizing large data sets in an understandable and insightful way.
The commonly used module in Matplotlib is [Link], which provides simple functions to plot different types
of graphs.
Uses of Matplotlib:
To plot line charts, bar charts, and histograms
To analyze trends and patterns in data
To visualize scientific and statistical results
Supports labels, legends, grids, and multiple plots
Works well with NumPy and Pandas
Histogram:
A histogram is used to represent the distribution of numerical data. It shows how data is grouped into bins or
intervals.
Python Program to Plot a Histogram Using Matplotlib:
import [Link] as plt
# Sample data
marks = [55, 67, 78, 90, 45, 62, 73, 80, 85, 50, 65, 70, 88, 92, 60]
# Create histogram
[Link](marks, bins=5, color='skyblue', edgecolor='black')
# Add title and axis labels
[Link]("Student Marks Distribution")
[Link]("Marks Range")
[Link]("Number of Students")
# Show the plot
[Link]()
Explanation of Code:
[Link]() – creates the histogram
o marks – data to be plotted
o bins=5 – divides the range into 5 intervals
o color and edgecolor – improve readability
title(), xlabel(), ylabel() – add context to the graph
show() – displays the histogram
Sample Output (Graph Description):
X-axis: Ranges of marks (e.g., 40–55, 56–70, etc.)
Y-axis: Number of students in each range
Each bar shows how many students fall in that range
A light blue histogram with black edges is displayed
5. Explain the uses of Pandas and mention the data structures supported by Pandas.
Introduction to Pandas:
Pandas is a popular Python library used for data analysis and manipulation. It provides flexible and easy-to-use
data structures for handling structured data like tables, time series, and labeled datasets.
Pandas is built on top of NumPy, and integrates well with Matplotlib, SciPy, and other data science tools.
Uses of Pandas:
Use Case Description
Data Cleaning Handle missing data, filter rows, drop duplicates
Use Case Description
Data Transformation Modify data (add/remove columns, apply functions)
Data Analysis Grouping, aggregation, statistics
Data Import/Export Read from or write to CSV, Excel, SQL, JSON, etc.
Data Visualization Simple plotting using .plot()
Handling Time Series Date/time indexing, resampling, time-shifted data
Example Uses:
Reading data from a CSV file: pd.read_csv("[Link]")
Displaying top 5 rows: [Link]()
Filtering rows: df[df['age'] > 30]
Calculating average: df['marks'].mean()
Data Structures Supported by Pandas:
Pandas supports two core data structures:
1. Series:
A one-dimensional labeled array
Can store any data type (int, float, string, etc.)
Similar to a single column in a spreadsheet
Example:
import pandas as pd
s = [Link]([10, 20, 30, 40])
2. DataFrame:
A two-dimensional labeled data structure (rows and columns)
Similar to an Excel sheet or SQL table
Most commonly used structure in Pandas
Example:
data = {'Name': ['Alice', 'Bob'], 'Marks': [85, 90]}
df = [Link](data)
Difference Between Series and DataFrame:
Feature Series DataFrame
Dimension 1D 2D
Structure Single column Rows and columns
Example Student marks Student details (name, marks, ID)
6. What is Tkinter in Python? Explain its importance in GUI programming with an example.
What is Tkinter?
Tkinter is the standard GUI (Graphical User Interface) library for Python.
It provides tools to create windows, buttons, text fields, menus, and other GUI components in desktop applications.
Tkinter is built on the Tcl/Tk GUI toolkit and comes pre-installed with Python, so no extra installation is required.
Importance of Tkinter in GUI Programming:
Feature Description
Ease of Use Beginner-friendly and simple syntax
Cross-platform Works on Windows, Linux, and macOS
Rich Widgets Provides buttons, labels, entries, frames, menus, etc.
Customizable GUI layout, font, color, and size can be modified easily
Event-driven Responds to user actions like clicks, inputs, etc.
Feature Description
Educational Use Widely used to teach GUI basics in Python
Common Tkinter Widgets:
Label – Display text
Button – Clickable button
Entry – Single-line text input
Text – Multi-line text box
Frame – Container for grouping widgets
Canvas – Drawing shapes and images
Example Program Using Tkinter:
import tkinter as tk
# Create the main window
window = [Link]()
[Link]("Simple GUI Example")
[Link]("300x200")
# Create a label
label = [Link](window, text="Welcome to Tkinter!", font=("Arial", 14))
[Link](pady=10)
# Create a button
def say_hello():
[Link](text="Hello, Python GUI!")
button = [Link](window, text="Click Me", command=say_hello)
[Link](pady=10)
# Start the GUI event loop
[Link]()
Explanation of Code:
[Link]() – Initializes the main window
Label() – Displays a message
Button() – Creates a button and links it to a function (say_hello)
pack() – Layout manager to place widgets
mainloop() – Keeps the window open and listens for user actions
Output (GUI Window):
A window titled “Simple GUI Example”
A label saying “Welcome to Tkinter!”
A button labeled “Click Me”
When clicked, the label changes to “Hello, Python GUI!”
7. Write a Python program using Tkinter to create a Student Mark Sheet GUI application.
Objective:
To create a GUI application using Tkinter that allows a user to enter a student's name, roll number, and marks in three
subjects. The program calculates and displays the total, average, and result (Pass/Fail).
Python Program:
import tkinter as tk
def calculate():
try:
m1 = float(entry_mark1.get())
m2 = float(entry_mark2.get())
m3 = float(entry_mark3.get())
total = m1 + m2 + m3
avg = total / 3
result = "Pass" if m1 >= 35 and m2 >= 35 and m3 >= 35 else "Fail"
label_total.config(text=f"Total: {total}")
label_avg.config(text=f"Average: {avg:.2f}")
label_result.config(text=f"Result: {result}")
except ValueError:
label_result.config(text="Please enter valid marks!")
# Main window
window = [Link]()
[Link]("Student Mark Sheet")
[Link]("350x350")
# Labels and Entry Widgets
[Link](window, text="Student Name").pack()
entry_name = [Link](window)
entry_name.pack()
[Link](window, text="Roll Number").pack()
entry_roll = [Link](window)
entry_roll.pack()
[Link](window, text="Mark 1").pack()
entry_mark1 = [Link](window)
entry_mark1.pack()
[Link](window, text="Mark 2").pack()
entry_mark2 = [Link](window)
entry_mark2.pack()
[Link](window, text="Mark 3").pack()
entry_mark3 = [Link](window)
entry_mark3.pack()
# Button to calculate result
[Link](window, text="Calculate", command=calculate).pack(pady=10)
# Output Labels
label_total = [Link](window, text="Total: ")
label_total.pack()
label_avg = [Link](window, text="Average: ")
label_avg.pack()
label_result = [Link](window, text="Result: ")
label_result.pack()
# Run the window
[Link]()
Explanation of the Program:
The program uses Tkinter widgets like Label, Entry, and Button.
calculate() is a function that:
o Fetches the entered marks
o Calculates total and average
o Displays "Pass" if all marks are ≥ 35; otherwise "Fail"
.pack() is used to arrange widgets vertically.
mainloop() keeps the GUI window running.
Output:
A GUI form appears where the user can enter:
o Student Name
o Roll Number
o 3 Subject Marks
On clicking "Calculate", it displays:
o Total Marks
o Average Marks
o Result (Pass/Fail)
8. Explain about packages and their advantages with an example.
What is a Package in Python?
In Python, a package is a collection of modules (files containing Python code) organized in a directory hierarchy.
Packages allow you to organize related modules into a folder structure, making the codebase cleaner, more
manageable, and reusable.
A module is a single file of Python code, while a package is a directory that can contain multiple modules and sub-
packages.
Advantages of Using Packages:
Advantage Explanation
Code Organization Packages help to organize large codebases into smaller, manageable modules.
Reusability Once a package is created, it can be reused across multiple projects without modification.
Namespace Packages help avoid naming conflicts by grouping related modules under a common
Management namespace.
Packages can be extended by adding new modules, making the code scalable and easier to
Scalability
maintain.
Namespace Control With packages, you can control the scope of your module's functions and classes.
Improved Teams can work on different parts of a project in separate packages, making collaboration
Collaboration easier.
Structure of a Package:
A package is typically represented as a directory with an __init__.py file (which makes Python treat the directory as a
package). It can contain modules and sub-packages.
Example structure:
markdown
CopyEdit
my_package/
│
├── __init__.py
├── [Link]
├── [Link]
└── sub_package/
├── __init__.py
└── sub_module.py
Example: Creating and Using a Package
Let's create a simple package that contains two modules: math_operations.py and string_operations.py.
1. Create the Package Structure:
my_package/
│
├── __init__.py
├── math_operations.py
└── string_operations.py
2. Code for math_operations.py:
# math_operations.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
3. Code for string_operations.py:
# string_operations.py
def concatenate(str1, str2):
return str1 + str2
def reverse_string(s):
return s[::-1]
4. Using the Package in Main Program:
# [Link]
from my_package import math_operations, string_operations
# Using math_operations module
sum_result = math_operations.add(10, 5)
print(f"Sum: {sum_result}")
# Using string_operations module
concatenated_result = string_operations.concatenate("Hello", " World")
print(f"Concatenated String: {concatenated_result}")
Explanation of the Code:
my_package/ is the directory that contains the package.
__init__.py makes Python treat the directory as a package (can be empty or contain initialization code).
math_operations.py and string_operations.py are the modules that are part of the package.
The [Link] file demonstrates how to import and use functions from the package using from my_package
import module_name.
Sample Output:
Sum: 15
Concatenated String: Hello World
9. Discuss NumPy features and usages with an example.
What is NumPy?
NumPy (Numerical Python) is an open-source library used for numerical computing in Python. It provides support
for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these
arrays. NumPy is widely used in data science, machine learning, scientific computing, and engineering for high-
performance operations on data.
Features of NumPy:
Feature Explanation
Feature Explanation
NumPy provides a powerful ndarray object for multi-dimensional arrays, which is more
Efficient Array Objects
efficient than Python’s native list or tuple.
Supports element-wise operations (e.g., addition, multiplication) on entire arrays without
Vectorized Operations
using explicit loops, making operations faster and more concise.
Mathematical Provides a wide range of mathematical operations, such as linear algebra, Fourier
Functions transform, and statistical functions.
Allows NumPy arrays of different shapes to work together in operations (e.g., adding a
Broadcasting
scalar to all elements of an array).
Integration with Other Can be integrated with libraries like Pandas, SciPy, and Matplotlib for data analysis,
Libraries statistical operations, and visualization.
NumPy arrays take up less memory compared to standard Python lists, as the data is stored
Memory Efficiency
in contiguous blocks of memory.
Random Number NumPy has a sub-module ([Link]) that is used for generating random numbers and
Generation performing random sampling.
Usage of NumPy:
1. Creating Arrays:
NumPy arrays can be created from Python lists, or using built-in functions like [Link](), [Link](), and [Link]().
import numpy as np
# Create a 1D array from a list
arr = [Link]([1, 2, 3, 4])
print("1D Array:", arr)
# Create a 2D array using a list of lists
arr_2d = [Link]([[1, 2, 3], [4, 5, 6]])
print("2D Array:")
print(arr_2d)
# Create an array of zeros
zeros = [Link]((3, 3))
print("3x3 Zeros Array:")
print(zeros)
# Create an array of ones
ones = [Link]((2, 4))
print("2x4 Ones Array:")
print(ones)
2. Array Operations:
NumPy supports element-wise arithmetic and mathematical operations on arrays.
# Array addition
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
result = arr1 + arr2
print("Addition:", result)
# Array multiplication
result = arr1 * arr2
print("Multiplication:", result)
# Element-wise square root
result = [Link](arr1)
print("Square Root:", result)
3. Indexing and Slicing:
You can access or modify elements in a NumPy array using indexing and slicing techniques.
# Accessing an element
print("Element at index 1:", arr[1])
# Slicing the array (Get first two elements)
print("Sliced Array:", arr[:2])
4. Statistical Operations:
NumPy provides functions for computing basic statistics.
python
CopyEdit
# Mean, median, standard deviation
print("Mean:", [Link](arr))
print("Median:", [Link](arr))
print("Standard Deviation:", [Link](arr))
5. Reshaping and Resizing:
NumPy arrays can be reshaped without changing their data.
# Reshaping an array
reshaped = arr_2d.reshape((3, 2))
print("Reshaped Array:")
print(reshaped)
6. Matrix Operations:
NumPy has built-in functions for performing matrix operations such as dot product, matrix multiplication, etc.
# Matrix multiplication (dot product)
matrix1 = [Link]([[1, 2], [3, 4]])
matrix2 = [Link]([[5, 6], [7, 8]])
dot_product = [Link](matrix1, matrix2)
print("Matrix Dot Product:")
print(dot_product)
Example Program:
Let's create a simple NumPy-based program that calculates the total sales for each product in a store based on the
quantity sold and price, and displays the results.
import numpy as np
# Data: quantity sold and price per unit for 3 products
quantities = [Link]([50, 30, 70]) # Quantities sold
prices = [Link]([20, 15, 10]) # Price per unit
# Calculate total sales for each product
total_sales = quantities * prices
print("Total Sales for Each Product:", total_sales)
# Calculate the total sales for all products
total_sales_sum = [Link](total_sales)
print("Total Sales for All Products:", total_sales_sum)
# Calculate the average sales
average_sales = [Link](total_sales)
print("Average Sales:", average_sales)
Output:
Total Sales for Each Product: [1000 450 700]
Total Sales for All Products: 2150
Average Sales: 716.6666666666666
10. Explain the use of built-in functions from the Matplotlib package and write a Python program to create a
simple pie chart.
What is Matplotlib?
Matplotlib is a widely-used library in Python for creating static, animated, and interactive visualizations. It
provides tools for generating a variety of plots, such as line charts, bar charts, histograms, pie charts, and more. The
most commonly used module in Matplotlib is pyplot, which provides simple plotting functionality.
Built-in Functions in Matplotlib:
Here are some important built-in functions available in Matplotlib, specifically from the [Link] module:
Function Description
plot() Used to plot data on a 2D line graph.
scatter() Used to create a scatter plot of data points.
bar() Used to create a bar chart.
hist() Used to create a histogram to display the distribution of data.
pie() Creates a pie chart to represent proportions of a whole.
show() Displays the plot on the screen.
title() Sets the title of the plot.
xlabel() Sets the label for the x-axis.
ylabel() Sets the label for the y-axis.
legend() Adds a legend to the plot.
xlim() / ylim() Sets the limits for the x-axis and y-axis.
grid() Displays grid lines on the plot.
Creating a Pie Chart:
The pie() function in Matplotlib is used to create pie charts. Pie charts are circular charts where each slice represents a
proportion of the whole.
Syntax:
[Link](data, labels=None, colors=None, autopct=None, startangle=None, radius=None)
Parameter Description
data A sequence of numerical values (sizes of slices).
labels Labels for each slice.
colors List of colors for the slices.
autopct String or function to format the percentage display.
startangle The angle at which the first slice will be drawn.
radius Radius of the pie chart.
Example Program to Create a Pie Chart:
Let's write a simple program that creates a pie chart representing the market share of different mobile brands.
import [Link] as plt
# Data for the pie chart (market share of different mobile brands)
labels = ['Apple', 'Samsung', 'Huawei', 'Xiaomi', 'Others']
sizes = [40, 30, 15, 10, 5] # Market share in percentage
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'lightgreen']
explode = (0.1, 0, 0, 0, 0) # "Explode" the first slice (Apple)
# Create a pie chart
[Link](sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=140, explode=explode)
# Set the title of the pie chart
[Link]("Market Share of Mobile Brands")
# Display the pie chart
[Link]()
Explanation of the Code:
labels: A list containing the names of mobile brands.
sizes: The corresponding market share for each brand in percentage.
colors: A list of colors to represent each slice.
explode: This tuple is used to "explode" a slice, i.e., make it stand out. The first slice (Apple) is exploded by
setting its value to 0.1.
autopct='%1.1f%%': This formats the display of the percentage value inside each slice to one decimal place.
startangle=140: Rotates the pie chart to start at a specific angle.
[Link](): Sets the title for the chart.
[Link](): Displays the pie chart on the screen.
Output:
The pie chart will look something like this:
A circle divided into slices, each slice representing a mobile brand.
The slice for Apple will be slightly "exploded" outwards.
The percentage value for each slice will be shown inside the chart.
PART – C (15 MARKS)
1. Discuss the various widgets available in Tkinter with an example.
Introduction to Tkinter Widgets:
In Tkinter, widgets are elements that allow you to interact with the graphical user interface (GUI). Widgets provide an
interface for user input or display information. Tkinter offers a wide range of widgets to create functional and
interactive applications. Some commonly used widgets include buttons, labels, entries, checkboxes, radio buttons, and
more.
List of Common Tkinter Widgets and Their Usage:
1. Label
o A Label widget is used to display text or images.
o It does not allow the user to interact with it, just for showing information.
Example:
import tkinter as tk
root = [Link]()
label = [Link](root, text="Hello, Tkinter!")
[Link]()
[Link]()
2. Button
o The Button widget is used to display a clickable button that can trigger an event or function when
clicked.
Example:
def on_click():
print("Button Clicked!")
root = [Link]()
button = [Link](root, text="Click Me", command=on_click)
[Link]()
[Link]()
3. Entry
o The Entry widget is used to create a text input box where users can type in data (single-line input).
Example:
def show_input():
entered_text = [Link]()
[Link](text=f"You entered: {entered_text}")
root = [Link]()
label = [Link](root, text="Enter something:")
[Link]()
entry = [Link](root)
[Link]()
button = [Link](root, text="Show Input", command=show_input)
[Link]()
[Link]()
4. Text
o The Text widget is used for multi-line text input or output. It supports rich text formatting like
changing font and color.
Example:
root = [Link]()
text_widget = [Link](root, height=5, width=30)
text_widget.pack()
text_widget.insert([Link], "This is a Text Widget\nYou can type multiple lines here.")
[Link]()
5. Checkbutton
o The Checkbutton widget is used to create a checkbox. It allows the user to select one or more
options.
Example:
def show_check_value():
value = [Link]()
[Link](text=f"Checkbox is {'checked' if value else 'unchecked'}")
root = [Link]()
var = [Link]()
checkbutton = [Link](root, text="Accept Terms and Conditions", variable=var,
command=show_check_value)
[Link]()
label = [Link](root)
[Link]()
[Link]()
6. Radiobutton
o The Radiobutton widget is used to create a set of mutually exclusive options (radio buttons). Only
one radio button can be selected at a time in a group.
Example:
def show_selected_option():
selection = [Link]()
[Link](text=f"You selected option {selection}")
root = [Link]()
var = [Link]()
radiobutton1 = [Link](root, text="Option 1", variable=var, value=1,
command=show_selected_option)
[Link]()
radiobutton2 = [Link](root, text="Option 2", variable=var, value=2,
command=show_selected_option)
[Link]()
label = [Link](root)
[Link]()
[Link]()
7. Listbox
o The Listbox widget is used to create a list of items where users can select one or more items.
Example:
def show_selection(event):
selection = [Link]()
[Link](text=f"You selected: {[Link](selection)}")
root = [Link]()
listbox = [Link](root)
[Link]()
items = ["Apple", "Banana", "Orange", "Grapes"]
for item in items:
[Link]([Link], item)
[Link]("<<ListboxSelect>>", show_selection)
label = [Link](root)
[Link]()
[Link]()
8. Scale
o The Scale widget is used to create a slider, allowing the user to select a value from a range.
Example:
def show_scale_value(val):
[Link](text=f"Selected value: {val}")
root = [Link]()
scale = [Link](root, from_=0, to=100, orient=[Link], command=show_scale_value)
[Link]()
label = [Link](root)
[Link]()
[Link]()
9. Scrollbar
o The Scrollbar widget is used to add scrolling functionality to a widget, such as a listbox, text widget,
or canvas.
Example:
root = [Link]()
text_widget = [Link](root, height=5, width=30)
text_widget.pack(side=[Link])
scrollbar = [Link](root, command=text_widget.yview)
[Link](side=[Link], fill=tk.Y)
text_widget.config(yscrollcommand=[Link])
[Link]()
10. Canvas
The Canvas widget is used for drawing shapes, images, and other graphical elements.
Example:
root = [Link]()
canvas = [Link](root, width=400, height=400)
[Link]()
# Draw a line
canvas.create_line(50, 50, 350, 350)
# Draw a rectangle
canvas.create_rectangle(100, 100, 300, 200)
# Draw an oval
canvas.create_oval(100, 250, 300, 350)
[Link]()
11. Menu
The Menu widget is used to create menus in an application, such as dropdown menus, which can contain
multiple items.
Example:
def hello():
print("Hello, Tkinter!")
root = [Link]()
menu_bar = [Link](root)
[Link](menu=menu_bar)
file_menu = [Link](menu_bar, tearoff=0)
menu_bar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Hello", command=hello)
file_menu.add_separator()
file_menu.add_command(label="Exit", command=[Link])
[Link]()
2. Write a python program to create a Pandas series using NumPy and perform basic operations on it.
import pandas as pd
import numpy as np
# Step 1: Create a NumPy array
data = [Link]([10, 20, 30, 40, 50])
# Step 2: Create a Pandas Series using the NumPy array
series = [Link](data)
# Display the created series
print("Created Pandas Series:")
print(series)
# Step 3: Perform basic operations
# 1. Accessing elements (get the element at index 2)
element_at_index_2 = series[2]
print("\nElement at index 2:", element_at_index_2)
# 2. Adding a constant value to each element of the series
series_plus_5 = series + 5
print("\nSeries after adding 5 to each element:")
print(series_plus_5)
# 3. Multiplying the series by a constant value
series_multiplied_by_2 = series * 2
print("\nSeries after multiplying each element by 2:")
print(series_multiplied_by_2)
# 4. Getting the mean of the series
mean_value = [Link]()
print("\nMean of the series:", mean_value)
# 5. Getting the sum of the series
sum_value = [Link]()
print("\nSum of the series:", sum_value)
# 6. Apply a function to the series (square each element)
squared_series = [Link](lambda x: x**2)
print("\nSeries after squaring each element:")
print(squared_series)
# Step 4: Adding a custom index to the series
custom_index = ['A', 'B', 'C', 'D', 'E']
custom_series = [Link](data, index=custom_index)
print("\nSeries with custom index:")
print(custom_series)
Explanation of the Code:
Creating a NumPy Array:
The code first creates a NumPy array data containing five elements: [10, 20, 30, 40, 50].
Creating a Pandas Series:
A Pandas Series is created using [Link](data), where data is the NumPy array.
Performing Basic Operations:
Accessing elements: You can access individual elements of the Series using indexing, for example, series[2]
returns the element at index 2.
Arithmetic operations: The Series is manipulated using basic arithmetic operations like addition (series + 5)
and multiplication (series * 2).
Statistical operations: The mean() function calculates the mean of the series, and sum() calculates the sum of
all elements.
Applying functions: You can apply a custom function (like squaring each element) using the apply() method.
Custom Indexing: A custom index (['A', 'B', 'C', 'D', 'E']) is applied to the Series to make it more meaningful.
Output:
Created Pandas Series:
0 10
1 20
2 30
3 40
4 50
dtype: int64
Element at index 2: 30
Series after adding 5 to each element:
0 15
1 25
2 35
3 45
4 55
dtype: int64
Series after multiplying each element by 2:
0 20
1 40
2 60
3 80
4 100
dtype: int64
Mean of the series: 30.0
Sum of the series: 150
Series after squaring each element:
0 100
1 400
2 900
3 1600
4 2500
dtype: int64
Series with custom index:
A 10
B 20
C 30
D 40
E 50
dtype: int64