0% found this document useful (0 votes)
4 views29 pages

Python QB Answers Mid-1

The document contains important questions and answers related to programming with Python, covering topics such as applications of Python, identifier rules, array operations, arithmetic operators, input/output statements, control statements, and NumPy arrays. It includes examples of Python code for various tasks like calculating distances, counting even/odd numbers, and removing duplicates from arrays. The content is structured into two parts, with Part A focusing on fundamental concepts and Part B delving into more advanced programming techniques.

Uploaded by

madatgnan143
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views29 pages

Python QB Answers Mid-1

The document contains important questions and answers related to programming with Python, covering topics such as applications of Python, identifier rules, array operations, arithmetic operators, input/output statements, control statements, and NumPy arrays. It includes examples of Python code for various tasks like calculating distances, counting even/odd numbers, and removing duplicates from arrays. The content is structured into two parts, with Part A focusing on fundamental concepts and Part B delving into more advanced programming techniques.

Uploaded by

madatgnan143
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

PROGRAMMING WITH PYTHON IMPORTANT QUESTIONS FOR MID 1

PART-A

a. State any four applications of python? [CO1, L1]


Ans. The most common important application areas are
1) For developing Desktop Applications
2) For developing web Applications
3) For developing database Applications
4) For developing games
b. State the identifier rules in python? [CO1,L1]
Ans. 1. The only allowed characters in Python are
• alphabet symbols(either lower case or upper case)
• digits(0 to 9)
• underscore symbol(_)
2. Identifier should not starts with digit
3. Identifiers are case sensitive.
4. We cannot use reserved words as identifiers.
5. Dollar ($) Symbol is not allowed in Python.
c. How would you determine whether any element is present in a given sequence?
Ans. you can use the ‘in’ operator to check if an element is present in a sequence.
Ex:
sequence = [1, 2, 3, 4, 5]
element = 3

if element in sequence:
print("Element is present")
else:
print("Element is not present")

d. List our the main difference between a List and an Array.[CO2, L1]
Ans.
e. What is the difference between break and continue? [CO1,L2]
Ans.

f. How would you determine length of an array and size of each element in an array?
Ans. In Python, you can determine the length of an array and the size of each element using
the len() function and the itemsize attribute, respectively.
Ex:

from array import array

my_array = array('i', [1, 2, 3, 4, 5])


array_length = len(my_array)
element_size = my_array.itemsize

print(f"Length of the array:{array_length}")


print(f"Size of each element in the array:{element_size}bytes")

g. How to find size and shape of the numpy array? [CO2,L2]


Ans. In NumPy, you can find the size and shape of an array using the size and shape
attributes, respectively.
Ex:

import numpy as np

my_array = np.array([[1, 2, 3], [4, 5, 6]])


array_size = my_array.size
array_shape = my_array.shape
print(f"Size of the array: {array_size}") //6
print(f"Shape of the array: {array_shape}") //(2,3)
h. Write a python program to accept a string and display each word and its length?[CO2,L2]
Ans.

input_string = input("Enter a string: ")


words = input_string.split()
for word in words:
print(f"Word: {word}, Length: {len(word)}")

i. Differentiate Del, remove and pop on Python Arrays. [CO2,L2]


Ans.

j. Write a python function to perform addition of two integers ?[CO3,L3]


Ans.

def add_two_integers(num1, num2):


result = num1 + num2
return result

I1 = int(input("Enter the first integer: "))


I2 = int(input("Enter the second integer: "))

print(f"The sum of {I1} and {I2} is: {add_two_integers(I1, I2)}")

k. Create a list using range() in python? [CO3, L3]

# Create a list of numbers from 0 to 4


print(list(range(5))) // [0, 1, 2, 3, 4]
# Create a list of even numbers from 2 to 10
print(list(range(2, 11, 2))) // [2, 4, 6, 8, 10]
PART- B

