0% found this document useful (0 votes)
4 views

Python Programming Question Bank 1-5 Units With Answers

The document is a question bank for a Python Programming course at Lords Institute of Engineering and Technology for the academic year 2024-25. It includes short answer questions (SAQs) and long answer questions (LAQs) covering various Python concepts such as Boolean variables, type conversion, loop control statements, and string operations. Each question is associated with specific course outcomes (CO) and Bloom's Taxonomy levels (BTL).

Uploaded by

mdfawazali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Programming Question Bank 1-5 Units With Answers

The document is a question bank for a Python Programming course at Lords Institute of Engineering and Technology for the academic year 2024-25. It includes short answer questions (SAQs) and long answer questions (LAQs) covering various Python concepts such as Boolean variables, type conversion, loop control statements, and string operations. Each question is associated with specific course outcomes (CO) and Bloom's Taxonomy levels (BTL).

Uploaded by

mdfawazali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

MOHAMMED ZAIN UL ABDEEN (160923748116)

LORDS INSTITUTE OF ENGINEERING AND TECHNOLOGY

(UGC Autonomous Institution)


Approved by AICTE | Affiliated to Osmania University | Estd.2003 | Accredited ‘A’ grade by NAAC
Department of Computer Science Engineering- (AI/ML)

Academic Year: 2024-25 B.E. III SEMESTER

Name of the Course: Python Programming (Question Bank)

Date: 13 December 2024


QUESTION AND ANSWERS FOR UNIT-01

Q.No Question Unit-1 CO BTL


SAQ’s
All questions carry 2 marks.
1 How do you declare and use a Boolean variable in Python? CO1 2 BTL1
To declare and use a Boolean variable in Python:
1. Assign True or False to a variable:
is_active = True
2. Use it in a condition:
if is_active:
print("Active")
else:
print("Inactive")

2 Write a Python statement to convert an integer value to a string? CO1 2 BTL2


To convert an integer value to a string in Python, use the str() function:
integer_value = 42
string_value = str(integer_value)
3 Explain the concept of type conversion in Python with an example? CO2 2 BTL1
Type conversion in Python is the process of changing the data type of a value. It can
be:
1. Implicit Conversion: Python converts types automatically.
Example: -
result = 10 + 2.5 # int is automatically converted to float
print(result) # Output: 12.5
2. Explicit Conversion: Done manually using functions like int(), float(), or str().
Example:-
value = "123"
number = int(value) # Convert string to integer
print(number) # Output: 123
4 Explain the use of the break statement in a while loop with an example. CO1 2 BTL2
The break statement in a while loop is used to exit the loop prematurely, before the
loop condition becomes false. It terminates the loop immediately, and control is transferred to
the next statement after the loop.
Example:
count = 0
while count < 10:
print(count)
MOHAMMED ZAIN UL ABDEEN (160923748116)
count += 1
if count == 5:
break # Exits the loop when count reaches 5
Output:
0
1
2
3
4

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)

6 Write a Python expression that concatenates two strings? CO1 2 BTL3


To concatenate two strings in Python, you can use the + operator.
Example:
string1 = "Hello"
string2 = "World"
result = string1 + " " + string2 # Concatenates with a space in between
print(result)
Output:
Hello World
This expression combines string1 and string2 into one string with a space between them
7. Discuss string data types in Python. Explain at least three string operations with CO1 2 BTL2
code examples.
In Python, strings are sequences of characters, and they are immutable. Here are three
common string operations:
1. Concatenation: Combine strings using the + operator:
"Hello" + " " + "World” # Output: "Hello World"
2. Slicing: Extract a substring using string[start: end].
"Python"[0:3] # Output: "Pyt"
3. Length (len ()): Get the length of a string using len().
len("Hello”) # Output: 5

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

4. else with Loops:


The else block after a loop runs only if the loop completes without hitting a break
statement. It won’t execute if the loop is exited using break.
Example with no break:
for i in range (5):
MOHAMMED ZAIN UL ABDEEN (160923748116)
print(i)
else:
print ("Loop finished.") # Output: 0 1 2 3 4 Loop finished.

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.

13. Give 2 examples of type conversion in Python? CO1 2 BTL1


1. Converting from String to Integer:
You can convert a string representing a number to an integer using the int ()
function.
Example:
str_num = "123"
int_num = int(str_num) # Converts string to integer
print(int_num) # Output: 123
2. Converting from Integer to String:
You can convert an integer to a string using the str () function.
Example:
num = 456
str_num = str(num) # Converts integer to string
print(str_num) # Output: "456"

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

# Empty loop where pass is used to avoid errors


for i in range(5):
if i == 3:
pass # Do nothing when i is 3
else:
print(i)
MOHAMMED ZAIN UL ABDEEN (160923748116)
Output:
0
1
2
4
Explanation:
• Function and Method: The function feature_not_implemented() and the method
method_to_implement_later() are defined with pass because their implementation
is not yet available. Using pass prevents a syntax error when these are called or
invoked.
• Loop: Inside the loop, when i == 3, pass is used to do nothing and simply continue to
the next iteration. If we didn't use pass, it would cause a syntax error as the if block
would be empty.
Conclusion:
The pass statement is useful for creating placeholders in code when implementing parts
incrementally or when a syntactically required code block needs to be empty.
3. a)How does Python handle for loops? CO1 4,4,4 BTL2
Python for loop is used to iterate over a sequence (like a list, tuple, dictionary, string, or
range). The loop assigns each item in the sequence to a variable, and then executes the block
of code inside the loop for each item in the sequence. This is called iteration.

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

▪ Iterating over a String: Strings are also iterable, meaning you


can loop through each character.

for char in "hello": # process each character

▪ Using range() for Numeric Iteration: range() is commonly


used when you need to repeat an action a specific number of
times.
for i in range (5):
# i will take values from 0 to 4

▪ Iterating over a Dictionary: You can iterate over the keys,


values, or key-value pairs of a dictionary. my_dict = {'a': 1,
'b': 2} for key, value in
my_dict.items(): # process key-value
pair
▪ Iterating over Multiple Sequences: You can use the zip()
function to iterate over multiple sequences simultaneously.
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
MOHAMMED ZAIN UL ABDEEN (160923748116)
for num, letter in zip(list1, list2): # process each pair from
list1 and list2

***************

• Provide a sample program that prints each element of a list.


c) Sample Program to Print Each Element of a List:
my_list = [10, 20, 30, 40, 50] for
element in my_list:
print(element)
Output:
10
20
30
40
50
Explanation:
• The program iterates over each element in the list my_list and prints each element in
a new line.

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

Feature % Operator .format() Method f-strings (formatted


string literals)
Introduction Oldest method, Introduced in Python Introduced in Python 3.6
C-style 3
Syntax % placeholders {} placeholders {} placeholders within
f"string"
Readability Less readable More readable Most readable
Flexibility Limited Flexible with named Most flexible, allows
arguments inline expressions
Performance Slower for large Slightly better Fastest
strings

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

def increment_counter ():


global counter # Declare that we are modifying the global variable
counter += 1 # Modify the global variable
print(f"Counter inside function: {counter}")
increment_counter () # Output: Counter inside function: 1
print (f"Counter outside function: {counter}") # Output: Counter outside function: 1
Explanation:
• Without the global keyword, attempting to modify a global variable inside a function
will result in the creation of a new local variable with the same name, leaving the
global variable unchanged.

