Font size
Worksheetsfunctions, file, random , date, math
Total questions: 83
Worksheet time: 40mins
What is the purpose of the try block in Python error handling?
To define the block of code where an exception may occur
To catch and handle exceptions that occur within the block
To ensure that the code executes without any errors
To terminate the program if an exception occurs
What will happen if an exception is raised inside the try block and there is no corresponding except block to handle it?
The program will terminate
The exception will be ignored
The program will enter an infinite loop
The program will continue executing the code after the try-except block
Which of the following statements about exceptions in Python is true?
All exceptions are errors
Exceptions can only be handled with try-except blocks
Exceptions can be raised explicitly using the raise keyword
Exceptions can only occur in the main block of code
What is the purpose of the except block in Python exception handling?
To define the block of code where an exception may occur
To catch and handle exceptions that occur within the try block
To ensure that the code executes without any errors
To terminate the program if an exception occurs
Which of the following is a built-in exception in Python?
StopIteration
ExceptionalError
BreakException
ProgramHalt
What will be the output of the following code? try: x = 10 / 0 except ZeroDivisionError: print("Divide by zero error") except: print("Other error")
“Divide by zero error”
“Other error”
Nothing will be printed
Error: division by zero
What is the purpose of the finally block in Python exception handling?
To define the block of code where an exception may occur
To catch and handle exceptions that occur within the try block
To ensure that the code executes without any errors
To execute cleanup code, whether an exception occurs or not
What is the output of the following code? try: raise NameError("Custom error") except NameError as e: print(e)
“Custom error”
“NameError: Custom error”
“Error: Custom error”
NameError: Custom error
What does the following code snippet do? try: x = int("abc") except ValueError: print("Invalid literal for int()") finally: print("Finally block executed")
Attempts to convert a string to an integer and prints an error message if it fails
Prints “Finally block executed” regardless of the outcome
Raises a ValueError exception
Terminates the program
What will be the output of the following code? try: raise IndexError("Index out of range") except ValueError: print("ValueError") except IndexError: print("IndexError") except Exception: print("Exception")
“ValueError”
“IndexError”
“Exception”
“Index out of range”
What will happen if an exception is raised but not caught in a Python program?
The program will continue executing normally
The program will terminate with an error message
The program will pause and wait for user input
The program will enter an infinite loop
What will be the output of the following code? try: x = int(input("Enter a number: ")) except ValueError: print("Invalid input") else: print("You entered:", x)
“Invalid input”
“You entered:
Nothing will be printed
Error: invalid literal for int() with base 10: ‘’
Which of the following is true about the else block in Python exception handling?
The else block is executed if an exception occurs
The else block is always executed after the except block
The else block is executed if no exceptions occur in the try block
The else block is optional in exception handling
What does the following code snippet do? try: assert 5 > 10, "AssertionError" except AssertionError as e: print(e) finally: print("Finally block executed")
Raises an AssertionError and prints “AssertionError”, followed by “Finally block executed”
Raises an AssertionError and prints “False”, followed by “Finally block executed”
Raises an AssertionError and prints “5 > 10”, followed by “Finally block executed”
Raises no error and prints “Finally block executed”
Which of the following is a built-in exception type in Python?
ProgramError
SystemError
ExecutionError
LogicalError
Which of the following is a valid reason to use custom exceptions in Python?
To replace built-in exceptions
To handle unexpected errors
To confuse the programmer
To reduce code readability
What is the output of the following code? try: raise KeyError("Key not found") except ValueError: print("ValueError") except KeyError as e: print(e)
“ValueError”
“KeyError: Key not found”
“Key not found”
Nothing will be printed
What keyword is used to define a function in Python?
def
function
define
func
What is the purpose of the return statement in a function?
To stop the execution of the function
To print a value to the console
To return a value to the caller
To define a recursive function
Which of the following statements about function arguments in Python is true?
All arguments must have default values
Functions cannot have more than one argument
Arguments are passed by value
Arguments can have default values
What is the purpose of the **kwargs parameter in a Python function definition?
To accept a variable number of positional arguments
To accept keyword arguments as a dictionary
To specify default values for keyword arguments
To raise an exception
What will be the output of the following code snippet? def multiply(*args): result = 1 for num in args: result *= num return result print(multiply(2, 3, 4))
24
9
10
None
What is the purpose of the global keyword in Python?
To define a variable inside a function
To access a variable outside a function
To modify a variable defined in the global scope from within a function
To specify a variable as constant
What will be the output of the following code snippet? x = 5 def modify(): global x x = 10 modify() print(x)
5
10
Error
None
What is the purpose of the lambda keyword in Python?
To define anonymous functions
To define a variable
To import modules
To handle exceptions
What will be the output of the following code snippet? square = lambda x: x ** 2 print(square(5))
10
25
5
None
What is a recursive function?
A function that calls itself
A function with multiple return statements
A function that returns a dictionary
A function that takes multiple arguments
What is a recursive function’s base case?
The function call that starts the recursion
The function call that ends the recursion
The maximum number of recursive calls allowed
The function’s return value
Which of the following is true about variable scope in Python?
Local variables can be accessed outside the function in which they are defined
Global variables take precedence over local variables
Variables defined inside a function have global scope
Variables defined inside a function have local scope
What will be the output of the following code snippet? def square(x): return x ** 2 numbers = [1, 2, 3, 4] squared_numbers = map(square, numbers) print(list(squared_numbers))
[1, 4, 9, 16]
[1, 2, 3, 4]
[2, 4, 6, 8]
[1, 3, 5, 7]
What will be the output of the following code snippet? def add(a, b): return a + b def subtract(a, b): return a - b operations = {'add': add, 'subtract': subtract} result1 = operations['add'](5, 3) result2 = operations['subtract'](7, 2) print(result1, result2)
8 5
2 5
5 2
8 7
What is a Python module?
A built-in function
A collection of Python functions and global variables
A type of Python data structure
A programming language
Which keyword is used to import a module in Python?
use
require
import
include
What is the purpose of the ‘sys’ module in Python?
To provide access to operating system functionality
To handle file I/O operations
To manipulate strings
To provide access to command-line arguments
Which of the following statements is true about packages in Python?
Packages are collections of modules
Packages are collections of functions
Packages are used for mathematical operations
Packages are used for string manipulation
What is the purpose of the ‘os’ module in Python?
To handle mathematical operations
To interact with the operating system
To manipulate strings
To handle file I/O operations
Which keyword is used to create an alias while importing a module in Python?
as
alias
rename
with
How can you install a third-party module in Python?
by copying the module file into the Python installation directory
using the ‘pip’ command followed by the module name
by downloading the module from a website and including it in your project directory
by importing the module directly from the internet
What is the purpose of the ‘csv’ module in Python?
To handle file I/O operations
To manipulate strings
To perform mathematical operations
To read and write CSV files
What does the filter() function in Python do?
Applies a function to every item in an iterable and returns a single cumulative value
Filters out elements of an iterable based on a given function
Returns a subset of elements from an iterable based on a condition
Maps a function to every item in an iterable and returns a list of the results
Which module is required to use the reduce() function in Python?
math
functools
itertools
operator
Which of the following statements about the lambda function in Python is true?
The lambda function can contain multiple expressions.
The lambda function can have a return statement.
The lambda function can have default arguments.
The lambda function can only have a single expression.
What will be the output of the following code? def even_check(num): if num % 2 == 0: return True else: return False numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = filter(even_check, numbers) print(list(even_numbers))
[1, 3, 5, 7, 9]
[2, 4, 6, 8, 10]
[True, False, True, False, True, False, True, False, True, False]
[2, 4, 6, 8]
Which of the following is equivalent to the map() function?
List comprehension
Generator expression
Iterator
Filter function
Which function can be used to combine elements of an iterable using a specified function and reduce it to a single value?
apply()
join()
reduce()
combine()
What will be the output of the following code? def is_vowel(char): vowels = 'aeiouAEIOU' return char in vowels chars = ['a', 'b', 'c', 'd', 'e', 'F', 'G', 'H', 'I', 'j'] filtered_chars = filter(is_vowel, chars) print(list(filtered_chars))
[‘a’, ‘e’, ‘F’, ‘I’]
[‘a’, ‘e’, ‘I’]
[‘a’, ‘e’, ‘A’, ‘E’, ‘I’]
[‘a’, ‘e’]
What function is used to open a file in Python for reading?
open_file()
read_file()
open()
read()
Which mode is used to open a file for writing in Python?
r
w
a
x
What function is used to read the entire contents of a file as a string in Python?
read_file()
read_string()
readlines()
read()
In Python, what does the readline() function do?
Reads the entire file as a string
Reads a specific line from the file
Reads all the lines from the file
Reads the first line from the file
Which mode is used to open a file for appending in Python?
r
w
a
x
What method is used to close a file object in Python?
close()
shutdown()
end()
terminate()
Which function is used to write data to a file in Python?
write()
append()
add()
insert()
Which method is used to check if a file exists in Python?
exists()
check_file()
isfile()
file_exists()
Which mode is used to open a file for reading and writing in Python?
r
w
r+
w+
What function is used to move the file cursor to a specific position in a file in Python?
seek()
move_cursor()
set_position()
position()
What does the tell() method do in Python file handling?
Returns the current line number being read
Returns the current position of the file cursor
Tells if the file exists or not
Tells the file size
Which of the following statements is true about reading files in Python?
The read() method reads one line at a time
The readline() method reads the entire file at once
The readlines() method reads one character at a time
The read() method reads the entire file at once
What is the output of the following code? file = open("data.txt", "w") file.write("Hello, World!") file.close()
It writes “Hello, World!” to the file data.txt
It reads “Hello, World!” from the file data.txt
It appends “Hello, World!” to the file data.txt
It does nothing
Which of the following is used to open a file in Python in binary mode?
open(‘file.txt’, ‘b’)
open(‘file.txt’, ‘binary’)
open(‘file.txt’, ‘rb’)
open(‘file.txt’, ‘wb’)
What is the purpose of the os.path.isfile() function in Python?
To create a new file
To check if a file exists
To read the contents of a file
To write data to a file
Which method is used to write multiple lines to a file in Python?
writelines()
write_lines()
write_multiple_lines()
append_lines()
Which module is used for reading and writing CSV files in Python?
os
csv
pandas
sys
What is the output of the following code? with open('data.txt', 'r') as file: print(file.read())
Prints the contents of data.txt
Reads the contents of data.txt into a variable
Raises a FileNotFoundError
Writes to data.txt
Which method is used to read CSV files in Python?
read_csv()
read()
csv_read()
csv.reader()
How do you read only the first n characters from a file in Python?
Using the read(n) method
Using the readlines(n) method
Using the readline(n) method
Using the read_first(n) method
What will be the output of the following Python code?
from math import factorial
print(math.factorial(5))
120
Nothing is printed
Error, method factorial doesn’t exist in math module
Error, the statement should be: print(factorial(5))
exp(),floor()belongs which module?
cmath.py
urlib.py
math.py
statistics.py
Which of the following is a Python library used for numerical computations?
Matplotlib
NumPy
Pandas
SciPy
Which operator is used in python to import all modules from packages?
. operator
* operator
-> symbol
, operator
(a) which function helps to display all information including docstring ,function name and constant in a module.
random.randrange(6)
0,1,2,3,4,5,6
1,2,3,4,5,6
0,1,2,3,4,5
1,2,3,4,5
random.randint(3,8)
4,5,6,7
3,4,5,6,7
3,4,5,6,7,8
0,1,2,3,4,5,6,7,8
random.random() generates a floating point number between _____ and ______
1 and 2
1 and 0
0 and 1
0 and 10
names = np.array(["Reem" , "Salah" , "Haya" , "Maryam" , "Fatema"])
print(names[[2,3,4]])
Mark the right output from the below options
[ 'Haya' 'Maryam' 'Fatema' ]
[ 'Maryam' 'Haya' 'Fatema' ]
[ 'Reem' 'Salah' 'Fatema' ]
[ 'Reem' 'Salah' 'Haya' ]
What output will the image above produce?
[ [ 65. 60. 70. 58.
1.70. 1.65. 1.72. 1.60. ]]
[ [ 1.70. 1.65. 1.72. 1.60
65. 60. 70. 58. ] ]
How we can find the type of numpy array in python?
dtype
typei
type
itype
x=np.array([10,20,30,40,50,60,70])
print(np.median(x))
Find the output
35
35.0
40
37.7
What will be the output of the following code:
import numpy as np
a = np.array([[0, 1, 2], [3, 4, 5]])
b = a.sum(axis=1)
print (b)
3
12
[3 12]
[3 5 7]
What function in the datetime module is used to get the current date and time?
datetime.now()
datetime.current()
datetime.today()
datetime.get()
Which method is used to format a datetime object as a string in Python?
to_string()
stringify()
strftime()
format()
What is the output of the following code snippet? from datetime import datetime print(datetime.now())
Current time only
Current date and time
Current date only
None
How can you create a datetime object representing January 1, 2023, at 12:00 PM?
datetime(2023, 1, 1, 12, 0)
datetime.new(2023, 1, 1, 12, 0)
datetime.create(2023, 1, 1, 12, 0)
datetime.make(2023, 1, 1, 12, 0)
