Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

🐍

Python
1 Marks Questions
a) What is dry run in Python?
Answer:

A dry run in Python refers to the process of mentally or manually simulating


the execution of a piece of code without actually running it on a computer. It
is a technique used by programmers to understand and analyze the flow of
the program, identify potential errors, and verify the logic without the need for
actual execution. During a dry run, variables and their values are tracked
step by step, and the program's behavior is traced without executing the
code on a computer.

b) Give the purpose of selection statements in Python.


Answer:

Selection statements in Python, such as if , elif (else if), and else , serve
the purpose of controlling the flow of a program based on certain conditions.
They allow the program to make decisions and execute different blocks of
code depending on whether a given condition is true or false. Selection
statements enable developers to implement conditional logic, making
programs more dynamic and responsive to different scenarios.

c) List the types of type conversion in Python.


Answer:

The types of type conversion in Python are:

1. Implicit Type Conversion (or Coercion): Automatically performed by


the interpreter.

2. Explicit Type Conversion (or Casting): Manually performed by the


programmer using functions like int() , float() , str() , etc.

Python 1
d) What is the use of the pass statement?
Answer:

The pass statement in Python is a no-operation statement. It serves as a


placeholder or a do-nothing statement when syntactically some code is
required, but no action is desired or necessary. It is often used as a
temporary placeholder during development to avoid syntax errors.

e) Explain the function enumerate() .


Answer:

The enumerate() function in Python is used to iterate over a sequence (such


as a list, tuple, or string) while keeping track of both the index and the
corresponding value of each item. It returns pairs of index and item as
tuples. This function is commonly used in for loops when you need both the
index and the value of each element.

f) Explain the extend method of a list.


Answer:

The extend() method in Python is used to append the elements of an


iterable (e.g., a list, tuple, or string) to the end of an existing list. It modifies
the original list by adding elements from the iterable.

g) What are required arguments in a function?


Answer:

Required arguments in a function are the parameters that must be passed


during a function call for it to execute successfully. They are mandatory, and
the number of arguments passed must match the number of parameters
defined in the function.

h) Explain any 2 functions in the time module.


Answer:

Two functions in the time module:

1. time.time(): Returns the current time in seconds since the epoch


(January 1, 1970, 00:00:00 UTC).

Python 2
2. : Suspends the execution of the current thread for the
time.sleep(seconds)

specified number of seconds.

i) What are the types of files in Python?


Answer:

The types of files in Python include:

1. Text Files ( 't' or default): Contain human-readable text and are


opened in text mode.

2. Binary Files ( 'b' ): Contain non-human-readable data (e.g., images,


executables) and are opened in binary mode.

j) Write the use of seek & tell functions.


Answer:

The seek(offset, whence) function is used to change the current file position
in a file, and the tell() function returns the current file position.

2 Marks Questions
a) How to handle exception in Python?
Answer:

Exception handling in Python is done using the try , except , else , and
finally blocks.

try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError as e:
# Handling specific exception
print(f"Error: {e}")
except Exception as e:
# Handling other exceptions
print(f"An error occurred: {e}")
else:
# Code to execute if no exception occurred

Python 3
print("No exception occurred.")
finally:
# Code that will be executed in any case
print("Finally block.")

b) Explain any 2 metacharacters used in regular expression.


Answer:

1. . (Dot): Matches any character except a newline ( \n ). For example, the


pattern a. would match "ab," "ac," etc.

2. (Asterisk): Matches zero or more occurrences of the preceding character


or group. For example, the pattern ab* would match "a," "ab," "abb," and so
on.

c) Explain any 2 built-in list functions.


Answer:

1. len() : Returns the number of elements in a list.

my_list = [1, 2, 3, 4, 5]
length = len(my_list) # Result: 5

2. append() : Adds an element to the end of a list.

my_list = [1, 2, 3]
my_list.append(4) # Result: [1, 2, 3, 4]

d) Explain backward indexing in strings.


Answer:

Backward indexing in strings allows accessing characters from the end of the
string using negative indices. The last character has index 1 , the second-to-
last has index 2 , and so on.

