wayground logo

Free Printable Worksheets

Font size

S
M
L
XL
Worksheets

functions, file, random , date, math

Total questions: 83

Worksheet time: 40mins

Name
Class
Date
1.

What is the purpose of the try block in Python error handling?

a)

To define the block of code where an exception may occur

b)

To catch and handle exceptions that occur within the block

c)

To ensure that the code executes without any errors

d)

To terminate the program if an exception occurs

2.

What will happen if an exception is raised inside the try block and there is no corresponding except block to handle it?

a)

The program will terminate

b)

The exception will be ignored

c)

The program will enter an infinite loop

d)

The program will continue executing the code after the try-except block

3.

Which of the following statements about exceptions in Python is true?

a)

All exceptions are errors

b)

Exceptions can only be handled with try-except blocks

c)

Exceptions can be raised explicitly using the raise keyword

d)

Exceptions can only occur in the main block of code

4.

What is the purpose of the except block in Python exception handling?

a)

To define the block of code where an exception may occur

b)

To catch and handle exceptions that occur within the try block

c)

To ensure that the code executes without any errors

d)

To terminate the program if an exception occurs

5.

Which of the following is a built-in exception in Python?

a)

StopIteration

b)

ExceptionalError

c)

BreakException

d)

ProgramHalt

6.

What will be the output of the following code? try: x = 10 / 0 except ZeroDivisionError: print("Divide by zero error") except: print("Other error")

a)

“Divide by zero error”

b)

“Other error”

c)

Nothing will be printed

d)

Error: division by zero

7.

What is the purpose of the finally block in Python exception handling?

a)

To define the block of code where an exception may occur

b)

To catch and handle exceptions that occur within the try block

c)

To ensure that the code executes without any errors

d)

To execute cleanup code, whether an exception occurs or not

8.

What is the output of the following code? try: raise NameError("Custom error") except NameError as e: print(e)

a)

“Custom error”

b)

“NameError: Custom error”

c)

“Error: Custom error”

d)

NameError: Custom error

9.

What does the following code snippet do? try: x = int("abc") except ValueError: print("Invalid literal for int()") finally: print("Finally block executed")

a)

Attempts to convert a string to an integer and prints an error message if it fails

b)

Prints “Finally block executed” regardless of the outcome

c)

Raises a ValueError exception

d)

Terminates the program

10.

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

a)

“ValueError”

b)

“IndexError”

c)

“Exception”

d)

“Index out of range”

11.

What will happen if an exception is raised but not caught in a Python program?

a)

The program will continue executing normally

b)

The program will terminate with an error message

c)

The program will pause and wait for user input

d)

The program will enter an infinite loop

12.

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)

a)

“Invalid input”

b)

“You entered:

c)

Nothing will be printed

d)

Error: invalid literal for int() with base 10: ‘

13.

Which of the following is true about the else block in Python exception handling?

a)

The else block is executed if an exception occurs

b)

The else block is always executed after the except block

c)

The else block is executed if no exceptions occur in the try block

d)

The else block is optional in exception handling

14.

What does the following code snippet do? try: assert 5 > 10, "AssertionError" except AssertionError as e: print(e) finally: print("Finally block executed")

a)

Raises an AssertionError and prints “AssertionError”, followed by “Finally block executed”

b)

Raises an AssertionError and prints “False”, followed by “Finally block executed”

c)

Raises an AssertionError and prints “5 > 10”, followed by “Finally block executed”

d)

Raises no error and prints “Finally block executed”

15.

Which of the following is a built-in exception type in Python?

a)

ProgramError

b)

SystemError

c)

ExecutionError

d)

LogicalError

16.

Which of the following is a valid reason to use custom exceptions in Python?

a)

To replace built-in exceptions

b)

To handle unexpected errors

c)

To confuse the programmer

d)

To reduce code readability

17.

What is the output of the following code? try: raise KeyError("Key not found") except ValueError: print("ValueError") except KeyError as e: print(e)

a)

“ValueError”

b)

“KeyError: Key not found”

c)

“Key not found”

d)

Nothing will be printed

18.

What keyword is used to define a function in Python?

a)

def

b)

function

c)

define

d)

func

19.

What is the purpose of the return statement in a function?

a)

To stop the execution of the function

b)

To print a value to the console

c)

To return a value to the caller

d)

To define a recursive function

20.

Which of the following statements about function arguments in Python is true?

a)

All arguments must have default values

b)

Functions cannot have more than one argument

c)

Arguments are passed by value

d)

Arguments can have default values

21.

What is the purpose of the **kwargs parameter in a Python function definition?

a)

To accept a variable number of positional arguments

b)

To accept keyword arguments as a dictionary

c)

To specify default values for keyword arguments

d)

To raise an exception

22.

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

a)

24

b)

9

c)

10

d)

None

23.

What is the purpose of the global keyword in Python?

a)

To define a variable inside a function

b)

To access a variable outside a function

c)

To modify a variable defined in the global scope from within a function

d)

To specify a variable as constant

24.

What will be the output of the following code snippet? x = 5 def modify(): global x x = 10 modify() print(x)