10 a) Describe how Python’s exception handling works. CO1 4,4,4 BTL2


Python uses a structured mechanism to handle runtime errors (exceptions) that might disrupt
normal program flow. The exception handling process includes:
1. Raising an Exception: An error occurs (e.g., ValueError, TypeError).
2. Catching the Exception: Using try and except blocks to intercept and handle the
error.
3. Executing Cleanup Code: Using the finally block to execute code that should run
regardless of whether an exception occurred.
***************
b) What are try, except and finally blocks used for?
MOHAMMED ZAIN UL ABDEEN (160923748116)
try Block:
• Used to wrap code that might raise an exception.
• If an error occurs, the try block exits immediately, and the except block executes.
except Block:
• Handles the specific exception that was raised.
• Multiple except blocks can be used to handle different types of exceptions.
finally Block:
• Always executes after the try block, whether an exception occurred or not.
• Useful for cleanup operations (e.g., closing files or releasing resources).

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?

1. Handling Specific Exceptions


Example: ValueError, TypeError, and IndexError
try:
value = int (input ("Enter a number: ")) # Might raise ValueError
result = 10 / value # Might raise ZeroDivisionError
my_list = [1, 2, 3]
print(my_list[value]) # Might raise IndexError
except ValueError:
print("Invalid input! Please enter a valid integer.")
except TypeError:
print("Type error! Ensure you're using compatible types.")
except IndexError:
print ("Index out of range! Enter a valid index.")
except ZeroDivisionError:
print ("Cannot divide by zero.")
finally:
print ("Execution complete.")

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

5 State indexing and negative indexing in Tuple. CO 2 BTL2


Indexing and Negative Indexing in Tuples (2 Marks) 2
1. Indexing:
o Access tuple elements using their position (index),
starting from 0 for the first element.
o Syntax: tuple[index].
Example:
my_tuple = (10, 20, 30)
print (my_tuple [1]) # Output: 20
2. Negative Indexing:
o Access elements from the end of the tuple using
negative indices.
o -1 represents the last element, -2 the second last, and so
on.
Example:
my_tuple = (10, 20, 30)
print (my_tuple [-1]) # Output: 30

6 What is the output of print tuple [1:3] CO 2 BTL3