Python 4
my_string = "Hello"
last_char = my_string[-1] # Result: 'o'
second_last_char = my_string[-2] # Result: 'l'

e) Define identifiers.
Answer:

Identifiers in Python are names given to variables, functions, classes,


modules, or any other entities in the code. They follow certain rules:

Must begin with a letter (a-z, A-Z) or an underscore ( _ ).

Subsequent characters can be letters, underscores, or digits (0-9).

Case-sensitive ( variable and Variable are different identifiers).

Cannot be a reserved word (keyword) in Python.

4 Marks Questions
a) Write a Python program to check if a given number is
Armstrong.

def is_armstrong(number):
num_str = str(number)
order = len(num_str)
sum_of_digits = sum(int(digit) ** order for digit in num_
return sum_of_digits == number

# Example usage:
num = 153
if is_armstrong(num):
print(f"{num} is an Armstrong number.")
else:
print(f"{num} is not an Armstrong number.")

Python 5
b) Write a Python program to display the power of 2 using an
anonymous function.

power_of_two = lambda x: 2 ** x

# Example usage:
exponent = 4
result = power_of_two(exponent)
print(f"2^{exponent} is {result}")

c) Write a Python program to print even-length words in a string.

def even_length_words(input_string):
words = input_string.split()
even_length_words_list = [word for word in words if len(wo
return even_length_words_list

# Example usage:
sentence = "This is a sample sentence for demonstration"
result = even_length_words(sentence)
print("Even-length words:", result)

4 Marks Questions
a) Write a Python program to check for Zero Division Error
Exception.

def divide_numbers(num1, num2):


try:
result = num1 / num2
print(f"The result of {num1} divided by {num2} is: {re
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

Python 6
# Example usage:
divide_numbers(10, 2) # Normal division
divide_numbers(5, 0) # Division by zero error

b) Write a Python program to find the GCD of a number using


recursion.

def gcd_recursive(a, b):


if b == 0:
return a
else:
return gcd_recursive(b, a % b)

# Example usage:
num1 = 48
num2 = 18
result = gcd_recursive(num1, num2)
print(f"The GCD of {num1} and {num2} is: {result}")

c) Write a Python program to check if a given key already exists


in a dictionary.

def key_exists(dictionary, key):


return key in dictionary

# Example usage:
sample_dict = {'a': 1, 'b': 2, 'c': 3}
search_key = 'b'
if key_exists(sample_dict, search_key):
print(f"The key '{search_key}' exists in the dictionary."
else:
print(f"The key '{search_key}' does not exist in the dicti

Python 7
3 Marks Questions
a) Trace the output of the following code:

pythonCopy code
sum = 0
for i in range(12, 2, -2):
sum += i
print(sum)

Explanation:

The range(12, 2, -2) generates a sequence of numbers from 12 to 3 (exclusive)


with a step of -2.

The loop iterates over these numbers, and each value is added to the sum .

The print(sum) statement outputs the final sum.

Let's trace the loop:

Iteration 1: sum += 12 (sum is now 12)

Iteration 2: sum += 10 (sum is now 22)

Iteration 3: sum += 8 (sum is now 30)

Iteration 4: sum += 6 (sum is now 36)

Iteration 5: sum += 4 (sum is now 40)

Iteration 6: sum += 2 (sum is now 42)

So, the output of the code is 42 .

b) Trace the output of the following code:

pythonCopy code
count = 1
def doThis():
global count
for i in (1, 2, 3):
count += 1
doThis()

Python 8
print(count)

Explanation:

The function doThis is defined, which contains a for loop iterating over the
values (1, 2, 3).

The global variable count is incremented by 1 for each iteration in the loop.

The function doThis is then called.

After calling the function, the print(count) statement outputs the final value of
count .

Let's trace the code:

Inside doThis :

Iteration 1: count += 1 (count is now 2)

Iteration 2: count += 1 (count is now 3)

Iteration 3: count += 1 (count is now 4)

After calling doThis , the final value of count is 4.

So, the output of the code is 4 .

Python 9

You might also like