a)

5

b)

10

c)

Error

d)

None

25.

What is the purpose of the lambda keyword in Python?

a)

To define anonymous functions

b)

To define a variable

c)

To import modules

d)

To handle exceptions

26.

What will be the output of the following code snippet? square = lambda x: x ** 2 print(square(5))

a)

10

b)

25

c)

5

d)

None

27.

What is a recursive function?

a)

A function that calls itself

b)

A function with multiple return statements

c)

A function that returns a dictionary

d)

A function that takes multiple arguments

28.

What is a recursive function’s base case?

a)

The function call that starts the recursion

b)

The function call that ends the recursion

c)

The maximum number of recursive calls allowed

d)

The function’s return value

29.

Which of the following is true about variable scope in Python?

a)

Local variables can be accessed outside the function in which they are defined

b)

Global variables take precedence over local variables

c)

Variables defined inside a function have global scope

d)

Variables defined inside a function have local scope

30.

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

a)

[1, 4, 9, 16]

b)

[1, 2, 3, 4]

c)

[2, 4, 6, 8]

d)

[1, 3, 5, 7]

31.

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)

a)

8 5

b)

2 5

c)

5 2

d)

8 7

32.

What is a Python module?

a)

A built-in function

b)

A collection of Python functions and global variables

c)

A type of Python data structure

d)

A programming language

33.

Which keyword is used to import a module in Python?

a)

use

b)

require

c)

import

d)

include

34.

What is the purpose of the ‘sys’ module in Python?

a)

To provide access to operating system functionality

b)

To handle file I/O operations

c)

To manipulate strings

d)

To provide access to command-line arguments

35.

Which of the following statements is true about packages in Python?

a)

Packages are collections of modules

b)

Packages are collections of functions

c)

Packages are used for mathematical operations

d)

Packages are used for string manipulation

36.

What is the purpose of the ‘os’ module in Python?

a)

To handle mathematical operations

b)

To interact with the operating system

c)

To manipulate strings

d)

To handle file I/O operations

37.

Which keyword is used to create an alias while importing a module in Python?

a)

as

b)

alias

c)

rename

d)

with

38.

How can you install a third-party module in Python?

a)

by copying the module file into the Python installation directory

b)

using the ‘pip’ command followed by the module name

c)

by downloading the module from a website and including it in your project directory

d)

by importing the module directly from the internet

39.

What is the purpose of the ‘csv’ module in Python?

a)

To handle file I/O operations

b)

To manipulate strings

c)

To perform mathematical operations

d)

To read and write CSV files

40.

What does the filter() function in Python do?

a)

Applies a function to every item in an iterable and returns a single cumulative value

b)

Filters out elements of an iterable based on a given function

c)

Returns a subset of elements from an iterable based on a condition

d)

Maps a function to every item in an iterable and returns a list of the results

41.

Which module is required to use the reduce() function in Python?

a)

math

b)

functools

c)

itertools

d)

operator

42.

Which of the following statements about the lambda function in Python is true?

a)

The lambda function can contain multiple expressions.

b)

The lambda function can have a return statement.

c)

The lambda function can have default arguments.

d)

The lambda function can only have a single expression.

43.

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

a)

[1, 3, 5, 7, 9]

b)

[2, 4, 6, 8, 10]

c)

[True, False, True, False, True, False, True, False, True, False]

d)

[2, 4, 6, 8]

44.

Which of the following is equivalent to the map() function?

a)

List comprehension

b)

Generator expression

c)

Iterator

d)

Filter function

45.

Which function can be used to combine elements of an iterable using a specified function and reduce it to a single value?

a)

apply()

b)

join()

c)

reduce()

d)

combine()

46.

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)

[‘a’, ‘e’, ‘F’, ‘I’]

b)

[‘a’, ‘e’, ‘I’]

c)

[‘a’, ‘e’, ‘A’, ‘E’, ‘I’]

d)

[‘a’, ‘e’]

47.

What function is used to open a file in Python for reading?

a)

open_file()

b)

read_file()

c)

open()

d)

read()

48.

Which mode is used to open a file for writing in Python?

a)

r

b)

w

c)

a

d)

x

49.

What function is used to read the entire contents of a file as a string in Python?

a)

read_file()

b)

read_string()

c)

readlines()

d)

read()

50.

In Python, what does the readline() function do?

a)

Reads the entire file as a string

b)

Reads a specific line from the file

c)

Reads all the lines from the file

d)

Reads the first line from the file

51.

Which mode is used to open a file for appending in Python?

a)

r

b)

w

c)

a

d)

x

52.

What method is used to close a file object in Python?

a)

close()

b)

shutdown()

c)

end()

d)

terminate()

53.

Which function is used to write data to a file in Python?

a)

write()

b)

append()

c)

add()

d)

insert()

54.

Which method is used to check if a file exists in Python?

a)

exists()

b)

check_file()

c)

isfile()

d)

file_exists()

55.

Which mode is used to open a file for reading and writing in Python?

a)

r

b)

w

c)

r+

d)

w+

56.

What function is used to move the file cursor to a specific position in a file in Python?