1. a.List and explain different arithmetic operators supported by Python. Discuss about their
precedence and associativity. ? [CO1,L2]
Ans: The python programming language supports various arithmetic operators for all floating-point
and integer numbers.
+ → Addition
- → Subtraction
* → Multiplication
/ → Division Operator
% → Modulo Operator
// → Floor Division Operator
** → Exponent Operator OR Power Operator

a=10
b=2
print('a+b=',a+b)
print('a-b=',a-b)
print('a*b=',a*b)
print('a/b=',a/b)
print('a//b=',a//b)
print('a%b=',a%b)
print('a**b=',a**b)
precedence and associativity:
` If multiple operators present then which operator will be evaluated first is decided by
operator precedence
1 b. Write a Python program to compute distance between two points in a 2- dimensional
coordinate system. [CO1, L2]
Ans:

# Python Program to Calculate Distance


# Reading co-ordinates
x1 = float(input('Enter x1: '))
y1 = float(input('Enter y1: '))
x2 = float(input('Enter x2: '))
y2 = float(input('Enter y2: '))
# Calculating distance
d = ( (x2-x1)**2 + (y2-y1)**2 ) ** 0.5
# Displaying result
print('Distance = %f' %(d))
2. a. Discuss about input and output statements in Python
Ans. In Python, input and output statements are essential components for interacting with user
and displaying information.
Input Statements:
In Python, the input() function is used to take user input from the keyboard.
It reads a line from the user as a string and returns that string.
If you need to convert the input into a different data type (e.g., integer or float),
you should explicitly perform the conversion.

name = input("Enter your name: ") # string


age = int(input("Enter your age: ")) # integer
height = float(input("Enter height in meters: ")) #float

Read multiple values from the keyboard in a single line:


You can read multiple values from the keyboard in a single line by using the
input() function and then splitting the input into individual values by using split() .

a,b= [int(x) for x in input("Enter 2 numbers :").split()]


a,b=map(int,input("Enter 2 numbers :").split())
lst=[map(int,input("Enter numbers into list :").split())]

Output Statements:
In Python, the print() function is used to display output.

print("Hello world !")


It can take multiple arguments separated by commas and prints them with a
space by default and also use string concatenation or formatting for more complex
output

print("Hello", "world", "!")


name = "John" ; age = 25
print("Name: " + name + ", Age: " + str(age))
print(f"Name: {name}, Age: {age}")
2. b.Write a Python program to count the number of even and odd numbers from 1 to 20.
Ans.

# Initialize counters for even and odd numbers


even_count = 0
odd_count = 0
# Iterate through numbers from 1 to 20
for number in range(1, 21):
# Check if the number is even or odd
if number % 2 == 0:
even_count += 1
else:
odd_count += 1
# Print the results
print("Number of even numbers:", even_count)
print("Number of odd numbers:", odd_count)

3. a. Explain in detail about python type conversion and type casting? [CO1, L2]
Ans: Python, type conversion and type casting refer to the process of changing the data type of a
variable from one type to another

Type Conversion:
In type conversion, the Python interpreter automatically converts one data type to
another. Since Python handles the implicit data type conversion, the programmer does not have
to convert the data type into another type explicitly.
In type conversion, the destination data (The data type to which the conversion happens) of
a smaller size is converted to the source data type(The data type from which the conversion happens)
of larger size. This avoids the loss of data and makes the conversion safe to use.

result = 5 + 3.2
print(result) # Output: 8.2

Type Casting:
In type casting, the programmer has to change the data type as per their requirement
manually.
In this, the programmer explicitly converts the data type using predefined functions
like int() , float() , str() etc. There is a chance of data loss in this case if a particular
data type is converted to another data type of a smaller size.

num_str = "10"
float_num = 7.8
num_int = int(num_str)
int_num = int(float_num)
print(num_int) # Output: 10
print(int_num) # Output: 7
3 b. Write a program to calculate the total amount to be paid by the user after reducing the 10%
discount on purchase more than 1000 rupees. [CO1, L3]
Ans.

# Input the purchase amount from the user


purchase_amount = float(input("Enter the purchase amount in rupees:"))

# Check if the purchase amount is greater than 1000 rupees


if purchase_amount > 1000:
# Apply a 10% discount
discount = 0.10 * purchase_amount
discounted_amount = purchase_amount - discount
else:
discounted_amount = purchase_amount
# Print the total amount to be paid
print("Total Amount to be Paid:",discounted_amount)

4 a. What is the purpose of else clause for a loop? Explain how else works with while and
for loops, with examples. [CO1, L2]
Ans. In Python, the else clause for a loop is used to specify a block of code that should be executed
when the loop condition becomes False.
The else block is executed only if the loop completes its iteration without encountering a break
statement.
The else clause simplifies post-loop execution without requiring an extra flag, useful when an
action is intended only upon successful completion of the loop.
‘else’ with a ‘while’ loop:

count = 0
while count < 5:
print(f"Count is {count}")
count += 1
else:
print(""Loop is exhausted because count is not less than 5.")

‘else’ with a ‘for’ loop:

numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num == 0:
print("Found 0 in the list. Breaking loop.")
break
print(num)
else:
print("Loop completed without a break.")
4 b.Write a Python program that prints all the numbers from 0 to 100 except multiples of 4 and 6.
Ans.

for num in range(101):


if num % 4 == 0 or num % 6 == 0:
continue # Skip multiples of 4 and 6
print(num)

5. a. Explain about the following Decision control Statements.


i)if-else ii)nested if-else iii)if-elif-else
Ans. Decision control statements in Python are used to control the flow of execution based on certain
conditions.
i)if-else Statement:
The ‘if-else’ statement allows you to execute one block of code if a given condition
is True and another block if the condition is False.
The general syntax is as follows:

if condition:
# Code to be executed if the condition is True
else:
# Code to be executed if the condition is False
Example:

age = int(input())
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
ii) nested if-else Statement:
The nested ‘if-else’ statement involves having an if-else statement inside another
if or else block. This allows for more complex decision-making based on multiple conditions.
The general syntax is as follows:

if outer_condition:

# Code for outer condition

if inner_condition:

# Code to be executed if both outer and inner conditions are True

else:

# Code to be executed if outer condition is True but inner condition is False

else:

# Code to be executed if outer condition is False


Example of nested if-else:

score = int(input())

if score >= 60:


print("You passed.")
if score >= 90:
print("You got an A.")
elif score >= 75:
print("You got a B.")
else:
print("You got a C.")
else:
print("You failed.")

iii ) if-elif-else Statement:


The ‘if-elif-else’ statement allows you to check multiple conditions in sequence.
The elif (short for "else if") is used to test additional conditions after the initial if
condition.
The general syntax is as follows:

if condition1:
# Code to be executed if condition1 is True
elif condition2:
# Code to be executed if condition1 is False and condition2 is True
else:
# Code to be executed if all conditions are False
Example:

num = int(input())

if num > 0:
print("Positive number.")
elif num < 0:
print("Negative number.")
else:
print("Zero.")
5 b. Write a python program to find sum of n natural numbers using while loop?
Ans.

# Get the value of n from the user


n = int(input("Enter a positive integer n: "))

# Initialize variables
sum_of_numbers = 0
count = 1

# Calculate the sum using a while loop


while count <= n:
sum_of_numbers += count
count += 1

# Print the result


print(f"The sum of the first {n} natural numbers is: {sum_of_numbers}")
6. a. Demonstrate the following array operations with suitable examples.
i) Remove ii) index iii) count
Ans.
i) Remove:
The remove() method is used to remove the first occurrence of a specified value
from a list.

# Remove operation
numbers_list = [1, 2, 3, 4, 2, 3, 5]
numbers_list.remove(3)
print("After removing the first occurrence of 3:", numbers_list)

ii) index:
The index() method is used to find the index of the first occurrence of a
specified value in a list.

# Index operation
numbers_list = [1, 2, 3, 4, 2, 3, 5]
index_of_3 = numbers_list.index(3)
print("Index of the first occurrence of 3:", index_of_3)

ii) count:
The count() method is used to count the number of occurrences of a specified
value in a list.

# Count operation
numbers_list = [1, 2, 3, 4, 2, 3, 5]
count_of_3 = numbers_list.count(3)
print("Number of occurrences of 3:", count_of_3)
6 b.Write a Python program that removes all duplicate elements from an array and returns a new array
Ans.

def remove_duplicates(input_array):
unique_array = []

for item in input_array:


if item not in unique_array:
unique_array.append(item)
return unique_array

# Example usage:
input_array = [1, 2, 3, 4, 2, 3, 5]
result_array = remove_duplicates(input_array)

print("Original Array:", input_array)


print("Array with Duplicates Removed:", result_array)
7. a. Discuss about creating numpy arrays and their operations.[CO2, L2]
Ans. NumPy is a powerful numerical computing library in Python, and it provides support for
creating arrays (ndarrays) and performing a wide range of array operations.
Creating NumPy Arrays:
1. Using np.array():
The most common way to create a NumPy array is by converting a Python list or tuple
using np.array():

import numpy as np
# Creating a 1-dimensional array
arr1 = np.array([1, 2, 3])
# Creating a 2-dimensional array (matrix)
arr2 = np.array([[1, 2, 3], [4, 5, 6]])
2. Using Special Functions:
NumPy provides functions to create arrays with specific properties:

import numpy as np
# Creating an array of zeros
zeros_array = np.zeros((3, 3))
# Creating an array of ones
ones_array = np.ones((2, 4))
# Creating an identity matrix
identity_matrix = np.eye(3)
# Creating a diagonal matrix
diagonal_matrix = np.diag([1, 2, 3])
# Creating a random array
random_array = np.random.rand(2, 3)#2x3 arraywithrandomvaluesbetween0and1
Basic Array Operations:
1. Arithmetic Operations:
NumPy allows you to perform element-wise arithmetic operations on arrays:

import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
# Element-wise addition
result_addition = arr1 + arr2
# Element-wise multiplication
result_multiplication = arr1 * arr2
2. Array Indexing and Slicing:
NumPy arrays support indexing and slicing similar to Python lists:

import numpy as np
arr = np.array([0, 1, 2, 3, 4, 5])
# Accessing an element
element = arr[2]
# Slicing
subset = arr[1:4]
3. Aggregation Functions:
NumPy provides functions to perform aggregation operations on arrays:

import numpy as np
arr = np.array([1, 2, 3, 4, 5])
# Sum of all elements
sum_of_elements = np.sum(arr)
# Mean of elements
mean_of_elements = np.mean(arr)
# Maximum and minimum elements
max_element = np.max(arr)
min_element = np.min(arr)
4. Reshaping and Transposing:
NumPy allows you to reshape and transpose arrays:

import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
# Reshaping the array
reshaped_array = arr.reshape((3, 2))
# Transposing the array
transposed_array = arr.T
7 b. Write a python program to compute addition, multiplication of matrices using numpy.
Ans.

import numpy as np

# Define matrices
matrix1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
matrix2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
# Addition of matrices
matrix_sum = np.add(matrix1, matrix2)
# Multiplication of matrices
matrix_product = np.matmul(matrix1, matrix2)
# Display the results
print("Matrix 1:")
print(matrix1)

print("\nMatrix 2:")
print(matrix2)

print("\nMatrix Sum:")
print(matrix_sum)

print("\nMatrix Product:")
print(matrix_product)

Matrix 1:
[[1 2 3]
[4 5 6]
[7 8 9]]
Matrix 2:
[[9 8 7]
[6 5 4]
[3 2 1]]
Matrix Sum:
[[10 10 10]
[10 10 10]
[10 10 10]]
Matrix Product:
[[ 30 24 18]
[ 84 69 54]
[138 114 90]]
8. a. Explain about different string operations using suitable python program? [CO2, L3]
Ans. 1. Concatenation:

str1 = "Hello"
str2 = "World"
result_concatenation = str1 + " " + str2
print(result_concatenation)
2. Slicing:

text = "Python is awesome"


substring = text[0:6] # Slice from index 0 to 5
print(substring)
3. String Length:

text = "Hello, World!"


length = len(text)
print("Length of the string:", length)
4. String Formatting:

name = "Alice"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
5. Searching in Strings:

text = "Python is easy to learn"


keyword = "easy"
if keyword in text:
print("found in the string.")
else: print("not found in the string.")
6. Changing Case:

text = "Hello, World!"


print("Uppercase:", text.upper())
print("Lowercase:", text.lower())
7. String Splitting:

sentence = "Python is versatile and powerful"


words = sentence.split()
print("Words in the sentence:", words)
8. String Stripping:

text_with_spaces = " Python is fun! "


stripped_text = text_with_spaces.strip()
print("Original text:", text_with_spaces)
print("Stripped text:", stripped_text)
8 b. Explain the importance of reshaping and flattening a numpy array with suitable examples?
Ans. Reshaping and flattening are important operations in NumPy that allow you to manipulate the
structure of arrays to better suit the requirements of your analysis or computations.
Reshaping:
• Reshaping allows you to change the dimensions of an array, converting it from one
shape to another without changing the data.
• It is particularly useful when you need to transform a 1D array into a 2D array (matrix)
or vice versa.

import numpy as np
# Creating a 1D array
arr_1d = np.array([1, 2, 3, 4, 5, 6])
# Reshaping to a 2D array (matrix)
arr_2d = arr_1d.reshape((2, 3))
print("Original 1D array:")
print(arr_1d)
print("Reshaped 2D array:")
print(arr_2d)
flattening:
• Flattening a multi-dimensional array means converting it into a 1D array.
• It is useful when you need to iterate through the elements of an array or when you want
to pass a flattened array to a function that expects a 1D input.

import numpy as np

# Creating a 2D array (matrix)


arr_2d = np.array([[1, 2, 3], [4, 5, 6]])

# Flattening the array


arr_flattened = arr_2d.flatten()
print("Original 2D array:")
print(arr_2d)

print("\nFlattened 1D array:")
print(arr_flattened)
9. a Explain the following string methods
i) Strip ii) split iii) join
Ans. i) strip() Method:
The strip() method is used to remove leading and trailing whitespaces
(including newline characters) from a string.

text = " Python is awesome! "


stripped_text = text.strip()
print("Original text:", text)
print("Stripped text:", stripped_text)
ii) split() Method:
The split() method is used to split a string into a list of substrings based on a
specified delimiter. By default, the delimiter is a whitespace.

sentence = "Python is powerful and versatile"


words = sentence.split()
print("Original sentence:", sentence)
print("Split words:", words)
iii) join() Method: The join() method is used to concatenate elements of an iterable
(such as a list) into a single string, using a specified separator..

words = ["Python", "is", "amazing"]


sentence = " ".join(words)
print("List of words:", words)
print("Joined sentence:", sentence)
9 b. Write a Python program that accepts a string and calculates the number of digits and letters.
Ans.

def count_digits_and_letters(input_string):
# Initialize counters
num_digits = 0
num_letters = 0

# Iterate through each character in the string


for char in input_string:
# Check if the character is a digit
if char.isdigit():
num_digits += 1
# Check if the character is a letter
elif char.isalpha():
num_letters += 1

return num_digits, num_letters

# Input from the user


user_input = input("Enter a string: ")

# Call the function to count digits and letters


digits, letters = count_digits_and_letters(user_input)

# Display the results


print("Number of digits:", digits)
print("Number of letters:", letters)

Enter a string: abc123


Number of digits: 3
Number of letters: 3
10. a.Ilustrate about the types of arrays and implementing arrays in Python. [CO2, L2]
Ans. In Python, the most commonly used array-like data structures are lists and NumPy arrays.
1. Lists:
Definition:
A list is a built-in data type in Python that represents an ordered, mutable sequence of
elements.
Implementation:
Lists are created using square brackets [].
Example:

fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']


2. NumPy Arrays:
Definition:
NumPy is a powerful numerical computing library in Python that provides support for
arrays, matrices, and a large collection of mathematical functions.
Implementation:
NumPy arrays are created using the numpy.array() constructor.
Example:

import numpy as np
my_array = np.array([[1, 2, 3], [4, 5, 6]])
10 b. Demonstrate the following array functions with suitable example.[CO2, L3]
i) append() ii)extend() iii)insert()
Ans. i) append():
The append() function is used to add a single element to the end of the list.

fruits = ['apple', 'banana', 'orange']


fruits.append('grape')
print("Updated list after append():", fruits)

ii) extend():
The extend() function is used to append the elements of an iteration to the end of the
list.

fruits = ['apple', 'banana', 'orange']


additional_fruits = ['grape', 'kiwi', 'mango']
# Extend the original list with additional fruits
fruits.extend(additional_fruits)
print("Updated list after extend():", fruits)
iii) insert():
The insert() function is used to insert an element at a specified index in the list.

fruits = ['apple', 'banana', 'orange']


# Insert a new fruit at index 1
fruits.insert(1, 'grape')
# Display the updated list
print("Updated list after insert():", fruits)
11. a.Explain about any five string handling functions with suitable examples. [CO2, L3]
Ans.
i) strip() Method:
The strip() method is used to remove leading and trailing whitespaces
(including newline characters) from a string.

text = " Python is awesome! "


stripped_text = text.strip()
print("Original text:", text)
print("Stripped text:", stripped_text)
ii) split() Method:
The split() method is used to split a string into a list of substrings based
on a specified delimiter. By default, the delimiter is a whitespace.

sentence = "Python is powerful and versatile"


words = sentence.split()
print("Original sentence:", sentence)
print("Split words:", words)
iii) join() Method:
The join() method is used to concatenate elements of an iterable(such
as a list) into a single string, using a specified separator..

words = ["Python", "is", "amazing"]


sentence = " ".join(words)
print("List of words:", words)
print("Joined sentence:", sentence)
iv) upper() and lower() Method:
The upper() function converts all characters in a string to uppercase,
while the lower() function converts them to lowercase.

text = "Hello, World!"


print("Uppercase:", text.upper())
print("Lowercase:", text.lower())

v) replace() Method:
The replace() function is used to replace a specified substring with
another substring in a string.

my_string = "Hello, World!"


modified_string = my_string.replace('Hello', 'Hi')
print("Modified string:", modified_string)
11 b.Write a python program to find maximum element in each column, minimum element in
each row and sum of elements in each row using numpy?
Ans.

import numpy as np

# Create a 2D NumPy array


matrix = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

# Find maximum element in each column


max_in_columns = np.max(matrix, axis=0)

# Find minimum element in each row


min_in_rows = np.min(matrix, axis=1)

# Find sum of elements in each row


sum_of_rows = np.sum(matrix, axis=1)

# Display the results


print("Original Matrix:")
print(matrix)

print("Maximum Element in Each Column:")


print(max_in_columns)

print("Minimum Element in Each Row:")


print(min_in_rows)

print("Sum of Elements in Each Row:")


print(sum_of_rows)

Original Matrix:
[[1 2 3]
[4 5 6]
[7 8 9]]
Maximum Element in Each Column: [7 8 9]
Minimum Element in Each Row: [1 4 7]
Sum of Elements in Each Row: [ 6 15 24]
12 a. Define what is a function? Explain about Function declaration, definition and function call
in Python. .[CO3, L2]
Ans. A function in Python is a block of organized, reusable code that performs a specific task.
1. Function Declaration:
• Syntax: def function_name(parameters):
• Functions are declared using the def keyword, followed by the function name and
parameters enclosed in parentheses. The colon indicates the beginning of the
function block.

def greet(name):
print("Hello, " + name + "!")
2. Function Definition:
• The function definition is the actual implementation of the function. It consists of
a block of statements that execute when the function is called.

def greet(name):
print("Hello, " + name + "!")

# Function call
greet("Alice")
3. Function Call:
• A function is called by using its name followed by parentheses containing the
arguments (values) for the parameters defined in the function declaration

# Full Example:
# Function declaration
def add_numbers(x, y):
sum_result = x + y
return sum_result

# Function call
result = add_numbers(3, 4)

# Display the result


print("Sum:", result)
12 b.List the different types of arguments/parameters used in functions with suitable examples?
Ans. In Python, functions can have different types of parameters, allowing flexibility in how
arguments are passed to them.
1. Positional Arguments:
These are the most common type of arguments, where the values are passed in
the order they are defined in the function.

def add_numbers(x, y):


sum_result = x + y
return sum_result
result = add_numbers(3, 4)

2. Keyword Arguments:
Values are passed to the function using the parameter names, which
allows you to specify the order explicitly.

def greet(name, age):


print("Hello, " + name + "! You are " + str(age) + " years old.")
greet(name="Alice", age=25)
3. Arbitrary Keyword Arguments:
Functions can receive an arbitrary number of keyword arguments using
the **kwargs syntax.

def print_person_info(**kwargs):
for key, value in kwargs.items():
print(key, value)
print_person_info(name="Bob", age=30, city="New York")
4. Unpacking Arguments::
You can use the * and ** operators to unpack arguments from iterables
or dictionaries.

def add_three_numbers(a, b, c):


sum_result = a + b + c
return sum_result

numbers = [1, 2, 3]
result = add_three_numbers(*numbers)
13. a. Define Recursion and python Recursive function? [CO2, L3]
Ans.
Recursion:
Recursion is a programming concept where a function calls itself directly or
indirectly to solve a problem.
A recursive function consists of two parts:
• Base Case(s): A condition that stops the recursion. It defines the simplest
version of the problem, and the function returns a result without making further
recursive calls.
• Recursive Case(s): The function calls itself with a smaller or simpler
version of the problem. The recursion continues until the base case is reached
Python Recursive Function:

def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: n! = n * (n-1)!
else:
return n * factorial(n - 1)

# Example usage
result = factorial(5)
print("Factorial of 5:", result)

.
13 b. Write a recursive Python function that recursively computes sum of elements in a list of
lists. Sample Input: [1,2, [3,4], [5,6]] Expected Result: 21 [CO3,L3]
Ans.
def recursive_list_sum(lst):
total = 0
for element in lst:
if type(element) == list:
total += recursive_list_sum(element)
else:
total += element
return total

sample_input = [1, 2, [3, 4], [5, 6]]


result = recursive_list_sum(sample_input)

print("Sample Input:", sample_input)


print("Expected Result:", result)
14.a. Analyze the basic list operations in detail with suitable examples.[CO3,L2]
Ans.
1. Creating a List:
Lists are created using square brackets [].Elements can be of any data type.

lis = [1, 2, 3, 'a', 'b']


2. Accessing Elements:
Elements in a list are accessed using index notation (starting from 0).

lis = [1, 2, 3, 'a', 'b']


print(my_list[2]) # Output: 3
3. Slicing:
Slicing allows you to extract a portion of the list.

my_list = [1, 2, 3, 4, 5]
sliced_list = my_list[1:4]
print(sliced_list) # Output: [2, 3, 4]
4. Appending Elements:
The append() method adds an element to the end of the list.

my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
5. Extending a List:
The extend() method adds elements from another iterable to the end of the list.

my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
6. Removing Elements:
The remove() method removes the first occurrence of a specified value.

my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
7. Finding the Index of an Element::
The index() method returns the index of the first occurrence of a specified value.

my_list = [1, 2, 3, 2]
index_of_2 = my_list.index(2)
print(index_of_2) # Output: 1
14 b. Build a python program to demonstrate various list operation? [CO3,L3].
Ans.

# Creating a list
my_list = [1, 2, 3, 4, 5]
print("Original List:", my_list)

# Accessing elements
print("Element at index 2:", my_list[2])

# Slicing
sliced_list = my_list[1:4]
print("Sliced List:", sliced_list)

# Appending elements
my_list.append(6)
print("After Appending 6:", my_list)

# Extending a list
additional_elements = [7, 8]
my_list.extend(additional_elements)
print("After Extending with [7, 8]:", my_list)

# Inserting elements
my_list.insert(2, 10)
print("After Inserting 10 at index 2:", my_list)

# Removing elements
my_list.remove(4)
print("After Removing 4:", my_list)

# Finding the index of an element


index_of_3 = my_list.index(3)
print("Index of 3:", index_of_3)

# Checking if an element is in the list


is_present = 7 in my_list
print("Is 7 present in the list:", is_present)
15. a. Discuss the following with suitable example? [CO3, L3]
i) Lambda function ii) Map function iii) Reduce function
Ans.
i) Lambda function:
A lambda function, also known as an anonymous function, is a concise way to
create small, unnamed functions.
The syntax for a lambda function is lambda arguments: expression
Lambda functions are often used for short-term operations and can take any
number of arguments but can only have one expression.

add_lambda = lambda x, y: x + y

result_lambda = add_lambda(3, 4)

print("Result:", result_lambda)
` ii) Map function:
The map() function applies a given function to all the items in an input iterable
(lists, tuples, etc.) and returns an iterator that produces the results. It takes two
arguments: the function to apply and the iterable.

