Python QB Answers Mid-1
Python QB Answers Mid-1
PART-A
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:
import numpy as np
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:
Output Statements:
In Python, the print() function is used to display output.
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.
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.")
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.
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:
if inner_condition:
else:
else:
score = int(input())
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.
# Initialize variables
sum_of_numbers = 0
count = 1
# 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 = []
# Example usage:
input_array = [1, 2, 3, 4, 2, 3, 5]
result_array = remove_duplicates(input_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:
name = "Alice"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
5. Searching in Strings:
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
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.
def count_digits_and_letters(input_string):
# Initialize counters
num_digits = 0
num_letters = 0
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.
ii) extend():
The extend() function is used to append the elements of an iteration to the end of the
list.
v) replace() Method:
The replace() function is used to replace a specified substring with
another substring in a string.
import numpy as np
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)
2. Keyword Arguments:
Values are passed to the function using the parameter names, which
allows you to specify the order explicitly.
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.
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
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)
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.
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.
# Original list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
*****