if tuple = (‘abcd', 786, 2.23, 'john', 70.2)? 2
Given Tuple:
tuple = ('abcd', 786, 2.23, 'john', 70.2)
Code:
print(tuple[1:3])
Explanation:
• Slicing tuple[1:3]:
o Starts at index 1 (element: 786).
o Stops before index 3 (element: 'john').
o Includes elements at indices 1 and 2.
Output:
(786, 2.23)

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

9. What is the purpose of _doc string in Python. CO 2 BTL2


A docstring in Python is a special string that is used to document a 2
module, class, method, or function. It provides information about what
the code does, making it easier for others (and yourself) to understand
and maintain the code. Docstrings are enclosed in triple quotes (""" or
''') and are placed immediately after the function, method, class, or
module definition.
Key Points:
1. Documentation: Helps to describe the purpose and behavior of
the code.
2. Access: Can be accessed using the help() function or the
.__doc__ attribute.

Why Use Docstrings?


• Code Readability: Helps other developers understand your
code.
• Auto-Documentation: Tools like Sphinx can generate
documentation automatically from docstrings.

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

13. Write a recursive python snippet to calculate Fibonacci series up to CO 2 BTL2


nth numbers. 2
A recursive function to calculate the Fibonacci series up to the nth
number can be written as follows:
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)

# Example to print Fibonacci series up to nth number


n = 10 # Example value for nth number
for i in range(n):
MOHAMMED ZAIN UL ABDEEN (160923748116)
print(fibonacci(i), end=" “) # Prints Fibonacci series
Explanation:
• The function Fibonacci(n) returns the nth Fibonacci number.
• The base case is Fibonacci (0) or Fibonacci (1) which returns
0 or 1.
• The function calls itself recursively for n-1 and n-2 to compute
the Fibonacci series.
Output (for n = 10):
0 1 1 2 3 5 8 13 21 34
14. Write a snippet to remove an element from a list and from a tuple CO 2 BTL2
1. Remove an Element from a List: 2
In Python, lists are mutable, so you can use the remove() method to
remove an element.
# List example
my_list = [1, 2, 3, 4, 5]
# Remove element (e.g., 3) from the list
my_list. Remove(3)
print(my_list) # Output: [1, 2, 4, 5]
2. Remove an Element from a Tuple:
Tuples are immutable, so you cannot directly remove elements from a
tuple. However, you can convert the tuple to a list, remove the element,
and convert it back to a tuple.
# Tuple example
my_tuple = (1, 2, 3, 4, 5)
# Convert tuple to list, remove element (e.g., 3), and convert back
to tuple
temp_list = list(my_tuple)
temp_list.remove(3)
my_tuple = tuple(temp_list)
print(my_tuple) # Output: (1, 2, 4, 5)
Summary:
• List: Use remove () method.
• Tuple: Convert to a list, remove the element, then convert back
to a tuple.

15. Write a snippet to append an item to a dictionary CO 2 BTL2


and to a set? 2
1. Append an Item to a Dictionary:
To add an item to a dictionary, you can use the assignment
syntax (dictionary[key] = value).
# Dictionary example
my_dict = {'name': 'John', 'age': 30}
# Append a new item to the dictionary
my_dict['city'] = 'New York'
print(my_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New
York'}
2. Append an Item to a Set:
To add an item to a set, you can use the add () method.
# Set example
my_set = {1, 2, 3, 4}
# Append a new item to the set
my_set.add (5)
print(my_set) # Output: {1, 2, 3, 4, 5}
MOHAMMED ZAIN UL ABDEEN (160923748116)
LAQ’s
All questions carry 12 marks
1. a) Discuss about function and the types of arguments to be in CO 6 BTL2
python. 2
A function in Python is a block of reusable code that performs a specific
task. Functions are defined using the def keyword followed by the
function name and parameters (if any). Functions in Python can return 6 BTL3
values or simply execute a task without returning anything.
Types of Arguments in Python:
1. Positional Arguments:
o These are the most common type of arguments passed
to a function. The values are assigned to parameters
based on their position in the function call.
Example:
def add (a, b):
return a + b
result = add (2, 3) # 2 and 3 are positional arguments
2. Keyword Arguments:
• Keyword arguments are passed to a function by explicitly
stating the parameter name along with its value. This allows for
more flexibility in passing arguments.
Example:
def greet (name, age):
return f"Hello {name}, you are {age} years old."
message = greet (age=25, name="Alice")
3. Default Arguments:
Default arguments are parameters that have a default value. If
the caller does not provide a value for these parameters, the
default value is used.

Example:
def greet (name, greeting="Hello"):
return f"{greeting} {name}"

print(greet("John")) # Output: Hello John


print (greet ("Alice", "Good morning")) # Output: Good
morning Alice
4. Variable-Length Arguments:
• Python allows you to pass a variable number of arguments using
*args for non-keyword arguments and **kwargs for keyword
arguments.
• *args: Used to pass a variable number of positional arguments.
• **kwargs: Used to pass a variable number of keyword
arguments.
Example:
def display(*args):
for arg in args:
print(arg)
display (1, 2, 3) # Output: 1 2 3

Example using **kwargs:


def show_info(**kwargs):
for key, value in kwargs. items():
print(f"{key}: {value}")
MOHAMMED ZAIN UL ABDEEN (160923748116)
show_info(name="John", age=25) # Output: name: John, age: 25

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

# Check if element 60 is in the list


element_to_check = 60
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.

2 a) What is lambda function? What are the characteristics of a CO 6 BTL2


lambda function? Give an example. 2
A lambda function in Python is a small, anonymous function that is
defined using the lambda keyword. It can have any number of 6
arguments, but it can only have one expression. The result of the BTL3
expression is automatically returned.
Characteristics of a Lambda Function:
1. Anonymous Function: It does not have a name like a regular
function defined with def.
2. Single Expression: It can only contain a single expression, and
that expression is returned automatically without the need for
the return keyword.
3. Arguments: It can take multiple arguments but can only
evaluate one expression.
Syntax:
lambda arguments: expression
• arguments is a list of input parameters.
• expression is a single expression evaluated and returned.
MOHAMMED ZAIN UL ABDEEN (160923748116)
Example:
# Lambda function to calculate the square of a number
square = lambda x: x ** 2
# Calling the lambda function
result = square (5)
print(result) # Output: 25
Explanation:
• In the above example, lambda x: x ** 2 is a lambda function
that calculates the square of the number x.
• square(5) calls the lambda function and returns 25.

************
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]

# Method 3: Using pop() (removes element by index and returns


it)
removed_element = my_list.pop (1) # Removes and returns the
element at index 1 (20)
print ("After pop:", my_list) # Output: [10, 50]
print ("Removed element:", removed_element) # Output: 20

# Method 4: Using clear() (removes all elements from the list)


my_list. clear() # Clears the entire list
print ("After clear:", my_list) # Output: []

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]

del my_list [0] # Removes element at index 0


print(my_list) # Output: [40]
my_list. clear () # Clears the entire list
print(my_list) # Output: []
5. Sorting:
• sort (): Sorts the list in place.
• sorted (): Returns a new sorted list (does not modify the original
list).
Example:
my_list = [30, 10, 20, 40]
my_list. sort () # Sorts the list in place
print(my_list) # Output: [10, 20, 30, 40]
sorted_list = sorted (my_list, reverse=True) # Returns a sorted list
in reverse order
print(sorted_list) # Output: [40, 30, 20, 10]
6. Finding Length and Membership:
• len (): Returns the length (number of elements) of the list.
• in: Checks if an element exists in the list.
Examples:
my_list = [10, 20, 30]
print(len(my_list)) # Output: 3
print (20 in my_list) # Output: True
print (40 in my_list) # Output: False
7. List Comprehension:
• List comprehension provides a concise way to create lists by
applying an expression to each item in an iterable.
Example:
my_list = [x**2 for x in range(5)] # Creates a list of squares
print(my_list) # Output: [0, 1, 4, 9, 16]

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.

4. a) Write a Python program to find GCD of two numbers using CO 6 BTL3


recursion? 2
The Greatest Common Divisor (GCD) of two numbers is the largest
number that divides both of them without leaving a remainder. The 6 BTL2
GCD can be calculated using Euclid’s algorithm. We can implement
this algorithm recursively in Python.
Python Program to Find GCD Using Recursion:
# Recursive function to find GCD
def gcd (a, b):
if b == 0: # Base case: when b becomes 0, a is the GCD
return a
else:
return gcd (b, a % b) # Recursive call with b and remainder of
a divided by b
# Example usage
num1 = 56
num2 = 98
result = gcd(num1, num2)
print("GCD of", num1, "and", num2, "is:", result)
Explanation:
• The function gcd(a, b) works recursively by dividing the larger
number by the smaller one and finding the remainder. The
function keeps calling itself with the second number and the
remainder until the remainder is 0. The non-zero number at that
point is the GCD.
• The base case occurs when b becomes 0. At this point, the value
of a is the GCD.
Output:
GCD of 56 and 98 is: 14

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

6 a) Explain how to create a function in Python, including CO 6 BTL2


parameters and return values. With help of example program. 2
In Python, a function is defined using the def keyword. Functions
can accept parameters (inputs) and can return values using the 6 BTL3
return keyword. Functions allow you to encapsulate reusable code
MOHAMMED ZAIN UL ABDEEN (160923748116)
and make your program more modular.
Steps to Create a Function:
1. Define the function using the def keyword.
2. Specify the parameters in parentheses after the function name
(optional).
3. Add function body to define the logic of the function.
4. Return a value using the return keyword (optional).
Example Program to Create a Function:
# Function to add two numbers
def add_numbers (a, b):
result = a + b # Adding the two parameters
return result # Returning the sum
# Function call
num1 = 10
num2 = 20
sum_result = add_numbers (num1, num2)
# Print the result
print ("Sum of", num1, "and", num2, "is:", sum_result)

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.

7 a) Discuss the concept of recursive functions. Write a Python CO 6 BTL2


program to calculate the factorial of a number using recursion. 2
A recursive function is a function that calls itself during its
execution. This allows the function to break down complex 6 BTL3
problems into simpler, smaller subproblems. Recursion typically
involves:
1. Base Case: A condition to stop the recursion.
2. Recursive Case: The function calls itself with updated
arguments, gradually approaching the base case.
Example Program to Calculate the Factorial of a Number
Using Recursion:
The factorial of a number n is the product of all positive integers
less than or equal to n. It is denoted as n! The formula for factorial
is:
• n! = n * (n-1) * (n-2) * ... * 1
• Base Case: 0! = 1
• Recursive Case: n! = n * (n-1)!
# Recursive function to calculate factorial
def factorial(n):
if n == 0: # Base case: factorial of 0 is 1
return 1
else:
return n * factorial(n - 1) # Recursive call

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

10 a) Explain about methods in Tuple of Python with appropriate CO 6 BTL2


examples. 2
Tuples in Python are immutable, which means they do not support
methods that modify the tuple directly, such as append(), remove(), or 6 BTL3
pop(), as seen in lists. However, tuples do have some built-in methods
that can be used for various operations.
Methods of Tuples in Python:
1. count():
o Returns the number of occurrences of a specified value
in the tuple.
Syntax: tuple.count(value)
Example:
my_tuple = (1, 2, 3, 1, 4, 1)
result = my_tuple.count(1)
print(f"Count of 1 in the tuple: {result}")
Output:
Count of 1 in the tuple: 3
2. index():
• Returns the index of the first occurrence of a specified value in
the tuple.
• If the value is not found, it raises a ValueError.
Syntax: tuple.index(value, start, end)
Example:
my_tuple = (10, 20, 30, 40, 50)
result = my_tuple.index(30)
print(f"Index of 30 in the tuple: {result}")
Output:
Index of 30 in the tuple: 2
Important Notes:
• Since tuples are immutable, they do not support methods that
alter their contents (like append() or remove()), but they do
support methods for retrieving information about the contents.
• count() and index() are the most commonly used tuple methods
for searching or counting elements in a tuple.

b) Write a python program to find sum of first 10 natural numbers


using lambda function.
To calculate the sum of the first 10 natural numbers using a lambda
function, we can use the reduce() function from the functools module.
The reduce() function takes a binary function (e.g., addition) and
applies it cumulatively to the elements of the sequence.
MOHAMMED ZAIN UL ABDEEN (160923748116)
Example Python Program:
from functools import reduce
# Using lambda to find the sum of first 10 natural numbers
sum_result = reduce(lambda x, y: x + y, range(1, 11))
# Print the result
print(f"Sum of the first 10 natural numbers is: {sum_result}")
Explanation:
• range(1, 11) generates the sequence of natural numbers from 1
to 10.
• The lambda function adds the two numbers at a time (x + y),
and reduce() accumulates the sum over the entire range.
• The result is the sum of the first 10 natural numbers.
Output: Sum of the first 10 natural numbers is: 55
Summary:
• a) Tuple Methods: Tuples in Python have two important
methods: count() (which counts the occurrences of an element)
and index() (which finds the index of the first occurrence of an
element).
• b) The lambda function in combination with reduce() can be
used to calculate the sum of numbers, like summing the first 10
natural numbers. The lambda function simplifies the operation
and makes the code more concise.

S No. Short Answer Questions CO Marks BT


L
UNIT -III

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}

2. Demonstrate to merge two dictionaries in Python with an example. CO 2 BTL


In Python, dictionaries can be merged using several methods. The most common 3 3
approaches are:
• Using the update() method
• Using the ** unpacking operator (available in Python 3.5 and later)
Example Program:
# Define two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
# Method 1: Using update() method
dict1.update(dict2)
print("Merged Dictionary using update():", dict1)
# Method 2: Using unpacking operator (Python 3.5+)
merged_dict = {**dict1, **dict2}
print("Merged Dictionary using unpacking operator:", merged_dict)
Explanation:
1. Using update(): The update() method updates the first dictionary (dict1)
with the key-value pairs from dict2. If there are any duplicate keys, the values
from dict2 will overwrite those in dict1.
2. Using ** unpacking operator: This creates a new dictionary that combines
the keys and values from both dictionaries.
Output:
Merged Dictionary using update(): {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Merged Dictionary using unpacking operator: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
In this example, both methods produce the same merged dictionary.

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

5. When else, finally block gets executed in python CO3 2 BTL


In Python, else and finally blocks are used in exception handling along with try and 2
except blocks.
else Block:
• The else block runs only if no exception was raised in the try block.
• If an exception is raised, the else block is skipped, and the control is passed
to the except block.
finally Block:
• The finally block is always executed, regardless of whether an exception
occurred or not. It is typically used for cleanup actions (like closing files,
releasing resources, etc.).
When They Are Executed:
• else is executed if the code in the try block executes successfully without any
exceptions.
• finally is executed regardless of whether an exception occurs or not, making
it useful for cleanup tasks.
Example Program:
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print(f"The result of {num1} / {num2} is {result}")
except ZeroDivisionError:
print("Error! Division by zero.")
else:
print("No errors occurred, result calculated successfully.")
finally:
print("This will always execute, no matter what.")
Explanation:
• else block: Executes only if no exception occurs in the try block.
• finally block: Always executes, no matter what, and is typically used for
cleanup operations.
Summary:
• else: Executes if no exception occurs in the try block.
• finally: Always executes, regardless of whether an exception occurs or not.

6. How to declare object. CO3 2 BTL


You declare an object by calling the class as if it were a function. This automatically 1
invokes the __init__ method of the class, which initializes the object's attributes.
Syntax:
object_name = ClassName(arguments)
object_name: Name of the object.
ClassName: Name of the class from which the object is created.
arguments: Arguments passed to the class constructor (__init__ method).
Example:
class Person:
MOHAMMED ZAIN UL ABDEEN (160923748116)
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# Create an object
person1 = Person("Alice", 30)
# Call a method on the object
person1.greet()
Explanation:
• The object person1 is created from the Person class with "Alice" and 30
passed as arguments to the __init__ method.
• The method greet() is called on the object person1.
Output:
Hello, my name is Alice and I am 30 years old.
In summary, declaring an object involves calling a class with appropriate
arguments, creating an instance of that class.

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.

12. List and explain built it class attributes CO3 2 BTL


2
Attribute Description Example Usage
__dict__ Stores the instance's attributes as a obj.__dict__
dictionary.
__class__ Returns the class of the instance. obj.__class__
__name__ The name of the class as a string. ClassName.__name__
__module__ The module in which the class is ClassName.__module__
defined.
__doc__ The documentation string for the ClassName.__doc__
class.
__bases__ A tuple containing the base classes of ClassName.__bases__
the class.
__mro__ Method Resolution Order, a tuple of ClassName.__mro__
the classes in order.
__init__ The constructor method. obj = ClassName()
__str__ String representation of the object print(obj)
for printing.

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

# Method to print person's details


def display(self):
print (f"Name: {self.name}, Age: {self.age}")

# Method to update age


def update_age (self, new_age):
self.age = new_age # Updating the instance variable using self

# Creating objects (instances) of the class Person


person1 = Person ("Alice", 30)
person2 = Person ("Bob", 25)

# Accessing instance methods using the object


person1.display() # Output: Name: Alice, Age: 30
person2.display() # Output: Name: Bob, Age: 25

# Modifying an attribute using self in a method


person1.update_age (35)
person1.display() # Output: Name: Alice, Age: 35
Summary:
• self is used to represent the instance of the class.
• It allows access to the instance’s attributes and methods.
• All instance methods must include self as the first parameter to refer to the
specific instance calling the method.

14. What is __init__ () constructor used in python for? CO3 2 BTL


the __init__() method is a special method (also known as a constructor) that is 1
automatically called when an object (instance) of a class is created. It is used to
initialize the object's attributes (instance variables) and perform any setup or
initialization tasks when an object is instantiated.
Key Points about __init__():
1. Automatic Invocation: The __init__() method is called automatically when
an object of the class is created. You don't call it explicitly.
2. Initialization: It is used to initialize instance attributes with values when the
object is created.
3. First Argument: The first argument of __init__() is always self, which refers
to the current instance of the class. Additional parameters can be added to
accept values from the user during object creation.

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.

S No. Long Answer Questions CO Ma BT


rks L
Unit III
1. Write a program to create a class Student that sores roll number, name and CO3 6,6 BT
marks of three different subjects and display the information roll number, CO3 L3
name, marks
Python Program:-
class Student:
# Constructor to initialize roll number, name, and marks
def __init__(self, roll_number, name, marks):
self.roll_number = roll_number # Roll number of the student
self.name = name # Name of the student
self.marks = marks # Marks in three subjects as a list
# Method to display student information
def display_info(self):
print("Student Information:")
print(f"Roll Number: {self.roll_number}")
print(f"Name: {self.name}")
print(f"Marks: {self.marks}")
print(f"Total Marks: {sum(self.marks)}")
print(f"Average Marks: {sum(self.marks) / len(self.marks):.2f}")
# Example usage
# Creating an instance of Student
student1 = Student(101, "John Doe", [85, 90, 88])
# Displaying the student's information
student1.display_info()
Program Output:
For the above code, when the object student1 is created with roll number 101, name
"John Doe", and marks [85, 90, 88], the output will be:
Student Information:
Roll Number: 101
Name: John Doe
Marks: [85, 90, 88]
Total Marks: 263
Average Marks: 87.67

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

2. Explain the types of Inheritance with suitable examples? CO3 6,6 BT


CO3 L2
Write a program to create a class Student that sores roll number, name and
marks of three different subjects and display the information roll number,
name, marks
Python Program:-
class Student:
# Constructor to initialize roll number, name, and marks
def __init__(self, roll_number, name, marks):
self.roll_number = roll_number # Roll number of the student
self.name = name # Name of the student
self.marks = marks # Marks in three subjects as a list
# Method to display student information
def display_info(self):
print("Student Information:")
print(f"Roll Number: {self.roll_number}")
print(f"Name: {self.name}")
print(f"Marks: {self.marks}")
print(f"Total Marks: {sum(self.marks)}")
print(f"Average Marks: {sum(self.marks) / len(self.marks):.2f}")
# Example usage
# Creating an instance of Student
student1 = Student(101, "John Doe", [85, 90, 88])
# Displaying the student's information
student1.display_info()
Program Output:
For the above code, when the object student1 is created with roll number 101, name
"John Doe", and marks [85, 90, 88], the output will be:
Student Information:
Roll Number: 005
Name: John Doe
Marks: [85, 90, 88]
Total Marks: 263
Average Marks: 87.67

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.

Write a Python program to implement multiple inheritance using two base BT


classes L3
Program: -
class Father:
def __init__(self, father_name):
self.father_name = father_name
def show_father(self):
print(f"Father's Name: {self.father_name}")
class Mother:
def __init__(self, mother_name):
self.mother_name = mother_name
def show_mother(self):
print(f"Mother's Name: {self.mother_name}")
class Child(Father, Mother):
def __init__ (self, father_name, mother_name, child_name):
Father. __init__(self, father_name)
Mother. __init__(self, mother_name)
self. child_name = child_name
def show_child(self):
print (f"Child's Name: {self.child_name}")
# Example usage
child = Child ("John", "Mary", "Emma")
child. show_father ()
child. show_mother ()
child. show_child()
MOHAMMED ZAIN UL ABDEEN (160923748116)
Output:
Father's Name: John
Mother's Name: Mary
Child's Name: Emma
4. Write a Python program to perform operations deposit or withdraw money in a CO3 6,6 BT
bank using object-oriented programming. CO3 L3
Program:-
class BankAccount:
def __init__(self, account_number, account_holder, balance=0):
"""
Constructor to initialize account details.
:param account_number: Bank account number
:param account_holder: Name of the account holder
:param balance: Initial balance (default is 0)
"""
self.account_number = account_number
self.account_holder = account_holder
self.balance = balance
def deposit(self, amount):
"""
Method to deposit money into the account.
:param amount: Amount to deposit
"""
if amount > 0:
self.balance += amount
print(f"Successfully deposited ${amount}. Current balance: ${self.balance}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
"""
Method to withdraw money from the account.
:param amount: Amount to withdraw
"""
if amount > self.balance:
print("Insufficient balance for withdrawal.")
elif amount <= 0:
print("Withdrawal amount must be positive.")
else:
self.balance -= amount
print(f"Successfully withdrew ${amount}. Current balance: ${self.balance}")
def display_balance(self):
"""
Method to display the current account balance.
"""
print(f"Account Balance: ${self.balance}")
# Example usage
account = BankAccount("123456789", "Alice", 1000)
# Display initial balance
account.display_balance()
# Perform deposit
account.deposit(500)
# Perform withdrawal
account.withdraw(300)
# Attempt to withdraw more than available balance
account.withdraw(1500)
# Display final balance
account.display_balance()
Output:
Account Balance: $1000
Successfully deposited $500. Current balance: $1500
Successfully withdrew $300. Current balance: $1200
Insufficient balance for withdrawal.
Account Balance: $1200
This program demonstrates OOP concepts such as encapsulation and method
abstraction.
MOHAMMED ZAIN UL ABDEEN (160923748116)
Write a Python program to create a Class person which includes attributes
name, country and date of birth. Implement a method to determine the person's
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

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.

Explain python polymorphism with suitable example program BT


Polymorphism in Python refers to the ability to use a single interface (or method) to L2
represent different types of behavior. The word polymorphism comes from the Greek
words "poly" (many) and "morph" (form), so polymorphism means "many forms." In
Python, polymorphism allows us to call the same method on different objects, and
each object can respond to the method in its own way.
There are two types of polymorphism in Python:
1. Method Overriding (Compile-time Polymorphism)
2. Method Overloading (Run-time Polymorphism)
Example :- Method Overriding (Compile-time Polymorphism)
Method overriding happens when a subclass provides a specific implementation of a
method that is already defined in its superclass. The method in the subclass overrides
the method in the parent class.
Program Example for Method Overriding:
# Parent class
class Animal:
def sound(self):
print("Animal makes a sound")
# Child class
class Dog(Animal):
def sound(self): # Overriding the sound method
print("Dog barks")
# Another Child class
class Cat(Animal):
def sound(self): # Overriding the sound method
print("Cat meows")
# Creating instances
animal = Animal()
dog = Dog()
cat = Cat()
# Calling sound() method for different objects
animal.sound() # Output: Animal makes a sound
dog.sound() # Output: Dog barks
cat.sound() # Output: Cat meows
BT
L4
MOHAMMED ZAIN UL ABDEEN (160923748116)
Difference between pop () and popitem () in dictionary
Feature pop() popitem()
Operation Removes a specific item by Removes the last key-value pair in
key. the dictionary.
Return Returns the value Returns a tuple (key, value).
Value associated with the key.
Argument Takes a key as an Does not take any arguments.
argument.
Use Case When you need to remove When you want to remove and
a specific key-value pair. return the last item in the
dictionary.
Error Raises KeyError if the key Raises KeyError if the dictionary
Handling is not found (unless a is empty.
default is provided).
When to When you know the key When you don’t care the key and
use and want to remove a just want to remove the last item
specific item or any item in a dictionary.
7. Write a Program to Enter Name and Percentage Marks in a Dictionary CO3 6, BT
Understand and Display Information on the Screen CO3 6 L3
Program:-
# Program to enter Name and Percentage Marks in a dictionary and display the
information
# Create an empty dictionary to store student information
student_info = {}
# Get user input for student's name and percentage
name = input("Enter the student's name: ")
percentage = float(input("Enter the student's percentage marks: "))
# Store the information in the dictionary
student_info["Name"] = name
student_info["Percentage"] = percentage
# Display the student information
print("\nStudent Information:")
for key, value in student_info.items():
print(f"{key}: {value}")
Output:
Enter the student's name: John Doe
Enter the student's percentage marks: 85.5
Student Information:
Name: John Doe
Percentage: 85.5
This program provides an easy way to store and display the student's name and
percentage marks using a dictionary.
Write a Program to find Number of Occurrences of each Vowel present in the BT
given String? Understand L3
# Program to count occurrences of each vowel in a given string
# Take input from the user
input_string = input("Enter a string: ").lower() # Convert input to lowercase for
uniformity
# Initialize a dictionary to store the count of each vowel
vowel_count = {'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}
# Loop through each character in the string
for char in input_string:
if char in vowel_count:
vowel_count[char] += 1
# Display the count of each vowel
print("\nVowel Occurrences:")
for vowel, count in vowel_count.items():
print(f"{vowel}: {count}")
Output:
Enter a string: Hello, How are you?
Vowel Occurrences:
a: 1
e: 2
i: 0
o: 2
u: 1
MOHAMMED ZAIN UL ABDEEN (160923748116)
8. What is the output of below code CO3 4, BT
dictlang = { 'c ': 6, 'GO': 89, 'flython': 4, 'Rust':10 } CO3 4, L3
for _ in sorted(dictlang): CO3 4
print (dictlang[_])
The given code will throw a SyntaxError because of improper formatting in the loop.
The correct syntax for the for loop should have the body properly indented, and there
should be a colon : after the loop header.
Here is the corrected version of the code:
dictlang = { 'c ': 6, 'GO': 89, 'flython': 4, 'Rust': 10 }
# Loop through the dictionary keys in sorted order
for _ in sorted(dictlang):
print(dictlang[_])
Output:
89
10
6
4
Explanation of Output:
• For the sorted keys, the program prints the corresponding values:
o 'GO' → 89
o 'Rust' → 10
o 'c ' → 6
o 'flython' → 4

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.

Explain the concept of traversing dictionary elements with suitable example BT


program L2
Traversing a Dictionary in Python:-
Traversing a dictionary means iterating over its elements (keys, values, or key-value
pairs) using loops like for.
Key Concepts:
1. Iterating through keys: Default behavior when looping over a dictionary.
MOHAMMED ZAIN UL ABDEEN (160923748116)
2. Iterating through values: Use the values() method.
3. Iterating through key-value pairs: Use the items() method.

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.

9. a) Illustrate the following Set methods with an example. CO3 4, BT


1) intersection () 2) union() 3) issubset() 4) difference() 5) update() 6) discard() CO3 4, L2
7)issuperset 8)remove() CO3 4
1. intersection()
• Purpose: Returns a set that contains the common elements of two or more
sets.
Example:
python
Copy code
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1.intersection(set2)) # {3, 4}

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

Compare tuples and lists, tuples and dictionaries in detail. BT


1. Tuples vs Lists L4
Feature Tuples Lists
Definition Immutable ordered Mutable ordered collection of
collection of elements. elements.
Syntax () (e.g., t = (1, 2, 3)) [] (e.g., l = [1, 2, 3])
Mutability Immutable (cannot be Mutable (elements can be
modified after creation). added, removed, or updated).
Use Cases Used for fixed data like Used for dynamic data where
coordinates, constant values. changes are expected.
Performance Faster due to immutability. Slightly slower as it supports
modifications.
Methods Limited (count(), index()). Extensive (append(), remove(),
sort(), etc.).
MOHAMMED ZAIN UL ABDEEN (160923748116)
Memory More memory-efficient. Less memory-efficient due to
mutability.
Iteration Iteration is faster. Iteration is slower compared
to tuples.
2. Tuples vs Dictionaries B2L
Feature Tuples Dictionaries 3
Definition Immutable ordered Mutable collection of key-value
collection of elements. pairs.
Syntax () (e.g., t = (1, 2, 3)) {} (e.g., d = {"key": "value"})
Access Accessed by index (e.g., Accessed by keys (e.g., d["key"]).
Method t[0]).
Mutability Immutable. Mutable (keys and values can be
added, removed, or updated).
Use Cases Used for fixed, positional Used for mapping and fast lookups.
data.
Order Ordered as of Python Ordered as of Python 3.7+.
3.7+.
Storage Stores elements without Stores elements with unique
identifiers. identifiers (keys).
Operations Limited operations (index, Extensive operations (get, keys,
count). values, items).
Memory More memory-efficient. Requires more memory for key-
value pairs.
------------------------------------------------------------------------------------------------------
Write a program that creates a dictionary of radius of a circle and its
circumference.
Python program that creates a dictionary where the radius of a circle is the key, and its
corresponding circumference is the value:
# Create a dictionary of radius and their circumferences
circle_data = {}
# List of radii
radii = [1, 2, 3, 4, 5]
# Calculate circumference for each radius and store in dictionary
for radius in radii:
circumference = 2 * 3.14159 * radius # Circumference formula: 2πr
circle_data[radius] = round(circumference, 2) # Round to 2 decimal places
# Display the dictionary
print("Radius and Circumference Dictionary:")
for radius, circumference in circle_data.items():
print(f"Radius: {radius}, Circumference: {circumference}")
Output:
Radius and Circumference Dictionary:
Radius: 1, Circumference: 6.28
Radius: 2, Circumference: 12.57
Radius: 3, Circumference: 18.85
Radius: 4, Circumference: 25.13
Radius: 5, Circumference: 31.42

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

Explain python polymorphism with suitable example program BT


Polymorphism in Python L2
Polymorphism means "many forms." In Python, polymorphism allows objects of
different classes to be treated as objects of a common superclass. It enables a single
interface to represent different types of objects.
Polymorphism is commonly implemented through:
1. Method Overriding
2. Duck Typing
3. Operator Overloading
Benefits of Polymorphism
• Enhances code reusability.
• Simplifies code by using a unified interface for different object types.
• Promotes flexibility and scalability.
Example Program:-
# Parent class
class Animal:
def speak(self):
return "Animal makes a sound"
# Child classes
class Dog(Animal):
def speak(self):
return "Dog barks
class Cat(Animal):
def speak(self):
MOHAMMED ZAIN UL ABDEEN (160923748116)
return "Cat meows"
# Function to demonstrate polymorphism
def animal_sound(animal):
print(animal.speak())
# Create objects
dog = Dog()
cat = Cat()
# Polymorphic behavior
animal_sound(dog) # Output: Dog barks
animal_sound(cat) # Output: Cat meows
Explanation
• The speak method is overridden in the Dog and Cat classes.
• The animal_sound function works for any object of a class derived from
Animal.

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.

Question Unit4 CO Marks BTL


MOHAMMED ZAIN UL ABDEEN (160923748116)
Q.No
SAQ’s
All questions carry 2 marks.
1 Mention the ACID properties for transaction. CO4 2 BTL1
The ACID properties ensure that database transactions are
processed reliably. They stand for:
1. Atomicity:
A transaction is atomic, meaning it is either fully completed or
not executed at all. If any part of the transaction fails, the entire
transaction is rolled back.
2. Consistency:
The database must be in a consistent state before and after the
transaction. Any transaction must leave the database in a valid
state according to all defined rules, constraints, and
relationships.
3. Isolation:
Transactions are isolated from each other. The operations of
one transaction should not affect the operations of other
transactions, even if they are running concurrently. Intermediate
states of a transaction are not visible to other transactions.
4. Durability:
Once a transaction is committed, the changes are permanent,
even if there is a system crash. The database ensures that
committed data is saved to non-volatile memory and can be
recovered.
These properties are critical for maintaining data integrity and
reliability in database systems.

2 Write a python program to show databases using MySQL. CO4 2 BTL3


To show databases using MySQL in Python, you need to use the
mysql-connector library. Here’s a program that demonstrates how to
connect to a MySQL database and list all available databases:
Python Program to Show Databases Using MySQL
import mysql.connector
# Connect to MySQL server
conn = mysql.connector.connect(
host='localhost', # Your host
user='your_username', # Your username
password='your_password' # Your password
)
# Create a cursor object to interact with MySQL
cursor = conn.cursor()
# Execute SQL query to show databases
cursor.execute("SHOW DATABASES")
# Fetch all databases
databases = cursor.fetchall()
# Display databases
print("Databases available:")
for db in databases:
print(db[0])
# Close the cursor and connection
cursor.close()
conn.close()
Output:
The program will print the list of databases available on the MySQL
server, for example:-
Databases available:
information_schema
MOHAMMED ZAIN UL ABDEEN (160923748116)
my_database
test_db
3 Suggest suitable command for the following purpose: CO4 2 BTL4
i)To display the list of the database already existing in MySQL
To display all the databases in MySQL, use the following command:-
SHOW DATABASES;
This will list all the databases that exist on the MySQL server.
ii. To use the database named City.
To select and use a specific database, use the following command:-
USE City;
This command sets the active database to "City", allowing you to
perform operations on it.

4 List out steps to connect Python with MySQL. CO4 2 BTL2


Steps to Connect Python with MySQL
import mysql.connector
# Establish connection
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="your_database"
)
# Create a cursor object
cursor = conn.cursor()
# Execute a query
cursor.execute("SHOW DATABASES")
# Fetch results
databases = cursor.fetchall()
# Display databases
for db in databases:
print(db[0])
# Close the cursor and connection
cursor.close()
conn.close()
Notes:
• Make sure MySQL is installed and running on your system.
• Replace "localhost", "your_username",
"your_password", and "your_database" with actual
values.
• Install the necessary Python MySQL connector if not already
installed (pip install mysql-connector-python).
These steps outline the basic process of connecting Python to
MySQL.

5 For DROP command write syntax and example. CO4 2 BTL2


• Syntax
Drop DATABASE database_name;
• Example
DROP DATABASE CITY;
This command delete the database named “City” along with all its
tables and data.
6 What is the use of commit () method in Python CO4 2 BTL2
The commit() method in python is used to save the changes made during a
transaction in a database. When working with databases, changes like
INSERT, UPDATE, or DELETE do not take effect immediately unless
MOHAMMED ZAIN UL ABDEEN (160923748116)
you commit the transaction.
7. Mention any two-database error. CO4 2 BTL1
Two Database Errors
1. Syntax Error:
o Occurs when there is a mistake in the SQL query
syntax, such as a typo or incorrect keyword.
o Example:
SELECT * FORM students; -- Incorrect keyword
'FORM' instead of 'FROM'
2. Constraint Violation Error:
o Happens when an operation violates a database
constraint, such as a unique, primary key, or foreign
key constraint.
o Example:
INSERT INTO students (id, name) VALUES (1, 'John');
-- Violation if ID 1 already exists as a primary key.

8. Write a python snippet to Delete a table,explain with example? CO4 2 BTL2


Python Snippet to Delete 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, deletes the
students table using DROP TABLE, and closes the connection. The
DROP TABLE IF EXISTS command ensures the table is deleted if it
exists.

9. Write a python snippet to Truncate a table,explain with example? CO4 2 BTL1


Python Snippet to Truncate 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 truncate a table
cursor.execute("TRUNCATE TABLE students;")
# Commit and close
conn.commit()
cursor.close()
conn.close()
Explanation:
This Python snippet connects to a MySQL database and uses the
TRUNCATE TABLE command to remove all records from the
students table without deleting the table itself. The table structure
remains intact, but all data is erased.
MOHAMMED ZAIN UL ABDEEN (160923748116)

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.

11. Write any 2 DDL commands? CO4 2 BTL1


Two DDL Commands:
1. CREATE:
Used to create a new database object like a table, view, or
index.
Example:-
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
salary DECIMAL(10, 2)
);
2. ALTER:
Used to modify an existing database object, such as adding or
modifying columns in a table.
Example:
ALTER TABLE employees ADD COLUMN department
VARCHAR(50);

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)

6 Explain briefly about : CO4 BTL2


(a) DDL commands
6,6 BTL2
DDL commands are used to define and manage the structure of
database objects such as tables, schemas, and indexes.
Common DDL Commands:
1. CREATE: Used to create new database objects.
o Example: CREATE TABLE students (id INT, name
VARCHAR(50));
2. DROP: Deletes a database object permanently.
o Example: DROP TABLE students;
3. ALTER: Modifies the structure of an existing database object.
o Example: ALTER TABLE students ADD age INT;
4. TRUNCATE: Removes all records from a table but retains its
structure.
o Example: TRUNCATE TABLE students;
******************
(b) DML commands
DML commands are used to manipulate the data stored in
database tables.
Common DML Commands:
1. INSERT: Adds new records to a table.
o Example: INSERT INTO students (id, name, age)
VALUES (1, 'Alice', 20);
2. UPDATE: Modifies existing records in a table.
o Example: UPDATE students SET age = 21 WHERE
MOHAMMED ZAIN UL ABDEEN (160923748116)
id = 1;
3. DELETE: Removes specific records from a table.
o Example: DELETE FROM students WHERE id = 1;
4. SELECT: Retrieves data from a table.
o Example: SELECT * FROM students;
Key Difference:
• DDL commands focus on defining the structure of the
database, while DML commands operate on the data within the
database.

7 What is the difference between DML and DDL operations with CO4 12 BTL4
database?

Aspect DML (Data DDL (Data Definition


Manipulation Language)
Language)
Purpose Manipulates data within Defines or modifies the
the database. structure of the database.
Commands INSERT, UPDATE, CREATE, ALTER,
DELETE, SELECT DROP, TRUNCATE
Effect Changes the data stored Changes the
in the database tables. structure/schema of
database objects.
Rollback Supports rollback Mostly not rollback-
operations for supported (irreversible).
transactions.
Usage INSERT INTO CREATE TABLE
Example table_name VALUES table_name (...)
(...)
Key Point:
• DML focuses on data manipulation, whereas DDL focuses on
database structure.
8 Write the list of exceptions how python handles? CO4 12 BTL1
List of Common Exceptions in Python:
1. ArithmeticError: Base class for arithmetic errors.
o Example: ZeroDivisionError, OverflowError
2. IndexError: Raised when accessing an invalid index in a
sequence.
o Example: list[10] when the list has fewer elements.
3. KeyError: Raised when accessing a non-existent key in a
dictionary.
4. NameError: Raised when using an undefined variable.
5. TypeError: Raised when an operation is performed on an
incompatible type.
6. ValueError: Raised when a function gets an argument of the
correct type but an invalid value.
7. IOError: Raised for input/output operations like file not found.
o Example: FileNotFoundError
8. AttributeError: Raised when an invalid attribute is accessed
on an object.
9. ImportError: Raised when an import statement fails.
10. SyntaxError: Raised when there’s a syntax issue in code.
11. IndentationError: Raised for incorrect indentation.
12. RuntimeError: Generic error during runtime.
13. StopIteration: Raised by iterators to indicate no further items.
14. MemoryError: Raised when the program runs out of memory.
MOHAMMED ZAIN UL ABDEEN (160923748116)
15. AssertionError: Raised when an assertion statement fails.
How Python Handles Exceptions:
• try Block: Contains code that might raise an exception.
• except Block: Handles the raised exception.
• else Block: Executes if no exception occurs.
• finally Block: Executes code regardless of whether an
exception occurred.
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("Execution completed.")

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

10 Explain in details Database Errors using Python Programming? CO4 12 BTL2


Database Errors in Python Programming
When working with databases in Python, errors may arise due to
connection issues, syntax problems, or constraint violations. Python
handles these errors using database-specific exceptions. Below are
common database errors and how to manage them:-
Common Database Errors
• Connection Errors: Issues with establishing a database
connection.
Example: mysql.connector.errors.InterfaceError.
• SQL Syntax Errors: Mistakes in SQL query syntax.
Example: mysql.connector.errors.ProgrammingError.
• Integrity Errors: Violations of database constraints like
primary keys.
Example: mysql.connector.errors.IntegrityError.
• Operational Errors: General issues like unavailable databases.
Example: sqlite3.OperationalError.
Example: Handling Errors
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(
host="localhost", user="root", password="password",
database="test_db"
)
cursor = connection.cursor()
cursor.execute("SELECT FROM students") # Intentional error
except mysql.connector.ProgrammingError as pe:
print("Syntax Error:", pe)
except mysql.connector.InterfaceError as ie:
print("Connection Error:", ie)
except Error as e:
print("Database Error:", e)
finally:
if connection.is_connected():
cursor.close()
MOHAMMED ZAIN UL ABDEEN (160923748116)
connection.close()
Best Practices
• Validate input data to prevent errors.
• Use parameterized queries to avoid SQL injection.
• Log errors for debugging.
• Ensure proper closure of connections and cursors in the finally
block.

Unit5:

Q.No Questions CO Marks BTL


SAQ’s
All questions carry 2 marks.
1 What is NumPy, and why is it important for data analysis in CO5 2 BTL1
Python?
NumPy is a powerful Python library for numerical computing. It
provides support for large, multi-dimensional arrays and matrices, along
with a collection of mathematical functions to operate on these arrays.
Importance for Data Analysis:
1. Efficient Data Storage: NumPy arrays are more memory-efficient
than traditional Python lists.
2. Speed: Operations on NumPy arrays are faster, as they are
implemented in C.
3. Convenience: Offers a variety of mathematical functions (e.g.,
linear algebra, statistical operations) and integrates well with other
data analysis libraries like pandas, matplotlib, and scikit-learn.

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.

4 What is the purpose of the drop () method in Pandas? CO5 2 BTL2


Write an example.
The drop() method in Pandas is used to remove rows or columns from a
DataFrame or Series.
• Rows: drop(index, axis=0)
• Columns: drop(columns, axis=1)
Example:
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
# Dropping a column
df_dropped_column = df.drop('Age', axis=1)
# Dropping a row
df_dropped_row = df.drop(1, axis=0)
print(df_dropped_column)
print(df_dropped_row)
Output:-
Name
0 Alice
1 Bob
2 Charlie
Name Age
0 Alice 25
2 Charlie 35
axis=1 for columns.
axis=0 for rows.
5 Explain what happens when missing data is encountered in a Pandas CO5 2 BTL2
DataFrame. How can it be handled?
When missing data is encountered in a Pandas DataFrame, it is
represented by NaN (Not a Number), which is the standard placeholder
for missing or undefined values.
Handling Missing Data in Pandas:
1. Detecting Missing Data:
o isna() or isnull() methods return a DataFrame of boolean
values indicating where the missing data is.
2. Removing Missing Data:
o dropna(): Removes rows or columns with missing data.
▪ Example: df.dropna(axis=0) removes rows with
missing data, and df.dropna(axis=1) removes
columns with missing data.
3. Filling Missing Data:
o fillna(): Fills missing data with a specified value or
method.
▪ Example: df.fillna(0) fills missing values with 0.
MOHAMMED ZAIN UL ABDEEN (160923748116)
You can also use forward fill (method='ffill') or
backward fill (method='bfill').
4. Replacing Missing Data:
o replace(): Replaces missing values with a specific value or
other replacement logic.

6 What happens when you add a scalar to an array? CO5 2 BTL3


When you add a scalar (a single value) to a NumPy array, broadcasting
occurs. Broadcasting is the process that allows NumPy to perform
element-wise operations between arrays of different shapes and sizes.
What happens:
1. Scalar Addition: The scalar is added to every element of the
array.
2. Element-wise Operation: NumPy will "broadcast" the scalar to
match the shape of the array and then perform the addition.

7. How do you access the second element of a 1D array? CO5 2 BTL1


To access the second element of a 1D array in Python (using NumPy or a
standard Python list), you use indexing. In Python, indexing starts from 0, so
the second element is at index 1.
NumPy array:
import numpy as np
# Create a 1D NumPy array
arr = np. array([10, 20, 30, 40, 50])
# Access the second element (index 1)
second_element = arr [1]
print(second_element)
Output:
20
8. What are the different summary statistics functions in Pandas? CO5 2 BTL2
Pandas provides several summary statistics functions, including:
• mean (): Computes the mean of the DataFrame or Series.
• sum (): Returns the sum of the DataFrame or Series.
• min (), max (): Finds the minimum or maximum value.
• describe (): Provides a summary of statistics like mean, count, std, etc.

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.

2 Explain Universal Array Functions in NumPy with examples. CO5 12 BTL1


Demonstrate at least two functions, such as np.sqrt and
np.mean.
Universal Array Functions (ufuncs) in NumPy:
Universal functions (ufuncs) are functions that operate element-wise on
ndarrays in NumPy. These functions allow you to perform
mathematical operations on arrays without using explicit loops. They are
optimized and are usually faster than regular Python functions.
MOHAMMED ZAIN UL ABDEEN (160923748116)
Some key features of ufuncs:
• They operate on whole arrays at once, allowing for vectorized
operations.
• They provide mathematical functions, trigonometric functions,
statistical functions, etc.
• They return a new array with the operation applied to each
element.
Example of Universal Array Functions:
1. np.sqrt(): Calculates the square root of each element in the array.
2. np.mean(): Computes the mean (average) of the elements in an
array.

Python Program Demonstrating np.sqrt and np.mean:


import numpy as np
# Create an array
arr = np. array([4, 9, 16, 25, 36])
# 1. np.sqrt() - Calculate the square root of each element
sqrt_arr = np. sqrt(arr)
print ("Square Root of each element:")
print(sqrt_arr)
# 2. np.mean() - Calculate the mean of the array
mean_value = np. mean(arr)
print ("\nMean of the array:", mean_value)
Explanation:
1. np.sqrt(arr): This function computes the square root of each
element in the array. For example, the square root of 4 is 2, 9 is 3,
and so on.
2. np.mean(arr): This function calculates the mean (average) of all
elements in the array. The mean is calculated as the sum of
elements divided by the number of elements,
i.e., (4 + 9 + 16 + 25 + 36) / 5 = 18.0.

3. a) What is a Pandas DataFrame? CO5 6,6 BTL2


A Pandas DataFrame is a two-dimensional, size-mutable, and
potentially heterogeneous tabular data structure with labeled axes (rows
and columns). It is one of the most commonly used data structures in the
Pandas library, designed for handling and analyzing structured data. It can
hold data of different types (integer, float, string, etc.), and you can access
data through both row and column labels.

b) Write a program to create a DataFrame, reindex it, and drop


an entry.

import pandas as pd

# 1. Create a DataFrame

data = {'Name': ['Alice', 'Bob', 'Charlie', 'David'],

'Age': [24, 27, 22, 32],

'City': ['New York', 'Los Angeles', 'Chicago', 'Houston']}

df = pd.DataFrame(data)

print("Original DataFrame:")

print(df)
MOHAMMED ZAIN UL ABDEEN (160923748116)

# 2. Reindex the DataFrame (changing row labels)

df_reindexed = df. reindex ([3, 2, 1, 0]) # Reversing the rows

print ("\nReindexed DataFrame:")

print(df_reindexed)

# 3. Drop an entry (drop the row where Name is 'Charlie')

df_dropped = df. drop(df[df['Name'] == 'Charlie']. index)

print ("\nDataFrame after dropping 'Charlie':")

print(df_dropped)

Explanation:

1. Create DataFrame: A DataFrame is created from a


dictionary containing names, ages, and cities.

2. Reindexing: The reindex() method rearranges the rows based


on the provided indices. Here, we reversed the order of rows.

3. Dropping an Entry: The drop () method removes a specific


entry. In this case, the row where the Name is 'Charlie' is
dropped from the DataFrame

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)

You might also like