a)

seek()

b)

move_cursor()

c)

set_position()

d)

position()

57.

What does the tell() method do in Python file handling?

a)

Returns the current line number being read

b)

Returns the current position of the file cursor

c)

Tells if the file exists or not

d)

Tells the file size

58.

Which of the following statements is true about reading files in Python?

a)

The read() method reads one line at a time

b)

The readline() method reads the entire file at once

c)

The readlines() method reads one character at a time

d)

The read() method reads the entire file at once

59.

What is the output of the following code? file = open("data.txt", "w") file.write("Hello, World!") file.close()

a)

It writes “Hello, World!” to the file data.txt

b)

It reads “Hello, World!” from the file data.txt

c)

It appends “Hello, World!” to the file data.txt

d)

It does nothing

60.

Which of the following is used to open a file in Python in binary mode?

a)

open(‘file.txt’, ‘b’)

b)

open(‘file.txt’, ‘binary’)

c)

open(‘file.txt’, ‘rb’)

d)

open(‘file.txt’, ‘wb’)

61.

What is the purpose of the os.path.isfile() function in Python?

a)

To create a new file

b)

To check if a file exists

c)

To read the contents of a file

d)

To write data to a file

62.

Which method is used to write multiple lines to a file in Python?

a)

writelines()

b)

write_lines()

c)

write_multiple_lines()

d)

append_lines()

63.

Which module is used for reading and writing CSV files in Python?

a)

os

b)

csv

c)

pandas

d)

sys

64.

What is the output of the following code? with open('data.txt', 'r') as file: print(file.read())

a)

Prints the contents of data.txt

b)

Reads the contents of data.txt into a variable

c)

Raises a FileNotFoundError

d)

Writes to data.txt

65.

Which method is used to read CSV files in Python?

a)

read_csv()

b)

read()

c)

csv_read()

d)

csv.reader()

66.

How do you read only the first n characters from a file in Python?

a)

Using the read(n) method

b)

Using the readlines(n) method

c)

Using the readline(n) method

d)

Using the read_first(n) method

67.

What will be the output of the following Python code?

from math import factorial

print(math.factorial(5))

a)

120

b)

Nothing is printed

c)

Error, method factorial doesn’t exist in math module

d)

Error, the statement should be: print(factorial(5))

68.

exp(),floor()belongs which module?

a)

cmath.py

b)

urlib.py

c)

math.py

d)

statistics.py

69.

Which of the following is a Python library used for numerical computations?

a)

Matplotlib

b)

NumPy

c)

Pandas

d)

SciPy

70.

Which operator is used in python to import all modules from packages?

a)

. operator

b)

* operator

c)

-> symbol

d)

, operator

71.

(a)   which function helps to display all information including docstring ,function name and constant in a module.

72.

random.randrange(6)

a)

0,1,2,3,4,5,6

b)

1,2,3,4,5,6

c)

0,1,2,3,4,5

d)

1,2,3,4,5

73.

random.randint(3,8)

a)

4,5,6,7

b)

3,4,5,6,7

c)

3,4,5,6,7,8

d)

0,1,2,3,4,5,6,7,8

74.

random.random() generates a floating point number between _____ and ______

a)

1 and 2

b)

1 and 0

c)

0 and 1

d)

0 and 10

75.

names = np.array(["Reem" , "Salah" , "Haya" , "Maryam" , "Fatema"])

print(names[[2,3,4]])

Mark the right output from the below options

a)

[ 'Haya' 'Maryam' 'Fatema' ]

b)

[ 'Maryam' 'Haya' 'Fatema' ]

c)

[ 'Reem' 'Salah' 'Fatema' ]

d)

[ 'Reem' 'Salah' 'Haya' ]

76.

What output will the image above produce?

a)

[ [ 65. 60. 70. 58.


1.70. 1.65. 1.72. 1.60. ]]

b)

[ [ 1.70. 1.65. 1.72. 1.60


65. 60. 70. 58. ] ]

77.

How we can find the type of numpy array in python?

a)

dtype

b)

typei

c)

type

d)

itype

78.

x=np.array([10,20,30,40,50,60,70])

print(np.median(x))


Find the output

a)

35

b)

35.0

c)

40

d)

37.7

79.

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)

a)

3

b)

12

c)

[3 12]

d)

[3 5 7]

80.

What function in the datetime module is used to get the current date and time?

a)

datetime.now()

b)

datetime.current()

c)

datetime.today()

d)

datetime.get()

81.

Which method is used to format a datetime object as a string in Python?

a)

to_string()

b)

stringify()

c)

strftime()

d)

format()

82.

What is the output of the following code snippet? from datetime import datetime print(datetime.now())

a)

Current time only

b)

Current date and time

c)

Current date only

d)

None

83.

How can you create a datetime object representing January 1, 2023, at 12:00 PM?

a)

datetime(2023, 1, 1, 12, 0)

b)

datetime.new(2023, 1, 1, 12, 0)

c)

datetime.create(2023, 1, 1, 12, 0)

d)

datetime.make(2023, 1, 1, 12, 0)