# Using map to square each element in a list


numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
` iii) Reduce function:
The reduce() function is part of the functools module and successively
applies a binary function to the items of an iterable, from left to right, so as to
reduce the iterable to a single cumulative result.

from functools import reduce

# Using reduce to find the product of all elements in a list


numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)

print("Original List:", numbers)


print("Product of List:", product)
15 b. Write a python program to implement basic calculator using functions? [CO3,L3]

def add(x, y):


return x + y

def subtract(x, y):


return x – y

def multiply(x, y):


return x * y

def divide(x, y):


if y != 0:
return x / y
else:
return "Cannot divide by zero."

# Main calculator function


def calculator():
print("Basic Calculator")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

choice = input("Enter choice (1/2/3/4): ")

if choice in ('1', '2', '3', '4'):


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print("Result:", add(num1, num2))
elif choice == '2':
print("Result:", subtract(num1, num2))
elif choice == '3':
print("Result:", multiply(num1, num2))
elif choice == '4':
print("Result:", divide(num1, num2))
else:
print("Invalid input. Please enter a valid choice.")
# Call the calculator function
calculator()
16. a.Discuss about various methods to process lists with example? [CO3,L3]
Ans.
1. Iteration with for Loop:
Using a for loop to iterate through each element in the list.

numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)

2. List Comprehensions:
A concise way to create lists and apply operations to each element.

numbers = [1, 2, 3, 4, 5]
squared_numbers = [num**2 for num in numbers]
print(squared_numbers)

3. Map Function:
Using the map() function to apply a function to each element.

numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers)

3. Filter Function:
Using the filter() function to filter elements based on a condition.

numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
4. Reduce Function::
Using the reduce() function from the functools module to perform a
cumulative operation on the elements.

from functools import reduce


numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)
16 b. Describe about List Comprehension. Write a python program to find even numbers in a
list using List Comprehension? [CO3,L3]
Ans.
List Comprehension:
• List comprehension is a concise way to create lists in Python.
• It provides a compact syntax for creating a new list by specifying the
expression to evaluate and the iterable to loop over.
• It is often used to apply an operation to each element of an existing iterable and
create a new list from the results
Syntax:

new_list = [expression for item in iterable if condition]

Finding Even Numbers in a List using List Comprehension:

# Original list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# List comprehension to find even numbers


even_numbers = [num for num in numbers if num % 2 == 0]

# Display the result


print("Original List:", numbers)
print("Even Numbers:", even_numbers)

Original List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


Even Numbers: [2, 4, 6, 8, 10]

*****

You might also like