Python Programming Question Bank 1-5 Units With Answers
Python Programming Question Bank 1-5 Units With Answers
5 How do you take user input in Python, and how is it stored by default? CO1 2 BTL2
In Python, user input is taken using the input () function. By default, the input is stored as a
string, regardless of what the user enters.
Example:
user_input = input ("Enter a number: ")
num = int(user_input) # Converts input to an integer
print ("Your number is:", num)
8. What are the differences between mutable and immutable data types in Python? CO1 2 BTL2
In Python, mutable and immutable data types differ in how they handle changes to the data
after creation.
1. Mutable Data Types:
• Definition: Mutable types can be modified after they are created. This means their
values can be changed in place without creating a new object.
• Examples: Lists, Dictionaries, Sets.
2. Immutable Data Types:
• Definition: Immutable types cannot be modified after they are created. Any operation
that changes an immutable object creates a new object instead.
• Examples: Strings, Tuples, Integers, Floats.
9. Provide examples of each (e.g., lists are mutable) for Strings, Tuples, Dictionaries, Sets? CO1 2 BTL1
Here are examples of mutable and immutable data types in Python:
1. Strings (Immutable):
my_string = "Hello"
# my_string [0] = "h” # Error: Strings are immutable
2. Tuples (Immutable):
my_tuple = (1, 2, 3)
MOHAMMED ZAIN UL ABDEEN (160923748116)
# my_tuple [0] = 10 # Error: Tuples are immutable
3. Dictionaries (Mutable):
my_dict = {'a': 1, 'b': 2}
my_dict['a'] = 10 # Dictionaries are mutable
print(my_dict) # Output: {'a': 10, 'b': 2}
4. Sets (Mutable):
my_set = {1, 2, 3}
my_set.add(4) # Sets are mutable
print(my_set) # Output: {1, 2, 3, 4}
10. How does this affect how data is passed to functions or modified in place? CO1 2 BTL2
Mutable data types (e.g., lists, dictionaries) can be modified in place. Changes made
inside a function will affect the original object.
Example:
def modify_list(lst):
lst.append(4)
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # Output: [1, 2, 3, 4]
Immutable data types (e.g., strings, tuples) cannot be modified in place. Any change
creates a new object, leaving the original unchanged.
Example:
def modify_string(s):
s = s + " World"
my_string = "Hello"
modify_string(my_string)
print(my_string) # Output: "Hello"
11. Explain the concept of loop control statements such as continue, break, pass, and CO1 2 BTL2
else in Python.
In Python, loop control statements are used to modify the behavior of loops:
1. break: Exits the loop prematurely when a condition is met.
for i in range(5):
if i == 3:
break
print(i) # Output: 0 1 2
2. continue: Skips the rest of the current iteration and moves to the next iteration.
for i in range(5):
if i == 3:
continue
print(i) # Output: 0 1 2 4
3. pass: A placeholder that does nothing but allows the code to run without error.
for i in range (5):
if i == 3:
pass
print(i) # Output: 0 1 2 3 4
12. How does the else block work with loops? CO1 2 BTL1
In Python, the else block in loops (for and while) is executed only if the loop
completes normally, i.e., without hitting a break statement. If the loop is terminated
by a break, the else block is skipped.
Key Points:
• else executes if the loop is not interrupted by a break.
• else does not execute if the loop is exited with a break.
Example 1: else with for loop (with break):
for i in range(3):
if i == 1:
break
print(i)
else:
print ("Loop completed without break.")
Output:
0
The else block is not executed because the loop was exited prematurely with a break
when i == 1.
14. Write about the print functions for a) print (f” ----”) and b). format method? CO1 2 BTL3
a) print(f"----") (f-strings):
• Definition: f-strings (formatted string literals) provide a way to embed
expressions inside string literals using curly braces {}. The expressions inside
the curly braces are evaluated at runtime and formatted into the string.
• Syntax: f "string {expression} string"
Example:
name = "Alice"
age = 25
print (f"Hello, my name is {name}, and I am {age} years old.")
Output:
MOHAMMED ZAIN UL ABDEEN (160923748116)
Hello, my name is Alice, and I am 25 years old.
b) .format() method:
• Definition: The .format() method allows you to insert values into placeholders
{} in a string. The values to be inserted are passed as arguments to the format
() function.
• Syntax: "string {} string”. format(value)
Example:
name = "Bob"
age = 30
print ("Hello, my name is {} and I am {} years old.".format(name, age))
Output:
Hello, my name is Bob and I am 30 years old.
15. Write 2 differences between While and For loop? CO1 2 BTL1
1. Loop Condition:
• while loop: Runs as long as a specified condition is true. The condition is
checked before each iteration.
• for loop: Iterates over a sequence (like a list, tuple, or range), running once for
each item in the sequence.
Example:
• while loop:
count = 0
while count < 5:
print(count)
count += 1
for loop:
for count in range(5):
print(count)
2. Usage:
• while loop: Typically used when the number of iterations is not known in
advance, and the loop should continue until a certain condition is met.
• for loop: Typically used when the number of iterations is known or when
iterating over a fixed sequence (like a list, tuple, or range).
Example:
• while loop:
# Continue until a specific condition is met
while some_condition:
# code block
• for loop:
# Iterate over a sequence (e.g., list or range)
for item in sequence:
# code block
LAQ’s
All questions carry 12 marks
1. What are conditional statements in Python? Explain the use of if, elif, and else with an CO2 12 BTL2
example where all three blocks are used.
Conditional Statements in Python:
Conditional statements in Python allow you to execute different blocks of code based on
whether a condition is True or False. These statements are used to control the flow of
execution in a program.
1. if:
MOHAMMED ZAIN UL ABDEEN (160923748116)
The if statement is used to test a condition. If the condition is True, the block of code inside
the if statement will execute.
2. elif:
The elif (short for "else if") statement is used to check multiple conditions. If the if condition
is False, Python will check the elif condition. You can have multiple elif statements.
3. else:
The else statement is used to run a block of code when none of the if or elif conditions are
True.
Example (Using if, elif, and else):
age = 20
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 60:
print("You are an adult.")
else:
print("You are a senior citizen.")
Output:
You are an adult.
Explanation:
The if statement checks if the age is less than 18. If True, it prints "You are a
minor."
If the first condition is False, the elif statement checks if age is between 18 and 60. If
True, it prints "You are an adult."
If both if and elif conditions are False, the else block is executed, printing "You are a
senior citizen."
2 Discuss the significance of the pass statement in Python. Explain its practical use cases CO1 12 BTL1
with an example program
Significance of the pass Statement in Python:
The pass statement in Python is a placeholder that does nothing when executed. It
is used in places where Python syntax requires a statement, but no action is required or
implemented at that point in the code. It allows you to write code that can be completed later
or serve as a placeholder for future implementation without causing any errors.
Practical Use Cases:
1. Empty Function or Class Definitions: When defining a function or class that you
plan to implement later, you can use pass to avoid errors.
2. Empty Loop or Conditional Block: In situations where a loop or conditional block
needs to be syntactically correct but doesn't need to do anything at the moment, pass
can be used.
3. Stub for Code Implementation: pass can act as a placeholder when writing code
incrementally or while debugging.
Example Program:
def feature_not_implemented ():
pass # Placeholder for future code implementation
class MyClass:
def method_to_implement_later(self):
pass # Placeholder for future method implementation
Python automatically handles the loop by iterating over the elements in the sequence and
allowing you to perform operations on each element during each iteration.
**************
b)Explain the different ways to use a for loop, including iterating over a sequence (list,
tuple, etc.).
Different Ways to Use a for Loop:
▪ Iterating over a List:
You can iterate directly over the elements of a list.
for element in my_list:
# process element
▪ Iterating over a Tuple: You can iterate directly over the elements
of a tuple in the same way as with a list.
for element in my_tuple:
# process element
***************
4. a) How do you take input and display output in Python? CO2 4,4,4 BTL2
In Python:
• The input () function is used to take input from the user. By default, it takes input as
a string.
• The print () function is used to display output to the console.
****************
b) using standard input (input)?
Using Standard Input (input ()):
1. Taking Input:
o The input () function waits for the user to type something, and press Enter.
o You can store the input in a variable.
o By default, input is stored as a string.
Example:
name = input ("Enter your name: “) # Takes user input as a string
print ("Hello, " + name + "!")
Output (if user inputs "Alice"):
Enter your name: Alice
Hello, Alice!
Converting Input:
• You can convert the input to other data types like integer or float using type
conversion.
Example:
age = int (input ("Enter your age: ")) # Converts input to an integer
print ("Your age is:", age)
***************
c) and output (print) functions? Provide examples.
Using Standard Output (print ()):
1. Displaying Text:
o The print () function is used to display text or variables on the screen.
o Multiple items can be separated by commas, which automatically adds a
space.
Example:
print ("Hello, World!")
print ("The sum of", 5, “and” 3, "is", 5 + 3)
Output:
Hello, World!
The sum of 5 and 3 is 8
2. Using String Formatting:
MOHAMMED ZAIN UL ABDEEN (160923748116)
• f-strings :
name = "Alice"
print (f"Welcome, {name}!")
3. Escape Characters:
Use \n for a newline or \t for a tab.
Example:
print("Hello\nWorld”) # Prints Hello and World on two lines
Full Example Program:
# Taking user input
name = input("Enter your name: ")
age = int(input("Enter your age: ")) #
Displaying output
print(f"Hello, {name}! You are {age} years old.")
print("Next year, you will be", age + 1, "years old.")
Sample Output:
Enter your name: Alice
Enter your age: 25
Hello, Alice! You are 25 years old.
Next year, you will be 26 years old.
5 a) What are string formatting techniques in Python? CO1 4,4,4 BTL3
String formatting in Python refers to ways of inserting variables or expressions into
strings. It allows you to create formatted strings dynamically. Common
techniques include:
1. % operator: A classic style similar to C-style formatting.
2. . format () method: A modern approach introduced in Python 3.
3. f-strings (formatted string literals): Introduced in Python 3.6 for concise formatting.
*************
b) Explain the difference between f-strings, .format(), and the % operator for string
formatting. Provide examples.
Differences Between f-strings, .format(), and % Operator: -
************
c) Examples of Each Technique
1. % Operator (Old Style Formatting):
• Placeholders like %s (string), %d (integer), %f (float) are used.
name = "Alice"
age = 25
print("Hello, %s! You are %d years old." % (name, age))
Output:
Hello, Alice! You are 25 years old.
2. .format() Method:
• Uses {} placeholders, which can be replaced by positional or keyword
arguments.
MOHAMMED ZAIN UL ABDEEN (160923748116)
name = "Bob"
age = 30
print ("Hello, {}! You are {} years old.”. format (name, age))
print ("Hello, {name}! You are {age} years old.”. format (name="Bob", age=30))
Output:
Hello, Bob! You are 30 years old.
Hello, Bob! You are 30 years old.
3. f-strings (Formatted String Literals):
• Allows expressions inside {} directly in the string.
name = "Charlie"
age = 35
print (f"Hello, {name}! You are {age} years old.")
print (f"Next year, you will be {age + 1} years old.")
Output:
Hello, Charlie! You are 35 years old.
Next year, you will be 36 years old.
6 a) Explain the different types of numbers in Python (integers, floats, and complex CO1 4,4,4 BTL1
numbers).
Integers (int):
• Whole numbers, positive or negative, without a decimal point.
• Examples: -5, 0, 42
Floating-Point Numbers (float):
• Numbers with a decimal point or in exponential form.
• Examples: 3.14, -0.001, 2.5e3 (scientific notation for 2.5×1032.5 \times
10^32.5×103).
Complex Numbers (complex):
• Numbers with a real part and an imaginary part, denoted by j.
• Examples: 3 + 4j, -2j
************
b) How does Python handle large integers and floating-point precision?
Large Integers:
• Python supports arbitrarily large integers, limited only by the memory of your
system.
• No separate data type for "long integers" as in some other languages.
Example:
large_int = 123456789012345678901234567890
print(large_int) # Output: 123456789012345678901234567890
Floating-Point Precision:
• Floating-point numbers are represented internally using the IEEE 754 double-
precision standard.
• They have finite precision, so operations may result in small rounding errors.
Example:
result = 0.1 + 0.2
print(result) # Output: 0.30000000000000004 (due to floating-point precision)
************
c) Provide examples of operations performed on each type.
1. Operations on Integers:
• Basic arithmetic: +, -, *, // (floor division), % (modulus), ** (exponentiation).
x, y = 10, 3
print (x + y) # Output: 13
print (x // y) # Output: 3
print (x ** y) # Output: 1000
2. Operations on Floats:
• Support all arithmetic operations, including division and exponential.
a, b = 2.5, 3.0
print (a * b) # Output: 7.5
print (a / b) # Output: 0.8333333333333334
MOHAMMED ZAIN UL ABDEEN (160923748116)
4. Operations on Complex Numbers:
• Use .real and. imag to access the real and imaginary parts.
• Arithmetic operations work directly.
z1, z2 = 3 + 4j, 1 - 2j
print (z1 + z2) # Output: (4+2j)
print (z1 * z2) # Output: (11-2j)
print (z1.real, z1. imag) # Output: 3.0 4.0
7 a) Explain the role of indentation in Python. CO1 4,4,4 BTL2
Indentation in Python is used to define the structure of the code. Unlike many programming
languages that use braces ({}) or keywords to define code blocks, Python relies on
indentation levels to indicate blocks of code. Indentation is mandatory in Python, and
incorrect indentation will result in a syntax error.
For example:
if condition:
# Indented block is executed if condition is True
print ("Condition is True")
***********
b) How does it affect the structure and readability of Python programs, particularly
with control structures like if, for and while loops?
Impact of Indentation on Structure and Readability
1. Structure:
o Indentation is used to group statements under control structures like if,
for, and while.
o It visually indicates which lines of code belong to a particular block.
Example with if statement:
x = 10
if x > 5:
print ("x is greater than 5")
2. Readability:
• Proper indentation makes the code easier to read and understand.
• It eliminates the need for additional symbols (like braces {}) to define blocks,
reducing visual clutter.
Example with for loop:
for i in range (3):
print(i) # Clearly part of the loop
print ("Loop finished”) # Clearly outside the loop
********
c) What common mistakes do beginners make related to indentation?
1) Inconsistent Indentation:
• Mixing spaces and tabs within the same code block.
• Python requires consistent use of either spaces or tabs (PEP 8 recommends 4 spaces
per indentation level).
• Error Example:
if x > 5:
print ("This uses 1 tab”) # Inconsistent indentation
print ("This uses 4 spaces")
2) Missing Indentation: Forgetting to indent a block of code after a control structure.
Error Example:
if x > 5:
print ("This line is not indented”) # SyntaxError
3) Unnecessary Indentation:
Indenting lines of code that should not be part of a block.
Error Example:
print ("Outside block")
print ("This line is unnecessarily indented") # IndentationError
4) Indenting Incorrectly with Nested Blocks:
Incorrectly aligning nested structures.
Error Example:
if x > 5:
if y > 10:
print("Incorrectly aligned nested block") # SyntaxError
MOHAMMED ZAIN UL ABDEEN (160923748116)
8 a) What are lambda functions in Python? CO1 4,4,4 BTL1
Lambda functions, also called anonymous functions, are small, single-expression
functions in Python that do not require a def keyword or a name. They are used for short-term
tasks, often in cases where a full function definition is not necessary.
*************
b) Discuss their syntax, use cases, and when to prefer them over regular function
definitions.
Syntax, Use Cases, and When to Prefer Lambda Functions
Syntax:
lambda arguments: expression
arguments: Input parameters for the lambda function.
expression: A single expression that is evaluated and returned.
Example:
add = lambda x, y: x + y
print (add (2, 3)) # Output: 5
Use Cases:
1. Short-Term Use:
o Ideal for quick, simple operations that do not require a full function.
2. Functional Programming:
o Often used with functions like map(), filter(), and sorted() for concise
operations.
3. Inline Functionality:
o When defining small, one-off functions that won't be reused elsewhere.
When to Prefer Lambda Functions:
• Use lambda functions for short, simple tasks.
• Use regular function definitions when:
o The function has complex logic.
o The function requires documentation or reuse.
**************
c) Provide examples where a lambda function is used with map(), filter(), or
sorted() to perform operations on data.
1. Using Lambda with map():
The map() function applies a lambda function to each element in a sequence.
Example:
numbers = [1, 2, 3, 4, 5]
squared = list (map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
2. Using Lambda with filter ():
The filter () function filters elements from a sequence based on a condition.
Example:
numbers = [10, 15, 20, 25, 30]
even_numbers = list (filter (lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [10, 20, 30]
3. Using Lambda with sorted():
The sorted () function can use a lambda function as the key for custom sorting.
Example:
names = ["Alice", "Bob", "Charlie"]
sorted_names = sorted(names, key=lambda x: len(x))
print(sorted_names) # Output: ['Bob', 'Alice', 'Charlie']
9 a) What are the differences between global and local variables in Python? CO1 4,4,4 BTL2
Differences Between Global and Local Variables in Python
Feature Global Variables Local Variables
Definition Declared outside of any Declared inside a function or block.
function or block.
Scope Accessible throughout the Accessible only within the
program. function/block where defined.
Persistence Retains value for the entire Exists only during the execution of
program execution. the function/block.
Declaration Can be declared and modified Declared within a specific scope.
MOHAMMED ZAIN UL ABDEEN (160923748116)
globally.
***************
b) How does scope affect variable accessibility?
1. Local Scope:
o Variables declared inside a function are local and accessible only within that
function.
o Attempting to access them outside the function results in an error.
Example:
def my_function ():
local_var = 10
print(local_var) # Accessible here
my_function ()
print(local_var) # Error: NameError: local_var is not defined
2. Global Scope:
• Variables declared outside any function are global and accessible throughout the
program.
• However, they cannot be modified inside a function unless explicitly declared as
global.
Example:
global_var = 20
def my_function ():
print(global_var) # Accessible inside the function
my_function ()
print(global_var) # Accessible outside the function
3. Nested Scope:
• Variables in outer functions are accessible in nested inner functions (nonlocal
scope)
*****************
c) Provide an example of how the global keyword is used to modify a global variable
inside a function.
The global keyword allows modification of a global variable inside a function.
Example: -
# Global variable
counter = 0
c) Explain with examples how they can be used to handle errors like ValueError,
TypeError, and IndexError. How do you raise custom exceptions in Python?
Sample Interaction:
• Input: a Output: Invalid input! Please enter a valid integer.
• Input: 10 Output: Index out of range! Enter a valid index.
2. Raising Custom Exceptions
You can define and raise your own exceptions using the raise keyword.
Example: Custom Exception
class CustomError (Exception):
"""Custom exception class"""
pass
def check_number(num):
if num < 0:
raise CustomError("Negative numbers are not allowed!")
print("Number is valid.")
try:
check_number(-5) # Raises CustomError
except CustomError as e:
print(f"CustomError caught: {e}")
finally:
print("Finished checking the number.")
Output:
CustomError caught: Negative numbers are not allowed!
Finished checking the number.
MOHAMMED ZAIN UL ABDEEN (160923748116)
Unit2:
Q.No Question CO Mark BTL
s
SAQ’s
All questions carry 2 marks.
1 Define function? Mention the type of function and uses. CO 2 BTL1
A function in Python is a block of reusable code designed to perform a 2
specific task. It is defined using the def keyword and can take
parameters, execute code, and return a result.
Types of Functions:
1. Built-in Functions: Predefined functions (e.g., print(), len()).
2. User-Defined Functions: Custom functions created by users.
Example:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
2 List basic list operations that can be performed in Python? CO 2 BTL2
Basic List Operations in Python: - 2
i) Accessing Elements: Use indexing to access list items.
my_list = [1, 2, 3]
print (my_list [0]) # Output: 1
ii) Adding Elements: Use append () or insert ().
my_list. Append (4) # Adds 4 at the end
iii) Removing Elements: Use remove () or pop ().
my_list.pop (0) # Removes the first element
iv) Slicing: Extract a portion of the list.
print (my_list [1:3]) # Output: [2, 3]
v) Sorting: Use sort () or sorted ().
my_list. Sort () # Sorts the list in ascending order
3 What are tuples in Python? CO 2 BTL1
A tuple is an immutable sequence of elements in Python, used to store 2
multiple items in a single variable. Tuples are defined using parentheses
() and can hold elements of different data types.
Key Features:
Immutable: Elements cannot be changed after creation.
Ordered: Maintains the order of elements.
Can contain duplicates.
my_tuple = (1, 2, 3, "Python")
print (my_tuple [0]) # Output: 1
Tuples are useful for grouping related data and ensuring data integrity.
CO 2 BTL2
Mention the advantages of Tuple over List? 2
4 Advantages of Tuples Over Lists : -
1. Immutability:
o Tuples are immutable, meaning their elements cannot
be changed after creation, ensuring data integrity.
2. Performance:
o Tuples are faster than lists for operations because they
are fixed in size and optimized for fewer modifications.
3. Memory Efficiency:
o Tuples consume less memory compared to lists,
making them better for large datasets.
4. Hashable:
o Tuples can be used as keys in dictionaries or elements
in sets because they are hashable, unlike lists.
MOHAMMED ZAIN UL ABDEEN (160923748116)
Example:
my_tuple = (1, 2, 3)
my_list = [1, 2, 3]
# my_tuple [0] = 10 # This will raise an error
CO 2 BTL3
2
7. Write the syntax of set data type in python with an example?
Syntax of Set in Python: -
A set in Python is a collection of unique and unordered elements. It is
defined using curly braces {} or the set () constructor.
Syntax:
# Using curly braces
my_set = {element1, element2, ...}
# Using set () constructor
my_set = set([iterable])
Example:
# Using curly braces
fruits = {"apple", "banana", "cherry"}
print(fruits) # Output: {'banana', 'cherry', 'apple'}
# Using set () constructor
numbers = set ([1, 2, 2, 3])
print(numbers) # Output: {1, 2, 3} (duplicates are removed)
MOHAMMED ZAIN UL ABDEEN (160923748116)
8. Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]. Find a) list [1:3] b) t[:4]. CO 2 BTL3
Given List: 2
list = ['a', 'b', 'c', 'd', 'e', 'f']
a) list [1:3]
• Explanation:
o Starts at index 1 (element 'b').
o Stops before index 3 (element 'd').
o Includes elements at indices 1 and 2.
• Output:
['b', 'c']
b) list [:4]
• Explanation:
o Starts from the beginning of the list.
o Stops before index 4 (element 'e').
o Includes elements at indices 0, 1, 2, and 3.
• Output:
['a', 'b', 'c', 'd']
10. What is the usage of help () and dir () function in Python? CO 2 BTL1
help () Function: 2
• Displays the documentation of an object (module, class,
function, etc.).
• Helps in understanding the purpose and usage of Python
objects.
Example:
help(str) # Displays documentation for the str class
dir () Function:
• Returns a list of attributes and methods available for an object.
• Helps in exploring the available properties of an object.
Example:
dir(str) # Lists all methods of the str class
MOHAMMED ZAIN UL ABDEEN (160923748116)
11. Write a python program to Check if all items in the tuple are the CO 2 BTL2
same? 2
def check_all_same(t):
return len(set(t)) == 1 # Convert tuple to a set and check if it has
only one unique item
# Example Tuple
my_tuple = ('a', 'a', 'a', 'a')
# Check if all items are the same
if check_all_same(my_tuple):
print ("All items in the tuple are the same.")
else:
print ("Not all items in the tuple are the same.")
Explanation:
• The program converts the tuple to a set, which removes
duplicates.
• If the set has only one element, all items in the tuple are the
same.
Output:
All items in the tuple are the same.
12. Analyze different ways to create a list with its syntax and example. CO 2 BTL3
Using Square Brackets: 2
• The simplest way to create a list is using square brackets[].
Example:
my_list = [1, 2, 3, 4]
Using list () Constructor:
• You can use the list () function to create a list from another
iterable, such as a tuple.
Example:
my_tuple = (1, 2, 3)
my_list = list(my_tuple)
Using List Comprehension:
• You can create a list by applying an expression to each item in
an iterable.
Example:
my_list = [x * 2 for x in range (5)]
Using * Operator:
• You can create a list by repeating an element multiple time.
Example:
my_list = [0] * 5
Example:
def greet (name, greeting="Hello"):
return f"{greeting} {name}"
*************
b)Write a python program to find whether the element is member
or not a member of the list.
The following Python program checks if a given element is a member
of a list using the in operator.
# Python Program to check membership of an element in a list
def is_member (element, my_list):
if element in my_list:
return True # Element is a member of the list
else:
return False # Element is not a member of the list
# Example list
my_list = [10, 20, 30, 40, 50]
# Check if element 30 is in the list
element_to_check = 30
if is_member (element_to_check, my_list):
print(f"{element_to_check} is a member of the list.")
else:
print(f"{element_to_check} is not a member of the list.")
Explanation:
• The is_member function checks if the provided element is
present in my_list using the in operator.
• The in operator returns True if the element is found and False
if it is not.
Output:
30 is a member of the list.
60 is not a member of the list.
************
b) Write a python program to describe different ways of deleting
an element from the given List.
In Python, elements can be deleted from a list using various
methods such as del, remove(), pop(), and clear(). Here’s a program
that demonstrates these methods.
Python Program:
# Python Program to Delete Elements from a List
# Define a list
my_list = [10, 20, 30, 40, 50]
# Method 1: Using del (removes an element by index)
del my_list[2] # Removes the element at index 2 (30)
print ("After del:", my_list) # Output: [10, 20, 40, 50]
# Method 2: Using remove () (removes first occurrence of a
value)
my_list. remove(40) # Removes the first occurrence of 40
print ("After remove:", my_list) # Output: [10, 20, 50]
Explanation:
1. del: Removes an element from the list by index. It does not
return the element.
2. remove(): Removes the first occurrence of a specified value. If
the value is not found, it raises a ValueError.
3. pop(): Removes an element by index and returns the removed
element. If no index is specified, it removes and returns the last
item.
4. clear(): Removes all elements from the list, leaving it empty.
Output:
After del: [10, 20, 40, 50]
After remove: [10, 20, 50]
After pop: [10, 50]
Removed element: 20
After clear: []
MOHAMMED ZAIN UL ABDEEN (160923748116)
3. a) Write a recursive Python function that recursively computes CO 6 BTL3
sum of elements in a list of lists. 2
A recursive function can be used to calculate the sum of elements in a
nested list (list of lists). The function should iterate through the list, 6
checking if an element is itself a list or an integer, and perform BTL4
summing accordingly.
Recursive Python Function to Compute Sum of Elements:
def sum_elements(nested_list):
total = 0
for element in nested_list:
if isinstance (element, list): # Check if the element is a list
total += sum_elements(element) # Recursively sum inner lists
else:
total += element # Add the element if it's not a list
return total
# Example list of lists
nested_list = [1, [2, 3], [4, [5, 6]], 7]
result = sum_elements(nested_list)
print ("Sum of elements:", result) # Output: 28
Explanation:
• The function sum_elements takes a nested list as an
argument.
• It initializes a variable total to accumulate the sum of
elements.
• It iterates through each element:
o If the element is a list (isinstance(element, list)), it
recursively calls sum_elements() to sum the inner
list.
o If the element is not a list (i.e., an integer), it simply
adds it to total.
• The recursion continues until all elements are processed.
Output:
Sum of elements: 28
*************
b)Analyze the different operations that can be performed on a list?
Explain with examples?
In Python, lists are versatile data structures that allow a variety of
operations. Some common operations on lists include indexing,
slicing, adding elements, removing elements, sorting, and more.
1. Indexing:
• Indexing allows access to individual elements in a list using an
index. Indexing starts at 0.
Example:
my_list = [10, 20, 30, 40, 50]
print(my_list [0]) # Output: 10
2. Slicing:
• Slicing allows extracting a portion of the list by specifying a
start and end index.
Example:
my_list = [10, 20, 30, 40, 50]
print(my_list [1:4]) # Output: [20, 30, 40]
3. Adding Elements:
• append (): Adds an element to the end of the list.
• insert (): Inserts an element at a specific index.
• extend (): Adds multiple elements (from another iterable) to the
end of the list.
MOHAMMED ZAIN UL ABDEEN (160923748116)
Examples:
my_list = [10, 20, 30]
my_list. append (40) # Adds 40 at the end
print(my_list) # Output: [10, 20, 30, 40]
my_list. Insert (2, 25) # Inserts 25 at index 2
print(my_list) # Output: [10, 20, 25, 30, 40]
my_list. extend ([50, 60]) # Extends the list with [50, 60]
print(my_list) # Output: [10, 20, 25, 30, 40, 50, 60]
4. Removing Elements:
• remove (): Removes the first occurrence of a specified element.
• pop (): Removes and returns an element from the specified
index (or the last item if no index is specified).
• del: Deletes an element at a specific index or the entire list.
• clear (): Removes all elements from the list.
Examples:
my_list = [10, 20, 30, 40]
my_list. remove (20) # Removes the first occurrence of 20
print(my_list) # Output: [10, 30, 40]
removed element = my_list.pop (1) # Removes and returns
element at index 1
print (removed element) # Output: 30
print(my_list) # Output: [10, 40]
Summary:
• Indexing and Slicing allow access to elements.
• Adding elements can be done with append(), insert(), and
MOHAMMED ZAIN UL ABDEEN (160923748116)
extend().
• Removing elements can be achieved with remove(), pop(),
del, and clear().
• Sorting can be done with sort() or sorted().
• List comprehension is a powerful tool for creating lists.
***************
b) Explain in brief about Tuple in python. Write operations with
suitable examples.
A tuple in Python is an immutable sequence type. Tuples are used to
store multiple items in a single variable. Unlike lists, tuples are
immutable, meaning once they are created, their elements cannot be
changed, added, or removed.
Key Characteristics of Tuples:
1. Immutable: Elements cannot be changed after creation.
2. Ordered: The elements in a tuple have a defined order and can
be indexed.
3. Allow Duplicates: Tuples can have repeated values.
4. Parentheses: Tuples are created by enclosing elements in
parentheses ().
5. Heterogeneous: Tuples can contain elements of different data
types.
Syntax:
tuple_name = (element1, element2, element3, ...)
Operations on Tuples:
1. Indexing:
MOHAMMED ZAIN UL ABDEEN (160923748116)
o Tuples allow indexing, where the first element is at
index 0.
Example:
my_tuple = (10, 20, 30, 40)
print(my_tuple[1]) # Output: 20
2. Slicing:
• You can slice a tuple to access a range of elements.
Example:
my_tuple = (10, 20, 30, 40, 50)
print (my_tuple [1:4]) # Output: (20, 30, 40)
3. Concatenation:
• You can concatenate tuples using the + operator.
Example:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple) # Output: (1, 2, 3, 4, 5, 6)
4. Repetition:
• You can repeat a tuple using the * operator.
Example:
my_tuple = (1, 2, 3)
repeated_tuple = my_tuple * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)
5. Membership:
• You can check if an element is present in the tuple using the
in operator.
Example:
my_tuple = (10, 20, 30, 40)
print(20 in my_tuple) # Output: True
print(50 in my_tuple) # Output: False
6. Length:
• You can find the length of a tuple using the len() function.
Example:
my_tuple = (1, 2, 3, 4)
print(len(my_tuple)) # Output: 4
7. Nested Tuples:
• Tuples can also contain other tuples, allowing for nested
structures.
Example:
nested_tuple = (1, (2, 3), (4, 5))
print(nested_tuple[1]) # Output: (2, 3)
8. Unpacking:
• You can assign individual elements of a tuple to variables
using unpacking.
Example:
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a, b, c) # Output: 1 2 3
Conclusion:
• Tuples are commonly used when you need a collection of items
that should not be modified.
• They are more memory-efficient and faster for iteration than
lists due to their immutability.
MOHAMMED ZAIN UL ABDEEN (160923748116)
5 a) Write a program to print the squares of numbers in a given list CO 6 BTL3
using lambdas in map (). 2
The map () function in Python applies a given function to all items
in an input list (or any iterable). In this case, we will use a lambda 6 BTL3
function to square the elements of the list.
Python Program to Print Squares of Numbers Using map() and
Lambda:
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Use map with lambda to square each element
squared_numbers = list (map (lambda x: x**2, numbers))
# Print the result
print ("Squares of numbers:", squared_numbers)
Explanation:
• The map () function applies the lambda function (lambda x:
x**2) to each element of the list numbers.
• The lambda function takes an argument x and returns its square
(x**2).
• The result is converted to a list using list () to display the
squared numbers.
Output:
Squares of numbers: [1, 4, 9, 16, 25]
b) Write a program which creates a list of strings and numbers
and combine that two lists into one.
In this case, we will create two separate lists: one containing strings
and the other containing numbers. We will then combine them into
a single list using the + operator.
Python Program to Combine Two Lists:
# List of strings
strings = ["apple", "banana", "cherry"]
# List of numbers
numbers = [1, 2, 3]
# Combine both lists
combined_list = strings + numbers
# Print the result
print("Combined List:", combined_list)
Explanation:
• We have two lists: strings and numbers.
• The + operator is used to concatenate the two lists together into
one list, combined_list.
Output:
Combined List: ['apple', 'banana', 'cherry', 1, 2, 3]
Summary:
• a) The map() function with a lambda expression is used to
apply a function (in this case, squaring numbers) to each
element of the list.
• b) The two lists of strings and numbers are combined into one
using the + operator.
Explanation:
• The function add_numbers(a, b) accepts two parameters a and
b.
• The function adds the two numbers and returns the result.
• The function is called with num1 and num2 as arguments.
• The return value is stored in the variable sum_result and printed.
Output:
Sum of 10 and 20 is: 30
*********************
b) Write a Python program calculate the product, multiplying all
the numbers of a given tuple.
To calculate the product of all numbers in a tuple, you can use a
loop to multiply each number iteratively or use the
functools.reduce() function.
Python Program to Calculate the Product of All Numbers in a
Tuple:
# Function to calculate the product of all elements in a tuple
from functools import reduce
def product_of_tuple(tup):
return reduce(lambda x, y: x * y, tup)
# Given tuple
my_tuple = (2, 3, 4, 5)
# Calculate the product
product_result = product_of_tuple(my_tuple)
# Print the result
print("Product of all elements in the tuple:", product_result)
Explanation:
• We use the reduce() function from the functools module. It
applies the lambda function to accumulate a result by
multiplying all the elements of the tuple.
• The lambda x, y: x * y defines a function to multiply two
numbers.
• The reduce() function processes each element of the tuple and
multiplies them together.
MOHAMMED ZAIN UL ABDEEN (160923748116)
• The result is stored in product_result and printed.
Output:
Product of all elements in the tuple: 120
Summary:
• a) Functions in Python are created using the def keyword. They
can take parameters and return values using the return
keyword.
• b) The product of all elements in a tuple can be calculated using
the reduce() function from functools and a lambda expression
to multiply the elements.
# Example usage
num = 5
result = factorial(num)
print(f"Factorial of {num} is {result}")
Explanation:
• The factorial() function calculates the factorial of a number
recursively.
• If n is 0, the function returns 1 (base case).
• Otherwise, it calls itself with n-1 and multiplies the result by n.
Output:
Factorial of 5 is 120
***********
b) Write a program to demonstrate list operations, including
adding, replacing, removing elements.
Python lists support various operations like adding elements,
replacing elements, and removing elements. Below are examples
of these operations.
Example Program to Demonstrate List Operations:
# List initialization
my_list = [1, 2, 3, 4, 5]
MOHAMMED ZAIN UL ABDEEN (160923748116)
# 1. Adding elements
my_list. append (6) # Adding an element at the end
my_list. Insert (2, 7) # Inserting an element at a specific position
(index 2)
# 2. Replacing elements
my_list [3] = 10 # Replacing the element at index 3 with 10
# 3. Removing elements
my_list. remove (7) # Removing the element with value 7
removed_element = my_list.pop (1) # Removing the element at
index 1 and storing it in a variable
# Print the updated list and removed element
print ("Updated List:", my_list)
print ("Removed Element:", removed_element)
Explanation:
1. Adding Elements:
o append(6) adds 6 to the end of the list.
o insert(2, 7) inserts 7 at index 2.
2. Replacing Elements:
o The element at index 3 is replaced with 10 using my_list
[3] = 10.
3. Removing Elements:
o remove (7) removes the first occurrence of the value 7.
o pop (1) removes the element at index 1 and returns it
(storing it in removed_element).
Output:
Updated List: [1, 10, 3, 4, 5, 6]
Removed Element: 2
Summary:
• a) A recursive function calls itself and is useful for solving
problems that can be broken down into smaller subproblems.
The base case terminates the recursion.
• b) In Python lists, elements can be added using append() or
insert(), replaced by directly assigning values, and removed
using remove() or pop().
8 a) What are lambda functions? How are they different from CO 6 BTL2
regular functions? Provide two examples to demonstrate their 2
use.
Lambda functions are anonymous (unnamed) functions in Python, 6 BTL3
defined using the lambda keyword. They are often used when a
simple, short function is required for a short duration, such as in
functions like map(), filter(), or sorted().
Syntax of Lambda Function:
lambda arguments: expression
• arguments: Input values (can be multiple).
• expression: A single expression whose result is returned.
Differences Between Lambda Functions and Regular
Functions:
1. Syntax:
o Lambda functions are defined using lambda, whereas
regular functions are defined using def.
2. Name:
o Lambda functions are anonymous (no function name),
while regular functions are named.
3. Functionality:
MOHAMMED ZAIN UL ABDEEN (160923748116)
o Lambda functions are limited to a single expression and
do not require a return statement. Regular functions can
have multiple expressions and complex logic.
Example 1: Using Lambda Function with map():
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Using lambda function to square the numbers
squared_numbers = list (map(lambda x: x**2, numbers))
# Print the result
print("Squared numbers:", squared_numbers)’
Explanation:
• The lambda function takes one input x and returns x**2.
• map () applies this lambda to each element of the list numbers.
Output:
Squared numbers: [1, 4, 9, 16, 25]
Example 2: Using Lambda Function with sorted() :
# List of tuples with name and age
people = [("Alice", 25), ("Bob", 20), ("Charlie", 30)]
# Sorting the list by age using lambda function
sorted_people = sorted(people, key=lambda person: person[1])
# Print the result
print("Sorted people by age:", sorted_people)
Explanation:
• The lambda function is used to extract the second element (age)
of each tuple for sorting.
• sorted() sorts the list of tuples based on the age.
Output:
Sorted people by age: [('Bob', 20), ('Alice', 25), ('Charlie', 30)]
************
b) Write a Python program calculate the product, multiplying all
the numbers of a given tuple.
To calculate the product of all elements in a tuple, we can use the
reduce() function from the functools module. This function applies
a binary function (in this case, multiplication) to all items in the
tuple.
Python Program to Calculate the Product of All Numbers in a
Tuple:
from functools import reduce
# Tuple of numbers
my_tuple = (2, 3, 4, 5)
# Using reduces to calculate the product
product_result = reduce(lambda x, y: x * y, my_tuple)
# Print the result
print("Product of all elements in the tuple:", product_result)
Explanation:
• The reduce() function takes two arguments: a function and an
iterable.
• The lambda x, y: x * y is a function that multiplies two
numbers.
• reduce() applies this lambda function to all elements of
my_tuple, multiplying them iteratively.
Output:
Product of all elements in the tuple: 120
MOHAMMED ZAIN UL ABDEEN (160923748116)
Summary:
• a) Lambda functions are anonymous functions defined using
lambda and can perform simple operations in a single
expression, unlike regular functions which are more versatile
and defined using def.
• b) The product of elements in a tuple can be calculated using the
reduce () function combined with a lambda expression for
multiplication.
9 a)Explain tuples in Python. Compare them with lists and with help CO 6 BTL2
of examples show where using a tuple is preferable to a list. 2
Tuples in Python are ordered, immutable collections of elements, which
means that once a tuple is created, its elements cannot be changed, 6 BTL4
added, or removed.
Key Characteristics of Tuples:
1. Ordered: The elements of a tuple have a specific order, and this
order is maintained.
2. Immutable: Once created, the elements of a tuple cannot be
modified (no add, remove, or change operations).
3. Allow Duplicate Elements: Tuples can contain duplicate
values.
4. Parentheses: Tuples are defined using parentheses (), while
lists use square brackets [].
Comparison Between Tuples and Lists:
Feature Tuple List
Syntax (1, 2, 3) [1, 2, 3]
Mutability Immutable (cannot Mutable (can change
change elements) elements)
Performance Faster in iteration and Slower in iteration and
memory usage uses more memory
Use Cases Used for fixed data, and Used for dynamic data
when you want to ensure where modification is
data integrity needed
When to Prefer a Tuple Over a List:
• Immutability: When you need to ensure that the data will not
be changed, a tuple is preferable.
• Performance: Tuples have a slight performance advantage
over lists, especially when iterating over large amounts of data.
• Fixed Data: If the collection is meant to store constant values
that should not be modified, use a tuple.
Example: Where Tuples Are Preferable:
# Tuples for fixed data (e.g., coordinates)
coordinates = (10, 20)
# Lists for data that might change (e.g., student scores)
student_scores = [90, 85, 88]
In the case of coordinates, since the values represent fixed points
that should not change, a tuple is appropriate. If it were a list, the user
could modify the values accidentally.
For student_scores, a list is appropriate because the scores may
change during the program execution.
*******************
b)Analyze the difference between local and global variables
Local variables and global variables differ in their scope and
MOHAMMED ZAIN UL ABDEEN (160923748116)
accessibility within a program.
Key Differences:
1. Scope:
o Local Variables: These are variables that are defined
inside a function. They can only be accessed within that
function.
o Global Variables: These are variables defined outside
of all functions and can be accessed anywhere in the
program.
2. Lifetime:
o Local Variables: The lifetime of a local variable is
limited to the function in which it is defined. Once the
function execution is complete, the local variable is
destroyed.
o Global Variables: The lifetime of a global variable lasts
for the entire duration of the program.
3. Modification:
o Local Variables: Can only be modified within the
function where they are defined.
o Global Variables: Can be accessed and modified from
any part of the program (but to modify them inside a
function, you must use the global keyword).
Example Program to Demonstrate Local and Global Variables:
# Global variable
x = 10
# Function using a local variable
def test_function ():
# Local variable
y=5
print ("Inside function, local variable y:", y)
print ("Inside function, global variable x:", x) # Access global
variable
# Call the function
test_function ()
# Print global variable outside the function
print ("Outside function, global variable x:", x)
# Trying to print local variable y outside the function will result
in an error
# print("Outside function, local variable y:", y) # This will
cause an error
Explanation:
• x is a global variable because it is defined outside the function,
and it can be accessed inside test_function().
• y is a local variable because it is defined inside test_function(),
and it can only be accessed within that function.
• Trying to access y outside the function will result in a
NameError since y does not exist outside of the function.
Output:
Inside function, local variable y: 5
Inside function, global variable x: 10
Outside function, global variable x: 10
MOHAMMED ZAIN UL ABDEEN (160923748116)
Summary:
• a) Tuples are immutable, ordered collections, used for fixed
data that should not be changed. They are more efficient for
iteration and memory usage. Lists, on the other hand, are
mutable and are more suitable when data needs to be modified.
• b) Local variables are accessible only within the function they
are defined in, while global variables are accessible throughout
the program. Global variables have a longer lifetime and can be
modified from any part of the code, but local variables only
exist during the function execution.
1. Write a Python program to find the intersection and union of two sets. CO 2 BTL
In Python, the intersection of two sets can be found using the & operator or the 3 2
intersection() method. The union of two sets can be found using the | operator or the
union() method.
Program:
# Define two sets
MOHAMMED ZAIN UL ABDEEN (160923748116)
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Intersection of two sets
intersection_result = set1 & set2
# Union of two sets
union_result = set1 | set2
# Print results
print("Intersection of sets:", intersection_result)
print("Union of sets:", union_result)
Explanation:
• The intersection (&) returns the common elements between set1 and set2.
• The union (|) returns all the unique elements from both sets.
Output:
Intersection of sets: {4, 5}
Union of sets: {1, 2, 3, 4, 5, 6, 7, 8}
3. How to Create a Class in Python? Create an Object from a Class in Python. CO3 2 BTL
It defines the properties (attributes) and behaviors (methods) that the objects of that 1
class will have.
To create a class:
1. Use the class keyword followed by the class name.
2. Define a special method __init__() to initialize the object's attributes.
3. Define other methods to represent the behaviors of the object.
To create an object of the class, call the class as if it were a function.
Explanation:
1. Class Definition:
o The Car class has an __init__() method that initializes the make,
model, and year attributes.
o The display_details() method prints the details of the car.
2. Creating an Object:
o The object my_car is created from the Car class by passing values
for make, model, and year.
4. Write a python program to illustrate use of try except and finally block together CO3 2 BTL
Program: 2
try:
# Try block: Code that might raise an exception
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print(f"The result of {num1} / {num2} is {result}")
MOHAMMED ZAIN UL ABDEEN (160923748116)
except ZeroDivisionError:
# Except block: Handles division by zero
print("Error! Division by zero is not allowed.")
except ValueError:
# Except block: Handles invalid input
print("Error! Invalid input. Please enter valid numbers.")
finally:
# Finally block: This code will run regardless of an exception
print("Execution of try-except block is complete.")
Explanation:
• try: Attempts to execute the code that may raise an exception.
• except: Catches specific exceptions (like ZeroDivisionError or ValueError)
and handles them with a message.
• finally: Executes no matter what, for cleanup actions (like printing a message
here).
7. Write a program that creates a dictionary of cubes of odd numbers in the range CO3 2 BTL
1-10 2
To create a dictionary of cubes of odd numbers in the range 1-10, we can use a
dictionary comprehension or a simple loop to iterate through the odd numbers and
calculate their cubes.
Program:
# Create a dictionary using dictionary comprehension
odd_cubes = {x: x**3 for x in range(1, 11) if x % 2 != 0}
# Print the dictionary
print(odd_cubes)
Explanation:
• The range(1, 11) generates numbers from 1 to 10.
• The if x % 2 != 0 filters out the odd numbers.
• The x**3 calculates the cube of each odd number.
• The dictionary comprehension {x: x**3 for x in range(1, 11) if x % 2 != 0}
creates a dictionary where each key is an odd number and the value is its
cube.
Output:
{1: 1, 3: 27, 5: 125, 7: 343, 9: 729}
8. Write Python snippet that validates name and age as entered by the user to CO3 2 BTL
determine whether the person can cast vote or not. 2
The program will prompt the user to input their name and age, and check if the person
is eligible to vote based on age. The legal voting age is assumed to be 18 or older.
Program:
# Input name and age from the user
name = input ("Enter your name: ")
age = int (input("Enter your age: "))
# Check if the person is eligible to vote
if age >= 18:
print(f"{name}, you are eligible to vote.")
else:
print(f"{name}, you are not eligible to vote.")
Explanation:
• The program first takes the user's name and age as input.
• The if age >= 18 condition checks if the user is 18 years or older, determining
eligibility to vote.
• Based on this condition, it prints a message indicating whether the person can
vote or not.
MOHAMMED ZAIN UL ABDEEN (160923748116)
Sample Output:
1. Eligible to Vote:
Enter your name: Alice
Enter your age: 20
Alice, you are eligible to vote.
2. Not Eligible to Vote:
Enter your name: Bob
Enter your age: 16
Bob, you are not eligible to vote.
This simple validation ensures that only users 18 or older are considered eligible
to vote.
9. Differentiate between error and exception CO3 2 BTL
Aspect Error Exception 2
Definition Serious issues Issues that occur during
preventing execution. execution, can be handled.
Types Syntax errors, Runtime errors like
indentation errors, etc. ZeroDivisionError,
FileNotFoundError.
Handling Cannot be handled Can be handled using try-
(usually leads to except blocks.
program failure).
Examples SyntaxError, ZeroDivisionError,
IndentationError ValueError
10. Explain Exception Handling in Python with suitable example program CO3 2 BTL
Exception handling in Python allows the programmer to manage errors or exceptional 1
situations that occur during the program's execution, preventing the program from
terminating abruptly. It is done using the try, except, else, and finally blocks.
Components of Exception Handling:
1. try block: Contains the code that may raise an exception.
2. except block: Executes code if an exception occurs in the try block.
3. else block: Executes code if no exception occurs (optional).
4. finally block: Executes code regardless of whether an exception occurred or
not (optional).
Example Program:
try:
# Try to open a file and read it
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
print(f"The result of division is: {result}")
except ZeroDivisionError:
# Catch division by zero exception
print("Error: Division by zero is not allowed!")
except ValueError:
# Catch invalid input (non-integer input) exception
print("Error: Invalid input! Please enter integers.")
else:
# Executes if no exception occurred
print("Division was successful.")
finally:
# This block always executes, used for cleanup
print ("Execution completed.")
Summary:
• try: Code that might raise an exception.
• except: Handles specific exceptions if they occur.
• else: Executes if no exceptions occur.
• finally: Always executes, typically for cleanup actions.
11. Discuss Function Polymorphism in Python with suitable example program, CO3 2 BTL
Polymorphism is a concept in Object-Oriented Programming (OOP) that allows a 1
single function or method to behave differently based on the input or context. In
Python, function polymorphism enables functions to be used with different data types,
and the same function can work in different ways based on the parameters passed.
MOHAMMED ZAIN UL ABDEEN (160923748116)
Key Concept:
• Polymorphism in Python occurs when a function or method has the same
name but behaves differently depending on the arguments passed.
• Python supports dynamic polymorphism, where the method or function to be
called is determined at runtime.
Example Program:
# Function to add two numbers (polymorphism with numbers)
def add (a, b):
return a + b
# Function to concatenate two strings (polymorphism with strings)
def add (a, b):
return a + " " + b
# Function to combine two lists (polymorphism with lists)
def add (a, b):
return a + b
# Demonstrating polymorphism
print (add (10, 20)) # Adds two integers
print (add ("Hello", "World")) # Concatenates two strings
print (add ([1, 2], [3, 4])) # Combines two lists
Advantages of Polymorphism:
1. Code Reusability: The same function name can be used for different types of
operations, reducing the need to write redundant functions.
2. Flexibility: The behavior of a function changes dynamically based on the type
of data passed, allowing for more flexible code.
In conclusion, polymorphism allows a single function to process different types of
data, making the code more modular and adaptable. It is a key feature of object-
oriented design and helps achieve cleaner and more efficient code.
13. What is the use of Self in Python Class? Discuss with suitable example program CO3 2 BTL
2
elf is a special reference variable used in class methods to refer to the current instance
of the class. It is used to access the instance's attributes and methods within the class.
The self-keyword allows methods to refer to the object's own attributes and to
distinguish between instance variables and local variables.
Key Points about self:
1. Refers to the current instance: self is used to refer to the current instance of
the class and its attributes.
2. Required in instance methods: Every method within a class must have self
as its first parameter (though it is not passed explicitly when calling a
method).
3. Distinguishes instance variables from local variables: It is used to refer to
variables that belong to the instance of the class.
MOHAMMED ZAIN UL ABDEEN (160923748116)
Example Program:
class Person:
# Constructor to initialize name and age attributes
def __init__(self, name, age):
self.name = name # Instance variable
self.age = age # Instance variable
15. Explain Finally block in Python with suitable example program CO3 2 BTL
the finally block is used in exception handling to define a block of code that will 1
always be executed, regardless of whether an exception occurs or not. This is useful
for performing cleanup operations such as closing files, releasing resources, or making
sure that specific actions are taken (e.g., logging or closing network connections).
Key Points about finally:
1. Always Executed: Code in the finally block is always executed, even if an
exception is raised or handled in the try or except blocks.
2. Used for Cleanup: It is typically used to release resources (e.g., closing files,
database connections) after the code execution, whether it finishes normally
or with an error.
3. Precedes Exception Propagation: If an exception is raised and not handled,
the finally block is executed before the exception is propagated.
Syntax:
try:
# Code that may raise an exception
except SomeException as e:
# Handle exception
finally:
# Cleanup code (always executed)
MOHAMMED ZAIN UL ABDEEN (160923748116)
Summary:
• The finally block is used for code that must run after the execution of try and
except blocks, no matter if an exception was raised or not.
• It is typically used for clean-up activities, ensuring resources are released
properly.
This program can be expanded to handle multiple students, calculate grades, or store
additional details as needed.
Write a program that has a class Person storing name and date_of_birth of a
person. The program should subtract the DOB from today’s date to find the
person is eligible to vote or not
Program: -
from datetime import date, datetime
class Person:
def __init__ (self, name, date_of_birth):
self.name = name
# Convert date_of_birth string to datetime object
self.date_of_birth = datetime.strptime(date_of_birth, "%Y-%m-%d")
def is_eligible_to_vote(self):
# Calculate age
today = date. today()
age = today.year - self.date_of_birth.year - ((today.month, today.day) <
(self.date_of_birth.month, self.date_of_birth.day))
# Check voting eligibility
if age >= 18:
print(f"{self.name} is eligible to vote. Age: {age}")
else:
print(f"{self.name} is not eligible to vote. Age: {age}")
# Example usage
MOHAMMED ZAIN UL ABDEEN (160923748116)
# Creating a person object with name and date_of_birth
person1 = Person("Alice", "2005-06-15")
person2 = Person ("Bob", "1995-12-20")
# Check voting eligibility
person1.is_eligible_to_vote ()
person2.is_eligible_to_vote ()
Output:
For the above code, assuming today's date is 2025-01-08:
Alice is not eligible to vote. Age: 19
Bob is eligible to vote. Age: 29
This program can be expanded to handle multiple students, calculate grades, or store
additional details as needed.
3. Write a Python program to create a Class person which includes attributes CO3 6,6 BT
name, country and date of birth. Implement a method to determine the person's CO3 L6
age.
Program: -
from datetime import date
class Person:
def __init__(self, name, country, date_of_birth):
"""
Constructor to initialize the attributes of the person.
: param name: Name of the person
: param country: Country of the person
: param date_of_birth: Date of birth (format: YYYY-MM-DD)
"""
self.name = name
self.country = country
self. date_of_birth = date_of_birth
MOHAMMED ZAIN UL ABDEEN (160923748116)
def calculate_age(self):
"""
Method to calculate the age of the person.
: return: Age in years
"""
birth_year, birth_month, birth_day = map(int, self.date_of_birth.split('-'))
dob = date(birth_year, birth_month, birth_day)
today = date.today()
age = today.year - dob.year - ((today.month, today.day) < (dob.month,
dob.day))
return age
def display_info(self):
"""
Display the person's information along with the calculated age.
"""
print (f"Name: {self.name}")
print (f"Country: {self.country}")
print (f"Date of Birth: {self.date_of_birth}")
print (f"Age: {self. calculate_age ()} years")
# Example usage
person1 = Person ("Alice", "USA", "1990-05-15")
person2 = Person ("Bob", "UK", "1985-10-25")
# Display information for both persons
person1.display_info ()
print ()
person2.display_info ()
Output:
Name: Alice
Country: USA
Date of Birth: 1990-05-15
Age: 34 years
Name: Bob
Country: UK
Date of Birth: 1985-10-25
Age: 39 years
This program is flexible and can handle multiple persons' data by creating instances
of the Person class.
def calculate_age(self):
"""
Method to calculate the age of the person.
: return: Age in years
"""
birth_year, birth_month, birth_day = map(int, self.date_of_birth.split('-'))
dob = date(birth_year, birth_month, birth_day)
today = date.today()
age = today.year - dob.year - ((today.month, today.day) < (dob.month,
dob.day))
return age
def display_info(self):
"""
Display the person's information along with the calculated age.
"""
print (f"Name: {self.name}")
print (f"Country: {self.country}")
print (f"Date of Birth: {self.date_of_birth}")
print (f"Age: {self. calculate_age ()} years")
# Example usage
person1 = Person ("Alice", "USA", "1990-05-15")
person2 = Person ("Bob", "UK", "1985-10-25")
# Display information for both persons
person1.display_info ()
print ()
person2.display_info ()
Output:
Name: Alice
Country: USA
Date of Birth: 1990-05-15
Age: 34 years
Name: Bob
Country: UK
Date of Birth: 1985-10-25
Age: 39 years
This program is flexible and can handle multiple persons' data by creating instances
of the Person class.
MOHAMMED ZAIN UL ABDEEN (160923748116)
5. Analysis differences between a List and a Dictionary
Aspect List Dictionary CO3 4,4 BT
Definition Ordered collection of Unordered collection of CO3 ,4 L4
items. key-value pairs. CO3
Access Access elements by Access values by keys.
index.
Syntax Created using square Created using curly braces
brackets []. {} with key: value.
Example list = [1, 2, 3] dict = {"a": 1, "b":
2, "c": 3}
Mutability Mutable (elements Mutable (keys and values
can be modified). can be modified).
Duplicate Allows duplicate Keys must be unique, but
Elements elements. values can duplicate.
Order Ordered (since Ordered (since Python
Python 3.7). 3.7).
Use Case Suitable for Suitable for structured data
sequential data with key-value pairs.
storage.
Write a program that has a dictionary of names of students and a list of marks in BT
4 subjects. L3
# Dictionary of student names with their marks in 4 subjects
students_marks = {
"Alice": [85, 90, 78, 92],
"Bob": [78, 81, 69, 75],
"Charlie": [92, 88, 84, 80],
"David": [76, 85, 80, 87]
}
# Function to display student marks and calculate the average
def display_marks_and_average():
for student, marks in students_marks.items():
total_marks = sum(marks)
average_marks = total_marks / len(marks)
print(f"{student}: Marks = {marks}, Total = {total_marks}, Average =
{average_marks:.2f}")
# Display the marks and average for each student
display_marks_and_average()
Output:
Alice: Marks = [85, 90, 78, 92], Total = 345, Average = 86.25
Bob: Marks = [78, 81, 69, 75], Total = 303, Average = 75.75
Charlie: Marks = [92, 88, 84, 80], Total = 344, Average = 86.00
David: Marks = [76, 85, 80, 87], Total = 328, Average = 82.00
This program demonstrates the use of dictionaries to store structured data and lists to
store marks in multiple subjects.
Create another dictionary that has name of the students and their total marks. BT
Find the topper and his/her score. L3
Program:-
# Dictionary of student names with their marks in 4 subjects
students_marks = {
"Alice": [85, 90, 78, 92],
"Bob": [78, 81, 69, 75],
"Charlie": [92, 88, 84, 80],
"David": [76, 85, 80, 87]
}
# Create a new dictionary to store total marks of students
students_total_marks = {}
# Calculate total marks for each student and store in the new dictionary
for student, marks in students_marks.items():
total_marks = sum(marks)
students_total_marks[student] = total_marks
# Find the topper (student with the highest total marks)
topper = max(students_total_marks, key=students_total_marks.get)
MOHAMMED ZAIN UL ABDEEN (160923748116)
topper_score = students_total_marks[topper]
# Display the topper and their total marks
print(f"The topper is {topper} with a total score of {topper_score}.")
Output:
The topper is Alice with a total score of 345.
6. What is python Class. Write Syntax for defining a class CO3 4,4 BT
In Python, a class is a blueprint for creating objects (instances). It defines attributes CO3 ,4 L2
(variables) and methods (functions) that are common to all objects of the class. A class CO3
serves as a template for objects and provides the structure for how data and behavior
should be organized.
Syntax for Defining a Class:
class ClassName:
# Constructor method (optional)
def __init__(self, parameter1, parameter2):
self.attribute1 = parameter1
self.attribute2 = parameter2
# Regular method
def method_name(self, param):
# Code for method
Pass
Key Points:
• Class: A blueprint for creating objects.
• __init__(): Constructor method that initializes an object’s attributes.
• self: Refers to the instance of the class.
• Attributes: Variables that belong to the object.
• Methods: Functions defined inside a class to define behaviors of the object.
Classes are fundamental in object-oriented programming (OOP) and provide a way to
structure and organize code effectively.
Discuss how to access dictionary items. Illustrate the use of get ( ), keys (), BT
values( ), items( ) in dictionary with suitable example program for each L2
Here’s a brief explanation of how to access dictionary items using get(), keys(),
values(), and items() methods:
1. get() Method:
• Purpose: Retrieves the value associated with a specified key. If the key
doesn't exist, returns None (or a default value if provided).
• Syntax: dict.get(key, default=None)
Example:
my_dict = {'a': 10, 'b': 20}
print(my_dict.get('a')) # 10
print(my_dict.get('z', "Not found")) # "Not found"
2. keys() Method:
• Purpose: Returns a view object that displays all the keys in the dictionary.
• Syntax: dict.keys()
Example:
my_dict = {'a': 10, 'b': 20}
print (my_dict. Keys()) # dict_keys(['a', 'b'])
3. values () Method:
• Purpose: Returns a view object that displays all the values in the
dictionary.
• Syntax: dict.values()
Example:
my_dict = {'a': 10, 'b': 20}
print(my_dict. Values()) # dict_values([10, 20])
4. items() Method:
• Purpose: Returns a view object with key-value pairs as tuples.
• Syntax: dict.items()
Example:
my_dict = {'a': 10, 'b': 20}
print(my_dict. items ()) # dict_items([('a', 10), ('b', 20)])
Summary:
• get(): Access value by key safely.
• keys(): Get all keys.
• values(): Get all values.
• items(): Get key-value pairs.
Example Program:
# Sample dictionary
student_marks = {'Alice': 85, 'Bob': 90, 'Charlie': 78}
# Traverse through keys
print("Keys:")
for key in student_marks:
print(key)
# Traverse through values
print("\nValues:")
for value in student_marks.values():
print(value)
# Traverse through key-value pairs
print("\nKey-Value Pairs:")
for key, value in student_marks.items():
print(f"{key}: {value}")
Output:
Keys:
Alice
Bob
Charlie
Values:
85
90
78
Key-Value Pairs:
Alice: 85
Bob: 90
Charlie: 78
Key Notes:
• for key in dict: Iterates through keys.
• dict.values(): Use to traverse values.
• dict.items(): Use to traverse both keys and values as pairs.
This allows flexibility when working with dictionary elements depending on your
requirements.
2. union()
• Purpose: Returns a set containing all unique elements from two or more sets.
Example:
python
Copy code
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # {1, 2, 3, 4, 5}
3. issubset()
• Purpose: Checks if a set is a subset of another set.
Example:
python
Copy code
set1 = {1, 2}
set2 = {1, 2, 3, 4}
MOHAMMED ZAIN UL ABDEEN (160923748116)
print(set1.issubset(set2)) # True
4. difference()
• Purpose: Returns the elements present in the first set but not in the second set.
Example:
python
Copy code
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1.difference(set2)) # {1, 2}
5. update()
• Purpose: Adds elements from another set to the current set.
Example:
python
Copy code
set1 = {1, 2}
set2 = {3, 4}
set1.update(set2)
print(set1) # {1, 2, 3, 4}
6. discard()
• Purpose: Removes an element from a set, but does not raise an error if the
element is not present.
Example:
python
Copy code
set1 = {1, 2, 3}
set1.discard(2)
print(set1) # {1, 3}
set1.discard(5) # No error
7. issuperset()
• Purpose: Checks if a set contains all elements of another set.
Example:
python
Copy code
set1 = {1, 2, 3, 4}
set2 = {2, 3}
print(set1.issuperset(set2)) # True
8. remove()
• Purpose: Removes a specific element from a set. Raises an error if the element
is not present.
Example:
python
Copy code
set1 = {1, 2, 3}
set1.remove(2)
print(set1) # {1, 3}
# set1.remove(5) # Raises KeyError
10. Explain Single and multiple Inheritance in python with suitable example CO3 6, BT
program 6 L2
Inheritance in Python
Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that
allows a class to inherit properties and methods from another class. Python supports
single inheritance and multiple inheritance.
1. Single Inheritance
In single inheritance, a child class inherits from a single parent class.
Example:
# Parent class
class Animal:
def speak(self):
return "Animal speaks"
# Child class
class Dog(Animal):
def speak(self):
return "Dog barks"
MOHAMMED ZAIN UL ABDEEN (160923748116)
# Create objects
dog = Dog()
print(dog.speak()) # Output: Dog barks
Explanation:
• The Dog class inherits from the Animal class.
• The child class can override methods from the parent class.
2. Multiple Inheritance
In multiple inheritance, a child class can inherit from more than one parent class.
Example:
# Parent class 1
class Parent1:
def func1(self):
return "This is Parent1"
# Parent class 2
class Parent2:
def func2(self):
return "This is Parent2"
# Child class inheriting from Parent1 and Parent2
class Child(Parent1, Parent2):
def func3(self):
return "This is Child"
# Create an object of Child class
child = Child()
print(child.func1()) # Output: This is Parent1
print(child.func2()) # Output: This is Parent2
print(child.func3()) # Output: This is Child
Explanation:
• The Child class inherits from both Parent1 and Parent2.
• The child class can access methods from both parent classes.
Key Differences
Feature Single Inheritance Multiple Inheritance
Number of Inherits from one Inherits from two or more parent
Parents parent class. classes.
Complexity Simple and easy to Can become complex with multiple
manage. parents.
Example Use Dog inherits from Child inherits features from
Case Animal. Mother and Father classes.
Both inheritance types are useful based on the problem you are trying to solve.
Multiple inheritance should be used with care to avoid complexity like the diamond
problem, which Python handles using the Method Resolution Order (MRO).
Summary
Polymorphism in Python is a powerful concept that allows the same interface to work
with different underlying forms, making the code more modular and extensible.
10. Write a python snippet to Drop a table,explain with example? CO4 2 BTL2
Python Snippet to Drop a Table:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost", user="your_username",
password="your_password", database="your_database"
)
cursor = conn.cursor()
# SQL query to drop a table
cursor.execute("DROP TABLE IF EXISTS students;")
# Commit and close
conn.commit()
cursor.close()
conn.close()
Explanation:
This Python snippet connects to a MySQL database and uses the
DROP TABLE command to permanently delete the students table
from the database. The IF EXISTS clause ensures that the query
doesn't throw an error if the table doesn't exist.
12. Write a python snippet to CREATE DATABASE Using MySQL? CO4 2 BTL2
Python Snippet to Create a Database:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost", user="your_username",
password="your_password"
)
cursor = conn.cursor()
# SQL query to create a database
cursor.execute("CREATE DATABASE IF NOT EXISTS
mydatabase;")
# Close connection
cursor.close()
conn.close()
MOHAMMED ZAIN UL ABDEEN (160923748116)
13. Write a python snippet to DISPLAY DATABASE Using MySQL? CO4 2 BTL2
Python Snippet to Display Databases:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost", user="your_username",
password="your_password"
)
cursor = conn.cursor()
# SQL query to show databases
cursor.execute("SHOW DATABASES;")
# Fetch and display all databases
for database in cursor:
print(database)
# Close connection
cursor.close()
conn.close()
14. Write a python snippet to DROP DATABASE Using MySQL? CO4 2 BTL1
Python Snippet to Drop a Database:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost", user="your_username",
password="your_password"
)
cursor = conn.cursor()
# SQL query to drop a database
cursor.execute("DROP DATABASE IF EXISTS mydatabase;")
# Commit and close
conn.commit()
cursor.close()
conn.close()
15 Write any 2 DML commands? CO4 2 BTL1
Two DML (Data Manipulation Language) Commands:
1. INSERT:
Used to add new records into a table.
o Example:
INSERT INTO students (id, name, age) VALUES (1, 'Alice', 20);
2. UPDATE:
Used to modify existing records in a table.
o Example:
UPDATE students SET age = 21 WHERE id = 1;
LAQ’s
All questions carry 12 marks
1. Explain about using database in python? Write a Python Program CO4 12 BTL2
to connect to MySQL database using MySQL?
➢ To build the real-world applications, connecting with the databases
is the necessity for the programming languages.
However, python allows us to connect our application to the databases
like SQLite, MySQL, Oracle, Sybase, PostgreSQL etc
MOHAMMED ZAIN UL ABDEEN (160923748116)
➢ Python also supports Data Definition Language (DDL), Data
Manipulation Language (DML) and Data Query Statements.
➢ Data is stored in a collection of tables with each table consisting of a
set of rows and columns. This is similar to how data is stored in
SQLite. To interact with the data stored in tables we use a special-
purpose programming language called SQL.
Python Program to Connect to MySQL Database:
import mysql.connector
# Establishing the connection to MySQL
connection = mysql.connector.connect(
host="localhost",
user="root", # your MySQL username
password="your_password", # your MySQL password
database="your_database" # the database you want to connect to )
# Creating a cursor object to interact with the database
cursor = connection.cursor()
# Execute a simple query to verify the connection
cursor.execute("SELECT DATABASE()")
result = cursor.fetchone()
print("Connected to database:", result)
# Closing the cursor and connection
cursor.close()
connection.close()
2 (a)Following Python code show how to use DELETE statement to CO4 6 BTL2
delete any record?
Python Snippet to Use DELETE Statement:
6
import mysql.connector BTL2
# Establish connection
conn = mysql.connector.connect(
host="localhost", user="your_username",
password="your_password", database="your_database"
)
cursor = conn.cursor()
# SQL query to delete a record
cursor.execute("DELETE FROM students WHERE id = 1;")
# Commit and close
conn.commit()
cursor.close()
conn.close()
Explanation:
This snippet connects to a MySQL database and uses the DELETE
SQL command to remove the record from the students table where
the id is 1. After executing the query, the changes are committed, and
the connection is closed.
*************
(b) Update existing records in a table by using the "UPDATE"
statement?
Python Snippet to Use UPDATE Statement:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost", user="your_username",
password="your_password", database="your_database"
)
cursor = conn.cursor()
# SQL query to update existing records
cursor.execute("UPDATE students SET age = 22 WHERE id = 1;")
# Commit and close
conn.commit()
MOHAMMED ZAIN UL ABDEEN (160923748116)
cursor.close()
conn.close()
Explanation:
This snippet connects to a MySQL database and uses the UPDATE
SQL command to modify the age column of the record in the students
table where the id is 1. The change is committed to the database
before closing the connection.
3. (a) Write a Python programme, show how to use ALTER TABLE CO4 6 BTL2
using MySQL?
Python Program to Use ALTER TABLE Command: 6
import mysql.connector BTL2
# Establish connection
conn = mysql.connector.connect(
host="localhost", user="your_username",
password="your_password", database="your_database"
)
cursor = conn.cursor()
# SQL query to alter table (add a new column)
cursor.execute("ALTER TABLE students ADD COLUMN grade
VARCHAR(5);")
# Commit and close
conn.commit()
cursor.close()
conn.close()
Explanation:
This program uses the ALTER TABLE statement to modify the
students table by adding a new column named grade of type
VARCHAR(5). The changes are committed and the connection is
closed.
*****************
(b) Write a Python code show how to use RENAME Command
using MySQL?
Python Program to Use RENAME Command:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost", user="your_username",
password="your_password", database="your_database"
)
cursor = conn.cursor()
# SQL query to rename a table
cursor.execute("RENAME TABLE students TO pupils;")
# Commit and close
conn.commit()
cursor.close()
conn.close()
Explanation:
This program renames the table students to pupils using the
RENAME TABLE command. The change is committed to the
database before closing the connection.
MOHAMMED ZAIN UL ABDEEN (160923748116)
4. Describe briefly about MYSQL? Write a Python program to CO4 12 BTL2
CREATE and DISPLAY database using MySQL?
Python Program to CREATE and DISPLAY a Database:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost", user="your_username",
password="your_password"
)
cursor = conn.cursor()
# Create a new database
cursor.execute("CREATE DATABASE IF NOT EXISTS school;")
print("Database 'school' created successfully.")
# Display all databases
cursor.execute("SHOW DATABASES;")
print("Databases:")
for db in cursor:
print(db[0])
# Close connection
cursor.close()
conn.close()
Explanation:
1. Create Database: The CREATE DATABASE statement
creates a new database named school.
2. Display Databases: The SHOW DATABASES command
retrieves and lists all available databases.
3. The connection and cursor are closed to release resources.
5 Write a python program to CREATE table, INSERT values and CO4 12 BTL6
modify /update the data of the MySQL table "student", and
display the result?
Python Program to CREATE Table, INSERT Values,
MODIFY/UPDATE Data, and Display Results:
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost", user="your_username",
password="your_password", database="your_database"
)
cursor = conn.cursor()
# Step 1: Create the "student" table
cursor.execute("""
CREATE TABLE IF NOT EXISTS student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100),
age INT,
marks INT
);
""")
print("Table 'student' created successfully.")
# Step 2: Insert values into the table
insert_query = "INSERT INTO student (name, age, marks) VALUES
(%s, %s, %s)"
values = [
("Alice", 20, 85),
("Bob", 22, 90),
("Charlie", 21, 88)
]
cursor.executemany(insert_query, values)
MOHAMMED ZAIN UL ABDEEN (160923748116)
conn.commit()
print("Values inserted into the 'student' table.")
# Step 3: Update the data in the table
update_query = "UPDATE student SET marks = 95 WHERE name =
'Alice';"
cursor.execute(update_query)
conn.commit()
print("Data updated successfully.")
# Step 4: Display the table content
cursor.execute("SELECT * FROM student;")
print("Table 'student' content:")
for row in cursor.fetchall():
print(row)
# Close connection
cursor.close()
conn.close()
Explanation:
1. CREATE Table: The program creates the student table with
columns id, name, age, and marks.
2. INSERT Values: The INSERT INTO statement adds three
rows to the table.
3. MODIFY/UPDATE Data: The UPDATE statement modifies
Alice's marks to 95.
4. DISPLAY Results: The SELECT statement retrieves and
displays all rows from the student table.
Output:
Table 'student' created successfully.
Values inserted into the 'student' table.
Data updated successfully.
Table 'student' content:
(1, 'Alice', 20, 95)
(2, 'Bob', 22, 90)
(3, 'Charlie', 21, 88)
7 What is the difference between DML and DDL operations with CO4 12 BTL4
database?
9 (a) How to Connect Python with SQL Database:- CO4 6,6 BTL3
1. Import Required Module: Use the mysql.connector or sqlite3
module to connect Python to SQL databases. For MySQL, you
BTL2
might use mysql-connector-python.
2. Establish a Connection: Use the connect() method with
necessary credentials like hostname, username, password, and
database name.
3. Create a Cursor Object: The cursor object is used to execute
SQL commands.
4. Execute Queries: Use cursor.execute() to execute SQL
commands.
5. Fetch Results (if needed): Use fetchall() or fetchone() to
retrieve query results.
6. Close the Connection: Always close the database connection
using connection.close().
Example Code:
import mysql.connector
# Connect to the database
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="my_database"
)
cursor = connection.cursor()
# Execute a query
cursor.execute("SELECT * FROM students")
# Fetch results
results = cursor.fetchall()
for row in results:
print(row)
# Close connection
connection.close()
****************
(b) Explain the steps in installing packages via PIP?
Steps to Install Packages via PIP
1. Ensure PIP is Installed:
o PIP is usually installed by default with Python. Check
using:
pip --version
2. Install a Package:
o Use the command:
pip install <package_name>
Example:
pip install numpy
MOHAMMED ZAIN UL ABDEEN (160923748116)
3. Upgrade a Package:
o Upgrade to the latest version of a package:
pip install --upgrade <package_name>
4. List Installed Packages:
o Check all installed packages:
pip list
5. Uninstall a Package:
o Remove a package:
pip uninstall <package_name>
6. Install from Requirements File:
o Use a requirements file to install multiple packages:
pip install -r requirements.txt
Example Command:
pip install pandas
Unit5:
2 How do you create a NumPy array from a Python list? CO5 2 BTL2
Provide an example.
You can create a NumPy array from a Python list using the np.array()
function.
Example:
import numpy as np
# Creating a Python list
python_list = [1, 2, 3, 4, 5]
# Converting Python list to NumPy array
numpy_array = np.array(python_list)
print(numpy_array)
Output: -
[1 2 3 4 5]
In this example, numpy_array is a NumPy array created from the
python_list.
3 What is a Pandas Series? How is it different from a NumPy array? CO5 2 BTL1
Pandas Series is a one-dimensional labeled array in Python that can hold
any data type (integers, strings, floats, Python objects, etc.). Each
element in a Series has an associated label (index), which provides easy
access and manipulation of data.
Differences between Pandas Series and NumPy Array:
1. Labels (Indexing):
o Series: Each element has a label (index), which allows
more flexibility in accessing data.
o NumPy array: Only uses integer-based indexing by
default, without labels.
MOHAMMED ZAIN UL ABDEEN (160923748116)
2. Data Types:
o Series: Can store mixed data types (integers, strings,
floats) in the same series.
o NumPy array: Typically stores elements of the same data
type (usually numerical values).
3. Functionality:
o Series: Comes with many built-in functions for data
manipulation (e.g., .mean(), .sum(), .apply()).
o NumPy array: Primarily designed for mathematical and
scientific computing, with limited data manipulation
functions.
9. Show how summary statistics functions used to summarize data in a CO5 2 BTL3
DataFrame? With an example.
import pandas as pd
# Sample DataFrame
data = {'Name': ['John', 'Alice', 'Bob', 'Charlie'],
'Age': [23, 25, 22, 28],
'Score': [85, 90, 78, 88]}
df = pd. DataFrame(data)
# Summary statistics
print (df. describe ()) # Gives count, mean, std, min, 25%, 50%, 75%, and max
print ("Mean Age:", df['Age']. mean ()) # Mean of 'Age' column
print ("Total Score:", df['Score']. sum ()) # Sum of 'Score' column
10. Explain data alignment in Pandas. CO5 2 BTL1
Data alignment in Pandas refers to the process of aligning data with respect to
its labels (indexes or column names) during operations between Series or
DataFrames. When performing operations on two or more objects, Pandas
automatically aligns the data based on the index or columns.
For example:
import pandas as pd
# Create two Series with different indexes
s1 = pd.Series([1, 2, 3], index= ['a', 'b', 'c'])
s2 = pd.Series([4, 5, 6], index= ['b', 'c', 'd'])
# Addition will align based on the index
result = s1 + s2
print(result)
MOHAMMED ZAIN UL ABDEEN (160923748116)
11. How does Pandas align data while performing operations on Series? Use CO5 2 BTL2
examples to illustrate this.
When performing operations on Series in Pandas, the data is aligned based on
the index. If an index is not present in one Series, the result will have NaN for
that index. Here's an example:
import pandas as pd
# Creating two Series with different indexes
s1 = pd.Series([10, 20, 30], index= ['a', 'b', 'c'])
s2 = pd.Series([5, 15, 25, 35], index= ['b', 'c', 'd', 'e'])
# Adding the two Series
result = s1 + s2
print(result)
12. How does Pandas align data while performing operations on DataFrames? CO5 2 BTL2
Use examples to illustrate this.
Pandas aligns data during operations on DataFrames by matching row indices
and column labels. If a row or column is missing in one DataFrame, the result
will have NaN for those positions. For example, when adding two DataFrames
with different indices and columns, Pandas aligns based on matching rows and
columns, filling missing entries with NaN.
Example: -
import pandas as pd
# Create two DataFrames with different indices and columns
df1 = pd. DataFrame ({
'A': [1, 2],
'B': [3, 4]
}, index=['a', 'b'])
df2 = pd.DataFrame({
'B': [5, 6],
'C': [7, 8]
}, index=['b', 'c'])
# Perform addition between the two DataFrames
result = df1 + df2
print(result)
13. Using numpy formulate the 3rd value of 2nd vector from the array CO5 2 BTL3
[[1,2,3],[2.3.4],[3,4,5]]?
The 3rd value of the 2nd vector from the array [[1, 2, 3], [2, 3, 4], [3, 4, 5]] is 4.
import numpy as np
# Create the array
arr = np. array([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
# Access the 3rd value of the 2nd vector (index 1 for vector, index 2 for
value)
value = arr [1, 2]
value
14. Which libraray is superior numpy or pandas? CO5 2 BTL2
The choice between NumPy and Pandas depends on the specific use case:
• NumPy is superior for numerical operations and mathematical
computations on large, multi-dimensional arrays and matrices. It
provides high performance and is widely used for scientific computing
tasks, where efficiency is crucial.
• Pandas is built on top of NumPy and provides higher-level data
structures, like Series and DataFrames, which are better suited for
handling labeled data (e.g., time series, spreadsheets). It is more versatile
for data manipulation, cleaning, and analysis in a structured tabular
format.
In short, NumPy is more efficient for raw numerical computation, while
Pandas is preferred for working with structured datasets and performing
complex data operations.
MOHAMMED ZAIN UL ABDEEN (160923748116)
15. Explain what is group by in pandas? CO5 2 BTL1
In Pandas, the groupby() function is used to split the data into groups based on
some criteria (such as column values), perform operations on each group
independently, and then combine the results back into a DataFrame or Series.
It’s particularly useful for:
1. Grouping data by a particular column (or multiple columns).
2. Aggregating the data by performing operations like sum, mean, count,
etc., on each group.
3. Transforming or filtering data.
CO5
LAQ’s
All questions carry 12 marks
1. Discuss the core functionalities of NumPy. Write a Python program to CO5 12 BTL2
demonstrate array creation, indexing, and transposition.
Core Functionalities of NumPy:
NumPy is a fundamental library for scientific computing in Python.
Some of its core functionalities include:
1. Multi-dimensional arrays: NumPy provides the ndarray object to
store and manipulate multi-dimensional arrays.
2. Array operations: It supports element-wise operations (addition,
subtraction, multiplication, etc.) on arrays.
3. Array indexing: NumPy provides powerful tools for indexing and
slicing arrays.
4. Mathematical functions: NumPy includes a wide range of
mathematical functions like trigonometric, statistical, algebraic,
etc.
5. Linear algebra operations: It has built-in functions for matrix
multiplication, eigenvalue decomposition, etc.
6. Random number generation: NumPy has a random module for
generating random numbers.
Program to Demonstrate Array Creation, Indexing, and
Transposition:-
import numpy as np
# 1. Array Creation
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print ("Original Array:")
print(arr)
# 2. Indexing (Accessing a single element)
element = arr [1, 2] # Access the element at 2nd row, 3rd column
print ("\nAccessed Element at [1,2]:", element)
# 3. Slicing (Accessing a subarray)
subarray = arr [0:2, 1:3] # Get a 2x2 subarray
print ("\nSubarray (rows 0-1, columns 1-2):")
print(subarray)
# 4. Transposition (Reversing rows and columns)
transposed_arr = arr.T
print ("\nTransposed Array:")
print(transposed_arr)
Explanation:
• Array Creation: The np.array() function is used to create a 2D
array.
• Indexing: arr[1, 2] accesses the element at row 1 and column 2
(value 6).
• Slicing: arr[0:2, 1:3] retrieves the subarray from rows 0-1 and
columns 1-2.
• Transposition: The .T attribute returns the transposed version of
the array, swapping rows and columns.
import pandas as pd
# 1. Create a DataFrame
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
MOHAMMED ZAIN UL ABDEEN (160923748116)
print(df_reindexed)
print(df_dropped)
Explanation:
4. Explain the process of data alignment in Pandas with an example CO5 12 BTL2
program. Include how Pandas aligns indices during operations.
Data Alignment in Pandas
Data alignment in Pandas refers to the process by which the indices
(both row and column labels) of two or more objects (Series or
DataFrames) are aligned when performing operations on them. If the
indices do not match, Pandas will align them based on the labels, filling
in missing values with NaN (Not a Number). This feature ensures that
the operations are applied correctly according to the matching labels.
Key Points:
• Row and column indices are aligned when performing operations
like addition, subtraction, etc.
• If an index from one object is missing in another, it will result in
NaN for that index in the result.
Example Program to Demonstrate Data Alignment:
import pandas as pd
# Create two Series with different indices
series1 = pd.Series([10, 20, 30], index=['a', 'b', 'c'])
series2 = pd.Series([1, 2, 3], index=['b', 'c', 'd'])
print("Series 1:")
print(series1)
print("\nSeries 2:")
print(series2)
# Perform an addition operation on the two Series
result = series1 + series2
print("\nResult of addition (aligned by index):")
print(result)
MOHAMMED ZAIN UL ABDEEN (160923748116)
5 a) What is the significance of handling missing data in CO5 6,6 BTL3
Pandas?
Significance of Handling Missing Data in Pandas:
1. Prevents Skewed Results: Missing data can distort
statistical measures like mean, median, or standard
deviation, leading to incorrect conclusions.
2. Ensures Accurate Calculations: Missing values can
affect mathematical and machine learning algorithms,
causing errors or biased predictions. Handling them
properly ensures valid results.
3. Avoids Errors in Functions: Many Pandas functions do
not work as expected when missing data exists. Handling
missing values helps prevent runtime errors during
operations.
4. Improves Data Integrity: Dealing with missing data
ensures the dataset is complete, maintaining its integrity
and reliability for analysis or modelling.
5. Supports Better Imputation: Handling missing data
allows you to fill gaps using imputation methods,
improving the dataset's completeness and minimizing
data loss.
6. Facilitates Smooth Data Cleaning: Proper handling
helps in cleaning datasets and ensures that they are ready
for further analysis or processing.
7. Flexible Approaches: Pandas provides several
techniques like filling (fillna()), dropping (dropna()), or
forward/backward filling (ffill()/bfill()) to handle missing
data, giving flexibility in how to deal with it.
***********
b) Write a program to detect, fill, and drop missing values in a
DataFrame.
Program:-
import pandas as pd
import numpy as np
# Create a DataFrame with missing values (NaN)
data = {'Name': ['John', 'Jane', 'Paul', np.nan],
'Age': [28, np.nan, 22, 35],
'City': ['New York', 'Paris', np.nan, 'London']}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
# a) Detect missing values (NaN)
print("\nDetect missing values:")
print(df.isna())
# b) Fill missing values with a specified value (e.g., 'Unknown' for
strings and 0 for numeric)
df_filled = df.fillna({'Name': 'Unknown', 'Age': 0, 'City': 'Unknown'})
print("\nDataFrame after filling missing values:")
print(df_filled)
# c) Drop rows with any missing values
df_dropped = df.dropna()
print("\nDataFrame after dropping rows with missing values:")
print(df_dropped)
Explanation:
1. Detecting Missing Values: The isna() function detects missing
values and returns a DataFrame of the same shape with True for
missing values and False otherwise.
2. Filling Missing Values: The fillna() function replaces missing
values with a specified value, like 'Unknown' for strings and 0
for numeric columns.
3. Dropping Missing Values: The dropna() function removes
rows with any missing values.
MOHAMMED ZAIN UL ABDEEN (160923748116)
6 Explain the concept of transposing an array in NumPy. How do you perform CO5 12 BTL1
array transposition for 1D, 2D, and multi-dimensional arrays? Provide
examples.
Transposing an array in NumPy refers to swapping its rows and columns. In a
2D array, transposing means converting the rows into columns and vice versa.
For higher-dimensional arrays, the concept of transposing involves permuting
the axes.
How to Perform Array Transposition:
1. For 1D Array:
o A 1D array doesn't have rows or columns, so transposing it
results in the same array. Essentially, it doesn't change.
Example:
import numpy as np
arr_1d = np. array ([1, 2, 3])
print (arr_1d. T) # Output: [1 2 3] (same array)
2. For 2D Array:
o In a 2D array, transposing swaps the rows and columns.
Example:
import numpy as np
arr_2d = np. array ([[1, 2, 3], [4, 5, 6]])
print(arr_2d.T)
# Output:
# [[1 4]
# [2 5]
# [3 6]]
3. For Multi-Dimensional Arrays:
o For multi-dimensional arrays, transposing involves rearranging
the axes. This can be achieved using np. transpose() or .T, where
the axes are permuted.
Example:
import numpy as np
arr_3d = np. array ([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(arr_3d.T)
# Output (shape changes accordingly depending on axis
permutation):
# [[[1 5]
# [3 7]]
#
# [[2 6]
# [4 8]]]
Summary:
• 1D Array: Transposition does not change the array.
• 2D Array: Swaps rows and columns.
• Multi-dimensional Array: Transposes the axes according to the
specified order.
7 Describe Array Processing in NumPy. How do you perform arithmetic CO5 12 BTL2
operations, broadcasting, and aggregate functions (like sum, mean, max) on
arrays? Provide examples.
program that demonstrates array processing in NumPy, including arithmetic
operations, broadcasting, and aggregate functions:
Example Program:
import numpy as np
# Creating two arrays
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Arithmetic operations (element-wise)
addition = arr1 + arr2
multiplication = arr1 * arr2
subtraction = arr1 - arr2
division = arr1 / arr2
# Broadcasting with a scalar
scalar = 5
broadcasted_addition = arr1 + scalar
# Aggregate functions
sum_val = np.sum(arr1)
mean_val = np.mean(arr1)
max_val = np.max(arr1)
min_val = np.min(arr1)
MOHAMMED ZAIN UL ABDEEN (160923748116)
# Displaying results
print ("Addition (arr1 + arr2):", addition)
print ("Multiplication (arr1 * arr2):", multiplication)
print ("Subtraction (arr1 - arr2):", subtraction)
print ("Division (arr1 / arr2):", division)
print ("Broadcasting (arr1 + scalar):", broadcasted_addition)
print ("Sum of arr1:", sum_val)
print ("Mean of arr1:", mean_val)
print ("Max of arr1:", max_val)
print ("Min of arr1:", min_val)
Explanation:
1. Arithmetic Operations:
o The program adds, multiplies, subtracts, and divides the two
arrays element-wise.
o For example, arr1 + arr2 will add corresponding elements from
both arrays (1+4, 2+5, 3+6).
2. Broadcasting:
o The scalar 5 is added to each element of arr1 using broadcasting.
This operation adds 5 to each element of the array, resulting in
[6, 7, 8].
3. Aggregate Functions:
o Sum: np.sum(arr1) calculates the sum of all elements in arr1
(1+2+3 = 6).
o Mean: np. mean(arr1) computes the mean of the array (average
of 1, 2, and 3).
o Max: np.max(arr1) returns the maximum value in arr1.
o Min: np.min(arr1) returns the minimum value in arr1.
8 a) Explain the concept of a Series in Pandas. How is a Series created, CO5 6,6 BTL1
and what are its key attributes and methods?
A Series is a one-dimensional labeled array in Pandas that can hold any
data type (integers, floats, strings, etc.). It is similar to a list or a NumPy
array but with an added feature of indexing. Each element in the Series
is associated with an index label, which makes it more powerful and
flexible than regular arrays or lists.
Key Attributes of a Series:
1. Data: The actual data values stored in the Series.
2. Index: Labels corresponding to each element. If not specified,
an integer index is created by default.
3. dtype: The data type of the Series (e.g., int, float, object).
Key Methods of a Series:
• head(): Returns the first few rows.
• tail(): Returns the last few rows.
• describe(): Provides summary statistics.
• sum(), mean(), min(), max(): Basic aggregation methods.
• value_counts(): Counts occurrences of unique elements.
Example of Series Creation and Attributes:
import pandas as pd
# Creating a Series
data = [10, 20, 30, 40, 50]
index_labels = ['a', 'b', 'c', 'd', 'e']
series = pd.Series(data, index=index_labels)
# Displaying the Series
print("Series:\n", series)
# Accessing attributes
print("\nData:\n", series.values)
print("\nIndex:\n", series.index)
print("\nData type:\n", series.dtype)
# Using methods
print("\nSum of Series:", series.sum())
print("\nFirst 3 elements:\n", series.head(3))
*******************
MOHAMMED ZAIN UL ABDEEN (160923748116)
b) Provide examples. Discuss the differences between a Series and a list or
NumPy array.?
Differences between a Series and a List/NumPy Array:
1. Indexing:
o Series: Each element has a label or index (can be customized).
o List/NumPy Array: Only numerical (integer) indexing.
2. Data Types:
o Series: Can hold mixed data types but has a single data type for
all elements by default (like a column in a DataFrame).
o List: Can hold elements of mixed data types.
o NumPy Array: Homogeneous data type (all elements must be
of the same type).
3. Labeling:
o Series: Can have a custom index (labels).
o List/NumPy Array: Only uses positional indexing.
4. Performance:
o NumPy Arrays: More efficient for numerical operations due to
lower overhead.
o Series: Less efficient than NumPy arrays but provides more
flexibility with data manipulation and indexing.
Example of Differences:
import numpy as np
# List
lst = [10, 20, 30, 40, 50]
# NumPy Array
np_arr = np.array([10, 20, 30, 40, 50])
# Pandas Series
pd_series = pd.Series([10, 20, 30, 40, 50], index=['a', 'b', 'c', 'd', 'e'])
# Accessing elements
print("List element (index 2):", lst[2])
print("NumPy Array element (index 2):", np_arr[2])
print("Pandas Series element (index 'c'):", pd_series['c'])
9 What is the purpose of the reindex() function in Pandas? How does it CO5 12 BTL2
work, and why is it useful? Explain with a suitable example.
Purpose of the reindex() function in Pandas:
The reindex() function in Pandas is used to change or modify the index of a
DataFrame or Series. It allows you to align your data to a new set of labels
(index) or reorder the existing ones. This function is especially useful when you
need to match the index of a DataFrame with another dataset or modify the
order of rows/columns to match a new reference.
How reindex() Works:
• The reindex() function allows you to specify a new index (or row
labels) for your DataFrame or Series.
• If any index labels are missing in the new index, it will insert NaN
values in those places.
• If the new index is a subset of the original, it will drop the non-matching
labels.
Why it is Useful:
• Aligning data: It helps align data from different sources, even when
their indices do not match.
• Reordering: You can reorder rows or columns as per your needs.
• Handling missing data: The function helps handle missing data by
introducing NaN where necessary.
Example:
import pandas as pd
# Create a sample DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],
'Age': [25, 30, 35, 40]}
df = pd. DataFrame(data)
# Display the original DataFrame
print ("Original DataFrame:")
print(df)
# Reindexing the DataFrame to change the row labels
new_index = ['a', 'b', 'c', 'd']
df_reindexed = df. reindex(new_index)
# Display the reindexed DataFrame
print ("\nReindexed DataFrame:")
print(df_reindexed)
MOHAMMED ZAIN UL ABDEEN (160923748116)
Explanation:
• In this example, the reindex() function is used to change the row labels
(index) of the DataFrame from the default 0, 1, 2, 3 to a, b, c, d.
• As the new index does not match the original one, all the values are
replaced by NaN.
• You can reindex to a new set of labels or adjust the alignment of data
when required.
10 What is Index Hierarchy in Pandas? How can you create and manipulate CO5 12 BTL2
multi-level indices? Provide examples using hierarchical indexing in
DataFrames and Series.
Index Hierarchy in Pandas:
Index Hierarchy, or multi-level indexing, allows you to work with data that
has multiple levels of indices. This is especially useful for organizing data in a
nested and structured way, making it easier to perform complex data analysis.
Key Features:
1. Multi-level structure: A single index can have multiple levels (like a
tree structure).
2. Grouping and aggregation: It is useful for data that naturally has a
hierarchy (e.g., geographical regions, time-series data).
3. Data slicing: Allows you to easily access subsets of data using one or
more index levels.
Example:
import pandas as pd
# Creating a Multi-level Indexed Series
data = [10, 20, 30, 40]
index = [('A', 1), ('A', 2), ('B', 1), ('B', 2)]
series = pd. Series(data, index=pd.MultiIndex.from_tuples(index,
names=['Group', 'Subgroup']))
print("Multi-level Indexed Series:")
print(series)
# Creating a DataFrame with Multi-level Columns
data = {
('Math', 'Test 1'): [85, 90],
('Math', 'Test 2'): [88, 92],
('Science', 'Test 1'): [80, 86]
}
df = pd.DataFrame(data, index=['Alice', 'Bob'])
df.columns.names = ['Subject', 'Exam']
print("\nDataFrame with Multi-level Columns:")
print(df)
# Accessing Data in Multi-level Indices
print ("\nAccessing subgroup 1 of group A in Series:")
print (series.loc['A', 1])
print("\accessing Math Test 1 column in DataFrame:")
print (df['Math', 'Test 1'])
# Resetting Index in Series
print ("\nResetting index in Series:")
print (series. reset_index ())
Summary:
Index Hierarchy in Pandas allows for structured, multi-dimensional data
representation. It provides tools for slicing, grouping, and organizing data
efficiently. Use pd.MultiIndex to create hierarchical indices and manipulate
them with .reset_index() or .set_index() for easier handling.
MOHAMMED ZAIN UL ABDEEN (160923748116)