0% found this document useful (0 votes)
16 views44 pages

PYTHON PROGRAMMING MCQ (III B.SC (CS) )

The document is a programming quiz for a Python course at Padmavani Arts and Science College for Women, covering various topics such as data types, operators, control structures, and functions. It includes multiple-choice questions designed to test knowledge of Python programming concepts. The quiz is structured into units, with each question focusing on specific aspects of Python syntax and functionality.

Uploaded by

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

PYTHON PROGRAMMING MCQ (III B.SC (CS) )

The document is a programming quiz for a Python course at Padmavani Arts and Science College for Women, covering various topics such as data types, operators, control structures, and functions. It includes multiple-choice questions designed to test knowledge of Python programming concepts. The quiz is structured into units, with each question focusing on specific aspects of Python syntax and functionality.

Uploaded by

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

PADMAVANI ARTS AND SCIENCE COLLEGE FOR WOMEN

(AUTONOMOUS)
DEPARTMENT OF COMPUTER SCIENCE AND COMPUTER APPLICATIONS

CLASS:III-B.Sc(CS)& III-BCA SUBJECT: PROGRAMMING IN PYTHON

UNIT 1
Python
1. Who created Python?
a) Guido van Rossum b) Larry Wall
c) Linus Torvalds d) Bill Gates
2. In what year was Python first released?
a) 1991 b) 1995 c) 2000 d) 2005
3. What is the purpose of the "=" operator in Python?
a) Comparison b) Assignment c) Arithmetic d) Logical

4. What is the difference between "=" and "==" in Python?


a) Assignment and comparison b) Arithmetic and logical
c) Equality and identity d) None of the above

5. What is the syntax for printing output in Python?


a) print() b) echo() c) cout() d) printf()

6. What is the purpose of indentation in Python?


a) Code readability b) Block-level structure
c) Commenting d) Error handling

7. What are valid identifier characters in Python?


a) Letters, digits, underscore b) Letters, digits, special chars
c) Letters, underscore d) Digits only

8. What is the maximum length of an identifier in Python?


a) 31 chars b) 63 chars c) 127 chars d) No limit

9. What is the recommended line length in Python?


a) 72 chars b) 80 chars c) 100 chars d) 120 chars
10. What is the purpose of docstrings in Python?
a) Code comments b) Function documentation
c) Variable description d) Error handling

11. What are the built-in numeric types in Python?


a) int, float b) int, float, complex
c) int, float, double d) int, float, long

12. What is the difference between tuples and lists in Python?


a) Immutability b) Size
c) Type d) performance

13. What is the purpose of the "+" operator in Python?


a) Multiplication b) Concatenation
c) division d) Extraction

14. What is the purpose of the "in" operator in Python?


a) Membership testing b) Identity testing
c) Equality testing d) Black-Box testing

15. What is the purpose of the len() function in Python?


a) Get length of sequence b) Get size of object
c) Get type of object d) Get size

16. What is the scope of a variable in Python?


a) Global b) private c) public d) protected

17. How do you convert a string to an integer in Python?


a) int() b) str() c) float() d) None

18. What is the difference between static and dynamic typing?


a) Type checking b) Type conversion
c) Variable declaration d) Variable initialization

19. How do you delete a variable in Python?


a) del b) remove c) delete d) rem

20. What is the purpose of the isinstance() function?


a) Type checking b) Type conversion
c) Variable declaration d) Type
21. What is the purpose of the if-else statement?
a) Looping b) Conditional execution
c) Function definition d) Function declaration

22. How do you exit a loop in Python?


a) break b) continue
c) pass d) return

23. What is the difference between for and while loops?


a) Iteration b) Conditional execution
c) Loop control d) Exit of loop

24. How do you skip to the next iteration in Python?


a) continue b) break c) pass d) return

25. What is the purpose of the pass statement?


a) Placeholder b) Loop control
c) Conditional execution d) Loop Execution

26. What is the purpose of the def keyword?


a) Function definition b) Variable declaration
c) Type definition d) Passing parameters

27. How do you call a function in Python?


a) Function name b) Function reference
c) Function invocation d) Function calling

28. What is the difference between positional and keyword arguments?


a) Argument order b) Argument name
c) Argument type d) Argument list

29. How do you return multiple values from a function?


a) Tuple b) List c) Dictionary d) Array

30. What is the purpose of the lambda function?


a) Anonymous function b) Higher-order function
c) Closure d) null function

31. What is the difference between lists and tuples?


a) Mutability b) Size c) Type d) Accessibility
32. How do you access an element in a list?
a) Index b) Key c) Value d) key-pair

33. What is the purpose of the dict data structure?


a) Key-value mapping b) Ordered collection
c) Unordered collection d) Key mapping

34. How do you add an element to a set?


a) add b) remove c) union d) difference

35. What is the difference between set and frozenset?


a) Mutability b) Size c) Type d) speed

36. How do you open a file in Python?


a) open b) read c) write d) close

37. What is the purpose of the file mode?


a) Read-only b) Write-only c) Read-write d) Execute-only

38. How do you read from a file?


a) read b) readline c) readlines d) readwrite

39. What is the purpose of the seek method?


a) File positioning b) File reading
c) File writing d) File closing
40. How do you close a file in Python?
a) close() b) open() c) read() d) write()
41. What happens when you open a file without specifying the mode?
a) Read-only b) Write-only c) Read-write d) Append

42. How do you read a file line by line?


a) readlines() b) readline() c) read() d) for loop

43. What is the purpose of the tell() method?


a) Get current file position b) Set file position
c) Read file d) Write file

44. How do you write to a file?


a) write() b) writelines() c) read() d) append()
45. What is the difference between ‘w’ and ‘a’ modes?
a) Read-write b) Write-append
c) Overwrite-append d) Read-append

45. What is the purpose of try-except blocks?


a) Error handling b) Exception handling
c) Code optimization d) Debugging

46. How do you raise an exception?


a) raise b) throw c) exception d) error

47. What is the difference between exceptions and errors?


a) Type b) Severity c) Handling d) Execution

48. How do you catch multiple exceptions?


a) Multiple except blocks b) Single except block
c) try-except-else d) try-finally

49. What is the purpose of the finally block?


a) Clean-up code b) Error handling
c) Exception handling d) Code optimization

50. How do you handle uncaught exceptions?


a) try-except b) try-finally
c) sys.excepthook d) logging

51. What is the purpose of the assert statement?


a) Debugging b) Testing
c) Error handling d) Code optimization

52. How do you log exceptions?


a) logging module b) print()
c) sys.stderr d) traceback

53. What is the difference between logging and printing?


a) Output b) Level c) Format d) Purpose

54. How do you configure logging levels?


a) logging.basicConfig() b) logging.config()
c) log.setLevel() d) logger.setLevel()
55. What was the inspiration for Python's name?
a) Monty Python's Flying Circus b) Python snake
c) Programming language d) Flying Circus

56. What is the official Python logo?


a) Snake
b) Eagle
c) Python letters
d) Animal

57. What is Python's memory management?


a) Manual b) Automatic c) Dynamic d) Static

58. What is Python's syntax style?


a) C-like b) Java-like c) Indentation-based d) XML-like
105. What is the assignment operator in Python?
a) = b) == c) := d) >>

59. What is the difference between = and ==?


a) Assignment vs. comparison b) Comparison vs. assignment
c) Compare d) Assignment

60. What happens when reassigning a variable?


a) Original value lost b) New value appended
c) Error d) No changes

61. What ends a statement in Python?


a) Semicolon b) Newline c) Colon d) Comma

62. What is the purpose of indentation?


a) Code readability b) Block definition
c) Syntax highlighting d) Definition

63. How do you write a multiline comment?


a) Triple quotes b) Double quotes
c) Hash symbol d) Backslash

64. What is the purpose of the pass statement?


a) Placeholder b) Skip execution
c) Error handling d) Execute

65. What are valid identifier characters?


a) Letters, digits, underscore b) Letters, digits
c) Letters, underscore d) Any character

66. What is the purpose of the underscore prefix?


a) Private variable b) Global variable
c) Protected variable d) Public variable

67. What is the purpose of the __ prefix?


a) Private variable b) Special method c) Protected variable d) Public

68. What is the recommended indentation size?


a) 2 spaces b) 4 spaces c) 8 spaces d) Tab

UNIT - 2
1) Which of the following data types is used for double-precision floating-point numbers in
Python?
a) int b) float c) double d) complex
2) What is the maximum value of an integer (int) in Python?
a) 2147483647 b) 9223372036854775807
c) Infinity d) There is no maximum integer value
3) Which of the following is a valid way to represent a double precision floating-point number in
Python?
a) 11 b) 10 c) 3.14 d) 678
4)Which of the following methods can be used to convert a floating-point number to an integer?
a) int() b) float() c) round() d) convert()
5)What will be the result of the following code?
x=7
y=2
print(x ** y)
a) 49
b) 14
c) 5.5
d) 3.5
6) What is the output of the following code?
x = 10.5
y=4
print(x / y)
a) 2.625 b) 2.6 c) 2 d) 4
7) What is the result of the following code?
x = 3.14159
print(int(x))
a) 3.14 b) 3 c) 4 d)3.1415
8) What is the correct way to define a complex number in Python?
a) x = 3 + 4i b) x = 3 + 4j c) x = 3 + 4I d) x = (3, 4)
9) What is the output of the following code?
x = 3 + 4j
print(x.real)
a) 3 b) 4 c) 3 + 4j d) 4j
10) How do you compute the conjugate of a complex number in Python?
a) x.conjgate() b) x.conjugate() c) conjugate(x) d) y.conjugate()
11) Which of the following is not a complex number?
a) k = 2 + 3j b) k = complex(2, 3) c) k = 2 + 3l d) k = 2 + 3J
12) What does ~4 evaluate to?
a) -5 b) -4 c) -3 d) +3
13) Which of the following is not a valid operation for complex numbers in Python?
a) Addition b) Subtraction c) Division d) Square root
14) How do you get the absolute value (magnitude) of a complex number in Python?
a) abs(x) b) x.abs() c) cmath.abs(x) d) x.magnitude()
15) What is the output of the following code?
x = 1 + 2j
print(abs(x))
a) 2 b) 2.23606797749979 c) 1 d) 1.5
16) How can you check if a number is complex in Python?
a) isinstance(x, complex) b) type(x),complex c) is_complex(x) d) type(x)
17) What is the result of the following operation?
x = 3 + 4j
print(x ** 2)
a) -7 + 24j b) -7 - 24j c) 7 + 24j d) 7 - 24j
18) How do you extract the real part of a complex number?
a) x.real() b) x.real c) real(x) d) get_real(x)
19) What does the cmath.phase() function return?
a) The real part of a complex number. b) The imaginary part of a complex number.
c) The magnitude of a complex number. d) The phase (angle) of a complex number.
20) What does the // operator do in Python?
a) Division that returns a float b) Division that returns an integer
c) Remainder of division d) Exponentiation
21) What is the result of the following code?
x = 10
y=3
print(x // y)
a) 3.33 b) 4 c) 2.0 d) 3
22) What will the following expression return?
x=5
y=5
print(x is y)
a) 11 b) 0 c) 1 d) 00
23) Which operator is used to assign a value to a variable?
a) = b) == c) += d) &
24) What is the result of the following code?
x = 10
x %= 3
print(x)
a) 0 b) 3 c) 1 d) 2
25) Which of the following operators is used to concatenate two strings?
a) & b) + c) * d) ==
26) Which of the following operators is a bitwise XOR operator?
a) ^ b) & c) | d) ~
27) What is the result of the following operation?
x=4
y=2
print(x << y)
a) 4 b) 8 c) 16 d) 2
28) Which operator is used for bitwise AND in Python?
a) & b) | c) ^ d) ~
29) Which of the following is the result of the operation 5 / 2 in Python?
a) 2 b) 2.5 c) 3 d) 3.0
30) What does the isnumeric() method do in Python?
a) Checks if a string is a valid floating-point number.
b) Checks if a string contains only alphabetic characters.
c) Checks if a string contains only numeric characters (0-9).
d) Checks if a string contains any digits.
31) Which of the following strings will return True when passed to the isnumeric() method?
a) "123abc" b) "456" c) "12.34" d) " " (empty string)
32) Does isnumeric() consider negative numbers (e.g., -5) as numeric?
a) Yes
b) No
c) Only if the negative sign is at the end
d) Only if the negative sign is in the middle
33) Which of the following is not considered a numeric string by the isnumeric() method?
a) "123" b) "Ⅹ" (Roman numeral for 10)
c) "٣" (Arabic digit) d) "12.34"
34) Which of the following is not a sequence type in Python?
a) List b) Tuple c) Dictionary d) String
35) What is the output of the following code?
s = "Hello"
print(s[1])
a) H b) e c) l d) o
36) Which of the following is immutable in Python?
a) List b) Set c) Dictionary d) Tuple
37) What does the len() function do when applied to a sequence in Python?
a) Returns the last element of the sequence
b) Returns the number of elements in the sequence
c) Returns the first element of the sequence
d) Returns a copy of the sequence
38) What will the following code output?
s = "Python"
print(s[1:4])
a) yth b) pyth c) tho d) Py
39) Which of the following string methods can be used to convert a string to uppercase in
Python?
a) lower() b) capitalize() c) swapcase() d) upper()
40) What does the len() function return when applied to a string?
a) The first character of the string b) The last character of the string
c) The number of characters in the string d) The string itself
41) What will the following code output?
s = "python programming"
print(s[:6])
a) python b) python c) program d) pytho
42) What does the find() method do in Python?
a) Finds the longest word in a string
b) Finds the index of the last occurrence of a substring
c)Finds the first occurrence of a substring
d) Finds the number of occurrences of a substring
43) What is the result of the following code?
s = "hello"
print(s[::-1])
a) hello b) olleh c) Error d) None
44) Which of the following methods can be used to check if a string contains only alphabetic
characters?
a) isalpha() b) isdigit() c) isalnum() d) isalpha()
45) Which of the following methods is used to replace a substring in a string with another
substring?
a) change() b) substitute() c) replace() d) transform()
46) What will be the result of the following code?
s = "Python"
print(s * 3)
a) PythonPythonPython b) Python3Python3 c) PYTHON d) PYT
47) Which method can be used to convert a string to a list of characters?
a) charlist() b) split() c) join() d) List()
48) What does the startswith() method do in Python?
a) Checks if the string starts with a specific substring
b) Checks if the string ends with a specific substring
c) Checks if the string contains a specific substring
d) Checks if the string is empty
49) What will the following code output?
s = "HELLO"
print(s.lower())
a) Hello b) HELLO c) hello d) Error
50) What does the capitalize() method do in Python?
a) Converts the first character to uppercase and the rest to lowercase
b) Converts the entire string to uppercase
c) Converts the entire string to lowercase
d) Capitalizes every word in the string
51) What is the result of the following code?
s = "apple"
print(s[1:4])
a) pple b) appl c) ppl d) ple
52) How can you check if a string contains only numeric characters?
a) isnum() b) isdigit() c) isnumeric() d) isalpha()
53) What does the join() method do in Python?
a) Joins a sequence of characters into a single string
b) Splits a string into a list of words
c) Combines a list of words into a sentence
d) Concatenates two strings
54) Which of the following is a valid way to create a list in Python?
a) list = (1, 2, 3) b) list = [1, 2, 3]
c) list = {1, 2, 3} d) list = 1, 2, 3
55) What will be the output of the following code?
lst = [1, 2, 3, 4]
print(lst[2])
a) 1 b) 2 c) 3 d) 4
56) Which method is used to add an element to the end of a list?
a) append() b) insert() c) add() d) extend()
57) What is the output of the following code?
lst = [1, 2, 3, 4]
lst[1:3] = [5, 6]
print(lst)
a) [1, 5, 6, 4, 6] b) [1, 5, 6, 4]
c) [5, 6, 3, 4] d) [1, 2, 3, 4, 5, 6]
58) What is the result of the following code?
lst = [1, 2, 3, 4]
lst.pop()
print(lst)
a) [1, 2, 3] b) [1, 2, 3, 4]
c) [2, 3, 4] d) [1, 2, 3, 4, None]
59) What is the correct syntax to access the last element of a list in Python?
a) list[0] b) list[-1]
c) list[len(list)] d) list[len(list) - 1]
60) Which method is used to sort a list in ascending order in Python?
a) order() b) sorted() c) sort() d) ascending()

61) What is the result of the following code?


lst = [10, 20, 30, 40, 50]
print(lst[::2])
a) [10, 20, 30, 40, 50] b) [10, 30, 50] c) [20, 40] d) [50, 40, 30, 20, 10]
62) What will be the output of the following code?
lst = [1, 2, 3]
lst[1:2] = [5, 6, 7]
print(lst)
a) [1, 5, 6, 7, 3] b) [1, 5, 6, 7] c) [1, 6, 7] d) [1, 5, 6, 7, 2, 3]
63) How can you combine two lists in Python?
a) list1.concat(list2) b) list1.merge(list2) c) list1.append(list2) d) list1 + list2
64) What does the remove() method do in Python?
a) Removes an element by index
b) Removes all occurrences of a value
c) Removes the first occurrence of a value
d) Removes a slice of the list
65) What will be the output of the following code?
lst = [10, 20, 30, 40, 50]
lst[1:4] = [100, 200]
print(lst)
a) [10, 100, 200, 50] b) [10, 100, 200, 30, 40, 50]
c) [100, 200] d) [10, 100, 200]
66) What will the following code output?
lst = [1, 2, 3]
lst += [4, 5]
print(lst)
a) [1, 2, 3,[ 4, 5]] b) [1, 2, 3, 4, 5] c) [4, 5, 1, 2, 3] d) [5, 4, 3, 2, 1]
67) What does the extend() method do in Python?
a) Adds an element at the end of the list
b) Combines two lists
c) Removes elements from the list
d) Changes the value of an element in the list
68) What is the result of the following code?
lst = [5, 10, 15]
lst.insert(1, 7)
print(lst)
a) [5, 7, 10, 15] b) [7, 5, 10, 15] c) [5, 10, 7, 15] d) [5, 10, 15, 7]
69) Which of the following is the correct way to create a tuple in Python?
a) tuple = [1, 2, 3]
b) tuple = {1, 2, 3}
c) tuple = (1, 2, 3)
d) tuple = (1; 2; 3)
70) What will be the output of the following code?
t = (1, 2, 3, 4, 5)
print(t[2])
a) 1 b) 2 c) 3 d) IndexError
71) Which of the following operations is not allowed with tuples in Python?
a) Tuple concatenation b) Tuple indexing
c) Tuple slicing d) Tuple item reassignment
72) What will be the output of the following code?
t = (1, 2, 3, 4)
t[1:3] = [5, 6]
print(t)
a) (1, 5, 6, 4)
b) (1, 5, 6, 2, 3, 4)
c) TypeError: 'tuple' object does not support item assignment
d) (5, 6)
73) Tuples in Python are:
a) Mutable b) Immutable
c) Neither mutable nor immutable d) Only mutable if they contain only integers
74) Which of the following methods can be used to convert a list to a tuple?
a) tuple() b) list() c) convert() d) make_tuple()
75) What is the output of the following code?
t = (10, 20, 30, 40, 50)
print(t[::-1])
a) Error b) (10, 20, 30, 40, 50) c) (30, 20, 10, 40, 50) d) (50, 40, 30, 20, 10)
76) How can you check if a value exists in a tuple?
a) if value in tuple: b) if tuple.contains(value):
c) if tuple.has(value): d) if tuple.index(value):
77) Which of the following is a valid tuple in Python?
a) [] b) (1, 2, 3) c) {} d) [1,2]
78) What will be the result of the following code?
t = (1, 2, 3)
t += (4, 5)
print(t)
a) (1, 2, 3, 4, 5) b) (1, 2, 3)
c) TypeError: 'tuple' object does not support item assignment d) Error
79) Which of the following is the correct way to access the last element of a tuple t?
a) t[0] b) t[-1] c) t[len(t)] d) t[len(t) - 1]
80) How do you create a tuple with a single element?
a) t = (1) b) t = [1] c) t = (1,) d) t = (1; )
81) Which of the following statements is true about tuples?
a) Tuples can have mixed data types b) Tuples can only contain integers
c) Tuples are mutable d) Tuples are used only for numeric data

82) What is the result of the following operation?


t = (1, 2, 3) + (4, 5)
a) (1, 2, 3,( 4, 5)) b) (5, 4, 3, 2, 1)
c) (1, 2, 3, 4, 5) d) TypeError
83) How do you find the index of an element in a tuple?
a) t.search(element) b) t.find(element)
c) t.get(element) d) t.index(element)
84) What will be the output of the following code?
lst = [1, 2, 3, 4]
lst.append(5)
print(lst)
a) [1, 2, 3, 4, 5] b) [1, 2, 3]
c) [5, 1, 2, 3, 4] d) Error
85) Which of the following methods is used to remove an item from a list at a specified index?
a) delete() b) remove() c) pop() d) clear()
86) What will be the result of the following code?
lst = [1, 2, 3, 4]
lst.insert(2, 99)
print(lst)
a) [1, 99, 2, 3, 4] b) [1, 2, 99, 3, 4]
c) [1, 2, 3, 4, 99] d) [99, 1, 2, 3, 4]
87) What will be the output of the following code?
lst = [1, 2, 3, 4]
lst.remove(3)
print(lst)
a) [1, 2] b) [1, 2, 3] c) [4] d) [1, 2,4]
88) Which of the following methods can be used to find the index of an element in a list?
a) find() b) index() c) locate() d) search()
89) What will be the output of the following code?
lst = [1, 2, 3, 4]
lst.reverse()
print(lst)
a) [1, 2, 3, 4] b) [4, 1, 2, 1] c) [4, 3, 2, 1] d) [4, 1, 2, 3]
90) Which of the following methods removes all items from a list?
a) reset() b) remove_all() c) delete() d) Clear()
91) What will be the result of the following code?
lst = [1, 2, 3]
lst.extend([4, 5])
print(lst)
a) [1, 2, 3, 4] b) [1, 2, 3, [4, 5]]
c) [4, 5, 1, 2, 3] d) [1, 2, 3, 4, 5]
92) Which of the following methods is used to add an element at the end of the list?
a) extend() b) insert() c) append() d) add()
93) What will be the output of the following code?
lst = [1, 2, 3, 4]
lst.pop(1)
print(lst)
a) [1, 2, 3] b) [1, 3, 4] c) [2, 3, 4] d) [1, 2, 3, 4]
94) What will be the result of the following code?
lst = [1, 2, 3]
lst *= 2
print(lst)
a) [1, 2, 3, 1, 2, 3] b) [1, 2, 3] c) [2, 3, 1] d) [1, 2, 3, 4, 5, 6]
95) Which method is used to check if an element is present in a list?
a) exists() b) in operator c) contains() d) has()
96) What will be the result of the following code?
lst = [1, 2, 3, 4]
lst.clear()
print(lst)
a) [] b) [1, 2, 3, 4] c) None d) Error
97) Which of the following methods can be used to count the occurrences of an element in a list?
a) find() b) count() c) frequency() d) index()
98) What will be the result of the following code?
lst = [5, 10, 15]
lst.insert(1, 7)
print(lst)
a) [5, 7, 1, 15] b) [7, 5, 10, 15] c) [5, 10, 15, 7] d) [5, 7, 10, 15]
99) Which of the following methods returns the last element from a list and removes it?
a) remove() b) pop() c) delete() d) discard()
100) Which method is used to sort the elements of a list in ascending order?
a) sort() b) order() c) sorted() d) arrange()
UNIT 3
1.What is the correct syntax to create a dictionary in Python?
a) dict = {key1: value1, key2: value2}
b) dict = [key1: value1, key2: value2]
c) dict = (key1: value1, key2: value2)
d) dict = <key1: value1, key2: value2>
2. Which of the following methods is used to add a key-value pair to a dictionary?
a) append() b) insert()
c) update() d) add()
3. Which of the following methods can be used to get the list of all keys in a dictionary?
a) dict.keys() b) dict.items()
c) dict.values() d) dict.get()
4. What is the output of dict = {'a': 1, 'b': 2}; print(dict['a'])?
a) a b) 1
c) 'a' d) KeyError
5. What does the get() method do in a dictionary?
a) It adds a key-value pair b) It returns the value associated with a key
c) It updates a key-value pair d) It returns all keys in the dictiona
6. How do you remove all elements from a dictionary?
a) dict.clear() b) dict.remove()
c) dict.popAll() d) del dict
7. What is the result of d = {'a': 1, 'b': 2}; d['c'] = 3; print(d)?
a) {'a': 1, 'b': 2} b) {'a': 1, 'b': 2, 'c': 3}
c) KeyError d) {'c': 3}
8. What happens if you try to access a non-existent key in a dictionary?
a) None is returned b) A default value is returned
c) A KeyError is raised d) The program exits
9. Which method returns a dictionary view object that displays a list of dictionary’s key-value
tuple pairs?
a) dict.values() b) dict.keys()
c) dict.items() d) dict.get()
10. Which of the following will raise a KeyError?
a) dict = {'x': 1}; dict['x']
b) dict = {'x': 1}; dict['y']
c) dict = {'x': 1}; dict.get('y')
d) dict = {'x': 1}; dict.pop('y')
11. Which of the following methods can be used to check if a key exists in a dictionary?
a) dict.exist(key) b) key in dict
c) dict.has_key(key) d) dict.contains(key)
12. What is the purpose of popitem() method in dictionaries?
a) To remove a specific item b) To remove and return a random key-value pair
c) To remove all items d) To return the first key-value pair
13. What does the setdefault() method do in a dictionary?
a) Returns the value of a key, and if it doesn't exist, adds it with a default value
b) Removes a key-value pair
c) Sets a default value for the dictionary
d) Adds a key without a value
14. Which of the following can be used as a dictionary key?
a) List b) Set
c) String d) Dictionary
15. What is the correct way to merge two dictionaries in Python?
a) dict1 + dict2 b) dict1.merge(dict2)
c) dict1.update(dict2) d) dict1.combine(dict2
16. Which of the following methods will return a copy of the dictionary?
a) copy() b) clone()
c) duplicate() d) reproduce()
17. What will the expression len(d) return, where d is a dictionary?
a) The number of values b) The number of key-value pairs
c) The sum of all values d) The number of keys
18. Which statement is true about dictionary keys?
a) They must be integers b) They can be mutable types
c) They can only be strings d) They must be immutable types
19. What is the result of calling dict.pop('key') on a dictionary that doesn’t contain 'key'?
a) “key” b) KeyError
c) 0 d) 'key'
20. What will dict = {'a': 1, 'b': 2, 'c': 3}; dict.pop('b') return?
a) 2 b) {'a': 1, 'c': 3}
c) None d) KeyError
21. Which of the following will print the values of a dictionary?
a) print(dict.values()) b) print(dict.items())
c) print(dict) d) print(dict.keys())
22. Which of the following will create a dictionary from two lists keys = ['a', 'b'] and values = [1,
2]?
a) dict(keys, values) b) dict(zip(keys, values))
c) zip(keys, values) d) dict(keys=values)
23. What is the method to get all the values in a dictionary?
a) dict.items() b) dict.keys()
c) dict.values() d) dict.get()
24. Which of the following is the correct way to define a nested dictionary in Python?
a) nested_dict = {key1: {key2: value2}} b) nested_dict = {key1: [key2: value2]}
c) nested_dict = (key1: {key2: value2}) d) nested_dict = [key1: {key2: value2}]
25. How can you access the value associated with a key key in dictionary dict?
a) dict(key) b) dict[]
c) dict.get(key) d) dictionary
26. What does the pop() method return?
a) The key-value pair b) The value of the key
c) The key d) The dictionary itself
27. What is the return type of dict.items()?
a) List b) Tuple
c) Dictionary view object d) Set
28. Which of the following will raise a TypeError in a dictionary?
a) dict[1] = 'a' b) dict[(1,2)] = 'b'
c) dict[[1]] = 'c' d) dict['key'] = 'value’
29. What is the result of dict1 = {'x': 1}; dict2 = dict1; dict2['x'] = 2; print(dict1)?
a) {'x': 1} b) {'x': 2}
c) {'x': 1, 'x': 2} d) KeyError
30. Which method allows you to iterate over a dictionary’s keys?
a) dict.keys() b) dict.values()
c) dict.items() d) dict.iterkeys
31. Which of the following is a built-in mapping type in Python?
a) List b) Dictionary
c) Set d) Tuple
32. Which function is used to create a dictionary from a sequence of key-value pairs?
a) dict() b) map()
c) set() d) tuple()
33. What does the method dict.get(key, default) do?
a) Returns the default value if the key is found.
b) Returns the key if found.
c) Returns the default value if the key is not found.
d) Removes the key-value pair from the dictionary
34. Which of the following methods returns a dictionary’s keys?
a) dict.items() b) dict.keys()
c) dict.values() d) dict.update()
35. The map() function in Python is used to:
a) Convert a dictionary to a list
b) Apply a function to each item in an iterable
c) Create a mapping between two lists
d) Create a dictionary from two lists
36. How can you add a new key-value pair to a dictionary d in Python?
a) d.append(key, value) b) d.add(key, value)
c) d[key] = value d) d.put(key, value)
37. Which function returns a view object that displays a list of a dictionary's values?
a) dict.keys() b) dict.values()
c) dict.items() d) dict.view()

38. Which of the following is the correct way to iterate over all key-value pairs in a dictionary d?
a) for key, value in d: b) for key in d:
c) for key, value in d.items(): d) for key, value in d.keys():
39. The dict.fromkeys() method is used to:
a) Create a dictionary from a list of keys
b) Create a dictionary with default values for all keys
c) Remove keys from a dictionary
d) Update the values of keys in a dictionar
40. What is the return type of dict.items()?
a) List of tuples b) List of dictionaries
c) View object d) Set of key-value pairs
41. What will d = {1: 'a', 2: 'b', 3: 'c'} and d.pop(2) return?
a) b b) {2: 'b'}
c) 2 d) KeyError
42. Which of the following methods removes a specific key and returns its value from a
dictionary?
a) dict.pop(key) b) dict.remove(key)
c) dict.delete(key) d) dict.erase(key)
43. What is the time complexity of looking up a key in a dictionary in Python?
a) O(1) b) O(n)
c) O(log n) d) O(n^2)
44. Which of the following functions can be used to create a dictionary from two lists, one of
keys and the other of values?
a) dict(zip(keys, values)) b) dict(keys, values)
c) dict.create(keys, values) d) dict(pair)
45. What is the purpose of the dict.update() method in Python?
a) Adds new keys to the dictionary
b) Replaces the entire dictionary with another dictionary
c) Merges another dictionary or iterable of key-value pairs into the current dictionary
d) Removes specific keys from the dictionary
46. How would you create a dictionary with keys 'a', 'b', and 'c' all initialized to 0 in Python?
a) dict('a'=0, 'b'=0, 'c'=0) b) dict.fromkeys(['a', 'b', 'c'], 0)
c) dict(['a', 'b', 'c'], 0) d) dict({'a': 0, 'b': 0, 'c': 0})
47. Which of the following is used to create a new dictionary from an iterable of key-value pairs?
a) dict.update() b) dict()
c) dict.fromkeys() d) dict.items()
48. What is the output of dict([('a', 1), ('b', 2)])?
a) {'a': 1, 'b': 2} b) [['a', 1], ['b', 2]]
c) ('a', 1), ('b', 2) d) {('a', 1), ('b', 2)}
49. Which of the following methods removes all items from a dictionary?
a) dict.clear() b) dict.delete()
c) dict.popall() d) dict.remove())
50. What is the behavior of dict.setdefault(key, default) in Python if the key already exists in the
dictionary?
a) It replaces the key’s value with default. b) It throws an exception.
c) It returns the current value of the key. d) It does nothing
51. Which built-in function can be used to find the largest item in an iterable?

a) max() b) min()
c) sum() d) abs()
52. What does the len() function return?

a) Sum of elements in a list b) Number of elements in an iterable


c) Type of an object d) Maximum value in an iterable
53. Which function is used to convert a string to lowercase?

a) lower() b) upper()
c) casefold() d) capitalize()
54.What is the purpose of the round() function?
a) Converts a string to an integer b) Rounds a number to the nearest integer
c) Converts an integer to a float d) Returns the absolute value
55. In Python, what keyword is used to execute a block of code when a condition is true?
a) if b) else
c) elif d) switch

56. What is the correct syntax for a while loop?


a) while condition: b) while (condition)
c) while condition {} d) do while (condition):
57. Which of the following functions converts a value to a string?
a) str() b) int()
c) float() d) repr()
58.Which function returns the type of an object?
a) id() b) type()
c) len() d) dir()
59. Which method is used to get a copy of a list?
a) copy() b) replicate()
c) duplicate() d) get()
60. Which keyword is used to stop a loop prematurely?
a) exit b) continue
c) break d) stop
61 What will happen if the condition in a while loop is always True?
a) The loop will run forever. b) The loop will run once.
c) The loop will exit after one iteration.d) Syntax error.
62. What does the continue keyword do in a loop?
a) Exits the loop. b) Skips the current iteration and moves to the next one.
c) Stops the loop after 1 iteration. d) Skips all iterations and stops the loop.
63. Which of the following loops is more suitable when the number of iterations is unknown?
a) for loop b) while loop
c) Both are equally suitable d) do-while loop
64. Which of the following loops uses the else block when the loop ends without break?
a) while loop b) if loop
c) do-while d) switch statement
65. How do you stop an infinite loop in Python manually?
a) Ctrl + Z b) Ctrl + C
c) Alt + F4 d) Shift + Esc
66. What happens if the break statement is used inside a nested loop?
a) It stops the innermost loop. b) It stops all loops.
c) It continues the loop execution. d) It causes an error.
67. In a nested loop, where does the break statement apply?
a) It exits all loops. b) It exits only the current loop.
c) It skips the current iteration of the outer loop.d) It has no effect.
68. What is the purpose of the pass statement in Python?
a) To exit a loop b) To raise an exception
c) To act as a placeholder for code d) To skip the current iteration of a loop
69. Which of the following statements about iterators is true?
a) Iterators do not store elements in memory
b) You cannot create custom iterators in Python
c) Iterators can only be used with for loops
d) Iterators are used to loop infinitel
70. What is the purpose of the iter() function?
a) To create a new list from an existing one b) To return an iterator object
c) To reverse a string d) To convert data type
71. Which method is used to write data to a file in Python?
a) read() b) write()
c) close() d) open()
72. Which mode is used to open a file for both reading and writing in Python??
a) r b) w
c) a d) r+
73. What happens if you try to open a file in write (w) mode that already exists?
a) The file will be opened without any changes b) The file will be appended
c) The file will be overwritten d) An error will be raised
74. Which method is used to read all the lines of a file in Python and return them as a list?
a) read() b) readline()
c) readlines() d) readfile()
75.. What is the default mode when opening a file using the open() function in Python?
a) r (read) b) w (write)
c) a (append) d) rb (read binary)
76. Which of the following is a valid way to write data to a file in Python?
a) file.write("Hello World") b) write(file, "Hello World")
c) file.add("Hello World") d) write("Hello World")
77. Which method is used to close a file in Python?
a) stop() b) end()
c) close() d) terminate()
78. What will happen if you try to open a non-existent file in read mode?
a) It will create a new file. b) It will return None.
c) It will raise a FileNotFoundError. d) It will open an empty file.
79. Which function is used to check if a file is closed in Python?
a) is_closed() b) file.closed
c) file.isclosed() d) closed()
80. Which built-in function is used to delete a file in Python?
a) delete() b) remove()
c) os.delete() d) os.remove()
81. What is the correct way to open a file for writing in binary mode?
a) open("file.txt", "w") b) open("file.txt", "wb")
c) open("file.txt", "w+b") d) open("file.txt", "bin")
82. What will the seek(0) method do when working with a file?
a) Move the file pointer to the end of the file.
b) Move the file pointer to the beginning of the file.
c) Move the file pointer to the middle of the file.
d) Delete the file content
83. Which of the following methods is used to read the entire content of a file in Python?
a) read() b) readline()
c) readlines() d) write()
84. What does the writelines() method do?
a) Writes a single string to a file. b) Writes a list of strings to a file.
c) Reads a single line from a file. d) Closes the file.
85.Which of the following methods is used to move the file pointer to a specific location?
a) seek() b) tell()
c) write() d) readline()
86. Which attribute returns the file mode of a file object?
a) file.name b) file.mode
c) file.closed d) file.seek()

87. Which attribute indicates whether a file is closed or not?


a) file.name b) file.mode
c) file.closed d) file.read
88. What does sys.stdout represent in Python?
a) Standard input b) Standard error
c) Standard output d) Standard file mode
89.Which module provides access to the standard input, output, and error streams in Python?
a) os b) sys
c) file d) io

90. Which of the following is used to access command-line arguments in Python?


a) sys.path b) sys.argv
c) os.environ d) file.args
91. What is the type of sys.argv?
a) Dictionary b) String
c) List d) Tuple
92. Which of the following is true about the elif statement in Python?
a) It's mandatory to use it in every if block. b) It can only follow an if statement.
c) It must be followed by an else statement. d) It can be used without an if statement.
93. Which operator is used for conditional expressions in Python?
a) ? : b) ->
c) if-else d) while
94. Which of the following conditional expressions is valid?
a) value = if x > 5 else 10 b) value = x > 5 ? x : 10
c) value = 10 if x > 5 else 5 d) value = if (x > 5) then 10 else 5
95. When will the else block of a while loop execute?
a) Always b) When the loop is prematurely terminated
using break
c) When the loop condition becomes false naturallyad) Never
96. Which of the following can replace the if-elif structure?
a) Nested loops b) Multiple ternary conditional
expressions
c) A single while loop d) Multiple try-except blocks
97. Which of the following loops will run infinitely?
a) while False: print("Hello") b) while 1: print("Hello")
c) while 0: print("Hello") d) while 1; print("Hello"
98. What will happen if there is no increment in a while loop?
a) The loop will terminate normally. b) The loop will run infinitely.
c) The loop will throw an error. d) The program will crash.
99. In which scenario is a while loop preferred over a for loop?
a) When the number of iterations is known in advance. b) When iterating over a range of
numbers.
c) When the loop should run until a condition is met. d) When the loop terminate
UNIT 4
1. Pure Functions have main properties.
a) Two b)Three c) Five d)Six

2. In pure function always produce the _____ output for the ______ arguments irrespective of
anything else.
a)Same, Different b)Different, Same c)Same, Same d)Different, Different

3. There are no __________“for” or “while” loop in functional languages.


a)for or while b)while 0r do…while c) if..then or if…else d)for or do…while

4. Iteration in functional languages is implemented through _________.


a) function b)function member c) class d)recursion
5. ________are First-Class and can be Higher-Order.
a) member b)functions c)objects d)encapsulation

6.The first-class variables can be passed to functions as a ________, can be returned from
functions, or stored in data structures.
a)class b)inheritance c)parameter d)arguments
7. What is the purpose of using *args in a function definition?
a) To pass a fixed number of arguments.
b) To pass a variable number of arguments to a function.
c) To specify default values for arguments.
d) To pass keyword arguments.
8. When calling a function, the order of arguments matters unless you're using keyword
Arguments is_________
a) Positional arguments b)Named arguments
c)Missing arguments d) Default and Positional Arguments
9. If a required argument is missing, Python raises a TypeError is_________
a) funcational call b) named arguments c)missing arguments d)positional arguments
10. The *args allows you to pass a variable number of arguments to the function is _____.
a) Positional arguments b)Named arguments c)Missing arguments d)variable arguments
11. What is the correct syntax to define a function in Python?
a) function myFunc(): b) def myFunc(): c) create myFunc(): d) def function myFunc():
12. Which of the following statements is true about the return value of a function in Python?
a) A function without a return statement will always return None.
b) A function with a return statement can only return integers.
c) A function can return only one value, but that value can be a list.
d) A function must return a value; otherwise, it will result in an error.
13. What will happen if a function is called with fewer arguments than it has parameters?
a) Python will throw a SyntaxError.
b) Python will use default values for missing arguments, if specified.
c) The function will not execute.
d) Python will ignore the extra parameters and proceed.
14. Which of the following is the correct way to define a function that accepts variable numbers
of arguments?
a) def myFunc(*args): b) def myFunc(**kwargs):
c) def myFunc(*args,**kwargs): d) def myFunc(args):

15. What is the purpose of the return statement in Python functions?


a) It stops the function's execution.
b) It sends a result back to the caller and exits the function.
c) It defines the function's parameters.
d) It defines a loop inside the function.

16. Which of the following is an example of a function with a default argument?


a) def greet(name="Guest"): b) def greet(name): c) def greet(): d) def greet("Guest")

17. Which of the following is true about Python functions?


a) Functions cannot return multiple values.
b) Functions can return only one value, which can be a tuple or a list.
c) Functions must return a value.
d) Functions always return None by default.

18. Which of the following allows you to pass an arbitrary number of keyword arguments to a
Python function?
a) *args b) * c) **kwargs d) **args
19. Which of the following is the correct way to call a function with named arguments in
Python?
a) myFunc(name="Alice", age=25) b) myFunc("Alice", age=25)
c) myFunc(name="Alice", 25) d) myFunc(name=Alice, age=25)

20. Which of the following is an incorrect function definition in Python?


a) def greet(): b) def greet(name): c) def 1greet(): d) def greet(name="Guest"):

21. Which of the following is the correct way to pass a function as an argument to another
function in Python?
a) function1(function2) b) function1(&function2)
c) function1(function2()) d) function1(function2)

22. What is a higher-order function in Python?


a) A function that takes more than one argument
b) A function that returns another function
c) A function that can only accept integer arguments
d) A function that is always recursive

23. Which of the following is the correct way to pass a lambda function to another function in
Python?
a) function1(lambda x: x+1) b) function1(lambda x = 1: x+1)
c) function1(x: lambda x: x+1 d) function1(lambda)

24. Which of the following Python code snippets correctly uses the map() function with a
function passed as an argument?
a) map(add, [1, 2, 3]) b) map([1, 2, 3], add)
c) map(lambda x: x + 1, [1, 2, 3]) d) map(add, [1, 2, 3], [4, 5, 6])

25.Which of the following statements correctly uses the filter() function with a function passed
as an argument?
a) filter(lambda x: x > 5, [1, 3, 6, 8]) b) filter([1, 3, 6, 8], lambda x: x > 5)
c) filter(lambda x > 5, [1, 3, 6, 8]) d) filter(x > 5, [1, 3, 6, 8])

26. Which of the following is the correct way to find the length of a list in Python?
a) length(list) b) list.len() c) len(list) d) length_of(list)

27. Which function is used to get the type of an object in Python?


a) typeOf() b) type() c) objectType() d) getType()

28. What will the abs(-5) function call return?


a) -5 b) 5 c) 0 d) None

29. Which of the following functions is used to convert a string into an integer?
a) strtoint() b) int() c) string_to_int() d) convert_to_int()

30. Which of the following functions can be used to round a floating point number to the nearest
integer?
a) round() b) floor() c) ceil() d) int()

31. What will the function sum([1, 2, 3, 4]) return?


a) 24 b) 10 c) 14 d) None

32. What does the sorted() function return?


a) Sorted version of the list b) The smallest value of the list c) The list is sorted in-place
d) The largest value of the list

33. Which function is used to get the maximum value from a list?
a) max_value() b) maximum() c) max() d) highest()

34. Which of the following functions is used to return the unique elements of a sequence in
Python?
a) unique() b) distinct() c) set() d) remove_duplicates()

35. What does the input() function do?


a) Returns the input from the user as a string b) Returns a list of user inputs
c) Returns the user input as an integer d) Accepts only numbers from the user

36. Which of the following functions is used to join elements of an iterable into a string?
a) join() b) concatenate() c) merge() d) combine()

37. What will the function call min([3, 1, 4, 1, 5, 9]) return?


a) 9 b) 1 c) 4 d) 5

38. Which function can be used to check whether an object is callable in Python?
a) callable() b) is_call() c) can_call() d) check_call()

39. What is the output of the expression len("Python")?


a) 5 b) 6 c) 7 d) 1

40. What does the all() function do in Python?


a) Returns True if all elements are numbers
b) Returns True if at least one element is true
c) Returns False if any element is false
d) Returns True if all elements in an iterable are true

41. Which built-in function is used to remove leading whitespaces from a string?
a) trim() b) strip() c) lstrip() d) rstrip()

42. Which built-in function is used to return a sequence of integers?


a) range() b) sequence() c) list() d) int_sequence()

43. Which function can be used to convert a string to lowercase?


a) lowercase() b) to_lower() c) convert_to_lower() d) lower()
44. What does the zip() function do in Python?
a) Zips two strings together b) Combines two iterables element-wise
c) Compresses data d) Returns the length of the list

45. Which function is used to calculate the power of a number in Python?


a) power() b) pow() c) exponent() d) exp()

46. Which of the following functions is used to apply a function along an axis of a
DataFrame in Pandas?
a) map() b) apply() c) reduce() d) filter()

47. What does the filter() function in Python do?


a) Applies a function to every item in an iterable and returns the results.
b) Reduces an iterable to a single value using a specified function.
c) Filters elements from an iterable based on a condition (function that returns a
boolean).
d) Transforms the items of an iterable based on a function.

48. What is the output of the following code snippet?


nums = [1, 2, 3, 4, 5]
result = map(lambda x: x ** 2, nums)
print(list(result))
a) [1, 4, 9, 16, 25] b) [1, 2, 3, 4, 5] c) [1, 3, 5, 7, 9] d) [2, 4, 6, 8, 10]

49. Which function can be used to combine elements of an iterable using a binary function
(e.g., addition, multiplication)?
a) map() b) reduce() c) filter() d) apply()

50. In the filter() function, the function applied to the iterable must return:
a) True or False b) An iterable of the same length
c) The transformed elements d) A boolean list

51. What is the default behavior of the map() function in Python?


a) It filters out elements based on a given condition.
b) It reduces an iterable to a single value.
c) It applies the given function to every element of an iterable.
d) It sorts the iterable based on a key.

52. Which of the following is true about the reduce() function?


a) It applies a function to an iterable and returns a transformed list.
b) It takes a function of two arguments and applies it cumulatively to the items of an
iterable.
c) It filters elements of an iterable based on a condition.
d) It returns an iterator over elements of an iterable.
53. Given the following code, what will result contain?
numbers = [10, 20, 30, 40, 50]
result = filter(lambda x: x > 30, numbers)
print(list(result))
a) [40, 50] b) [10, 20, 30, 40, 50] c) [20, 30, 40, 50] d) [30, 40, 50]

54. Which function is used to apply a function element-wise to a sequence, like a list, and return
the results as a new iterable?
a) apply() b) filter() c) reduce() d) map()

55. How many arguments does the reduce() function take in Python?
a) One b) Two c) Three d) Four

56. Which of the following is the correct way to use reduce() in Python?
a) reduc() b) reduce(x, y: x + y, [1, 2, 3, 4], 0)
c) reduce(lambda x, y: x * y, [1, 2, 3, 4]) d) (x, y: x + y, [1, 2, 3, 4], 0)

57. Which of the following will return the square of each number from a list using map()?
a) map(lambda x: x**2, [1, 2, 3, 4]) b) map(lambda x: x > 2, [1, 2, 3, 4])
c) map(lambda x: x + 1, [1, 2, 3, 4]) d) map(lambda x: x - 1, [1, 2, 3, 4])

58. Which of the following functions in Python is often used in functional programming and
takes two arguments to cumulatively reduce a sequence?
a) map() b) reduce() c) apply() d) filter()

59. What is the result of the following code?


nums = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, nums)
print(result)
a) 15 b) 1 c) 10 d) [1, 2, 3, 4, 5]

60. Which of the following statements about the apply() function in Python's Pandas is correct?
a) apply() can be used only on lists.
b) apply() can apply a function along either axis of a DataFrame (rows or columns).
c) apply() returns a function object.
d) apply() can only be used for mathematical functions.

61. What is a Python module?


a) A function defined within a script
b) A class defined within a script
c) A file containing Python definitions and statements
d) A variable that stores a function
62. How can you import a specific function from a module in Python?
a) import function_name from module_name
b) from module_name import function_name
c) import module_name.function_name
d) include module_name.function_name

63. Which of the following commands imports the entire math module?
a) from math import * b) import math as m c) import math d) include math

64. What is the correct way to import a module with an alias?


a) import module_name as alias b) import alias from module_name
c) from module_name import alias d) module_name = alias

65. Which of the following functions is used to get the path of the current module in Python?
a) os.path.current() b) os.getcwd() c) sys.argv() d) sys.path

66. What does the __name__ variable represent in a Python module?


a) The name of the class defined in the module b) The path of the file
c) The name of the module d) The version of the module

67. How can you check whether a module is already imported in Python?
a) module.is_loaded() b) import sys; sys.modules
c) module.is_imported() d) import module; module.exists()

68. What does the importlib module in Python do?


a) Manages system environment variables b) Handles file input and output
c) Provides a way to import modules dynamically d) Implements regular expressions

69. Which of the following is the correct way to reload a module in Python?
a) reload(module_name) b) importlib.reload(module_name)
c) module_name.reload() d) import reload(module_name)

70. What is the function of the __all__ attribute in a Python module?


a) It defines the variables to be included in the module documentation
b) It specifies the names of objects to be imported when using from module import *
c) It marks the module as a built-in module
d) It controls the module version
71. What will happen if a Python module contains an error, but you still try to import it?
a) The error will be ignored, and the module will be loaded successfully
b) The error will be displayed, but the module will still be imported
c) The import statement will fail, and an exception will be raised
d) The error will be logged in a separate log file

72. In Python, which of the following is the correct way to import a module from a subpackage?
a) from subpackage import module_name
b) import subpackage.module_name
c) import subpackage as module_name
d) import subpackage.module_name as module_name

73. What will the following statement do in Python? import os; os.system('echo Hello')
a) It prints "Hello" to the console
b) It imports the os module
c) It executes the command echo Hello in the system's shell
d) It returns "Hello" as a string

74. Which module is commonly used for handling file and directory operations in Python?
a) os b) sys c) time d) random

75. Which module would you import if you want to work with JSON data in Python?
a) json b) csv c) xml d) yaml

76. How can you check the documentation of a module in Python?


a) module_name.doc() b) help(module_name)
c) module_name.info() d) dir(module_name)

77. What is the purpose of the site module in Python?


a) It handles Python package installations
b) It provides access to Python's site-specific configuration
c) It lists all installed modules
d) It defines the core functionality of Python

78. Which of the following modules would you import for working with dates and times in
Python?
a) datetime b) calculator c) software d) datetime,time,calendar

79. How do you access the list of modules currently imported in a Python program?
a) sys.modules b) os.modules c) imported_modules() d) list(modules)
80. Which of the following is NOT a built-in module in Python?
a) math b) datetime c) re d) numpy
81. What is the correct way to import the math module in Python?
a) import math() b) import math[]
c) import math d) from math import *
82. Which of the following functions is used to load a module in Python?
a) load() b) import() c) require() d) import
83. How do you access the pi constant from the math module?
a) math.pi() b) math(pi) c) math.pi d) pi(math)
84. What is the purpose of the __name__ variable in Python modules?
a) It is used to define the module name for logging.
b) It is used to test whether the module is being run as a standalone script or imported into
another script.
c) It is used to name functions within a module.
d) It is a built-in variable that holds the module's author name.
85. Which of the following is the correct syntax to write to a file in Python?
a) file.write("Hello World") b) write.file("Hello World")
c) write("file", "Hello World") d) file("Hello World").write()
86. Which method is used to open a file in write mode in Python?
a) open("filename", "r") b) open("filename", "w")
c) open("filename", "a") d) open("filename", "rw")
87. What is the default mode when opening a file in Python?
a) r (read) b) w (write) c) a (append) d) rb (read binary)
88. Which of the following methods is used to read the contents of a file in Python?
a) file.read() b) file.get() c) file.load() d) file.text()
89. What will happen if you try to open a file that does not exist in Python with the mode w
(write)?
a) Python will raise a FileNotFoundError.
b) Python will create a new empty file.
c) Python will print a warning but continue running.
d) Python will return a None value.
90. Which of the following is the correct way to import a specific function sqrt from the math
module in Python?
a) import sqrt from math b) from math import sqrt
c) import math.sqrt d) from sqrt import math
91. Which of the following is the correct way to append text to a file in Python?
a) open("file.txt", "w").write("Hello World")
b) open("file.txt", "a").write("Hello World")
c) open("file.txt", "r").append("Hello World")
d) open("file.txt", "a").append("Hello World")
92. Which Python function can be used to list all the modules that are currently imported?
a) list_modules() b) get_imports() c) dir() d) imported()
93. Which method is used to close a file after opening it in Python?
a) file.close() b) file.end() c) file.stop() d) file.quit()
94. Which of the following Python commands will delete a module from memory?
a) del module b) remove(module) c) unload(module) d) delattr(module)
95. Which of the following is the correct way to read a file line by line in Python?
a) for line in file: b) file.readlines() c) file.read() d) file.each_line()
96. How do you open a file for reading and writing in Python?
a) open("file.txt", "rw") b) open("file.txt", "r+")
c) open("file.txt", "w+") d) open("file.txt", "rw+")
97. What is the function __init__() used for in Python modules?
a) It initializes the module variables. b) It initializes the Python interpreter.
c) It defines the main function in a script. d) It initializes class instances.
98. What is the output of the following code snippet?
import os
print(os.getcwd())
a) Prints the current working directory. b) Prints the os module’s location.
c) Prints the home directory. d) Prints the last directory used.
99. What does the import statement do in Python?
a) It imports functions and variables from external modules into the current script.
b) It loads external files into the Python interpreter.
c) It imports data from external sources like databases.
d) It executes a file as a standalone script.
100. Which of the following file modes is used for reading binary files in Python?
a) rb b) wb c) r d) a
101. Which of the following functions is used to import a specific function from a module in
Python?
a) import module.function b) from module import function
c) import function d) from function import module
102. Which Python module provides the function sqrt() to calculate the square root of a number?
a) math b) cmath c) statistics d) random
103. What will the following code output?
import random
print(random.randint(1, 10))
a) A random float between 1 and 10 b) A random integer between 1 and 10
c) A random string of length 10 d) A random number between 1 and 10, inclusive
104. Which function is used to get the current date and time in Python?
a) datetime.now() b) time.get_time() c) datetime.today() d) date.current()
105. Which function in Python is used to read all lines from a file and return them as a list?
a) readlines() b) read() c) getlines() d) filelines()
106. What will be the result of the following Python code?
import math
print(math.ceil(3.14))
a) 3 b) 3.0 c) 4 d) 2
107. Which module is used to generate pseudo-random numbers in Python?
a) random b) math c) randomize d) numpy
108. Which of the following Python functions returns the absolute value of a number?
a) abs() b) absval() c) value() d) absolute()
109. What does the dir() function do in Python?
a) Returns the directory of a module
b) Lists all the attributes and methods of an object
c) Returns the current working directory
d) Returns the name of the directory in which a module is located
110. Which of the following Python built-in functions can be used to return the length of an
object (string, list, tuple, etc.)?
a) len() b) length() c) size() d) count()
111. Which Python function is used to convert a string to lowercase?
a) lower() b) tolower() c) convert() d) casefold()
112. What does the help() function do in Python?
a) Returns a list of all available modules
b) Provides documentation about a function, class, or module
c) Prints the error traceback
d) Offers suggestions for troubleshooting
113. Which of the following modules in Python is used to work with regular expressions?
a) regex b) re c) regexp d) pattern
114. What will be the result of the following code?
import sys
print(sys.version)
a) Python's current version number b) Python's installation location
c) The version of a specific library d) The operating system version
115. Which of the following built-in functions is used to round a floating point number to the
nearest integer in Python?
a) round() b) ceil() c) floor() d) int()
UNIT 5
1. Why is database programming important in Python?
a) To perform mathematical calculations
b) To store and manage large amounts of data efficiently
c) To create graphical user interfaces
d) To write system-level code
2. Which Python library is commonly used for database connectivity?
a) NumPy b) Matplotlib c) SQLite3 d) TensorFlow
3. What is the primary benefit of using an ORM (Object-Relational Mapping) tool in
Python?
a) It speeds up the execution of Python scripts.
b) It allows interaction with databases using Python objects instead of SQL
cueries.
c) It eliminates the need for any database.
d) It improves the performance of graphical applications.
4. Which of the following is NOT a type of database you can work with in Python?
a) Relational databases b) NoSQL databases
c) In-memory databases d) Word processing databases
5. In Python, which statement is true regarding SQL injection?
a) It is a technique to improve database performance.
b) It is a type of security vulnerability that allows attackers to execute
arbitrary SQL code.
c) It is a method for creating database tables.
d) It is a way to optimize database queries.
6. What is the role of a database connection in Python programming?
a) To manage user sessions in web applications
b) To facilitate communication between the Python application and the
database
c) To generate HTML content for web pages
d) To perform data visualization
7. Which of the following SQL commands is used to retrieve data from a database in
Python?
a) INSERT b) DELETE c) UPDATE d) SELECT
8. Why might a developer choose to use a NoSQL database with Python?
a) To enforce strict schema requirements
b) To handle large volumes of unstructured data
c) To perform complex SQL queries
d) To utilize traditional relational database features
9. What is a common use case for database programming in Python applications?
a) Writing mathematical algorithms
b) Storing user information and application data
c) Rendering graphics
d) Generating random numbers
10. Which of the following statements is true about transactions in a database context?
a) Transactions are not important for data integrity.
b) A transaction can contain multiple SQL statements and can be committed
or rolled back.
c) Transactions only apply to NoSQL databases.
d) Transactions are automatically managed by Python.
11. What is the purpose of SQL (Structured Query Language) in Python programming?
a) To format strings and manipulate text
b) To create and manage relational databases
c) To generate graphical user interfaces
d) To handle web requests
12. Which of the following SQL commands is used to insert new records into a table?
a) UPDATE b) INSERT c) SELECT d) DELETE
13. In Python, which library is commonly used for executing SQL commands with SQLite
databases?
a) NumPy b) Matplotlib c) SQLite3 d) Pandas
14. What is the correct SQL command to retrieve all columns from a table named
"customers"?
a) SELECT * FROM customers; b) GET ALL FROM customers;
c) SHOW customers; d) FETCH ALL FROM customers;
14. Which statement best describes the role of a primary key in a database table?
a) It is used to define the data type of each column.
b) It uniquely identifies each record in the table.
c) It is an optional field that can be null.
d) It creates a relationship between two tables.
15. How do you ensure that changes made in a transaction are saved to the database in
Python?
a) By closing the connection b) By committing the transaction
c) By rolling back the transaction d) By using the SELECT command
16. What is the purpose of the cursor object in Python's database programming?
a) To connect to the database
b) To execute SQL commands and fetch results
c) To close the database connection
d) To create new database tables
17. Which of the following SQL commands is used to update existing records in a table?
a) UPDATE b) MODIFY c) CHANGE d) ALTER
18. What SQL clause is used to filter records in a query?
a) WHERE b) HAVING c) GROUP BY d) ORDER BY
19. Which of the following statements correctly demonstrates how to connect to an SQLite
database in Python?
a) db = sqlite3.connect('database.db') b) db = sqlite3.open('database.db')
c) db = sqlite3.create('database.db') d) db = sqlite3.access('database.db')
20. When executing a SQL command, which method is used to fetch the results from a
cursor object?
a) cursor.get() b) cursor.fetch() c) cursor.fetchall() d) cursor.retrieve()
21. What does the DROP TABLE command do in SQL?
a) Deletes all records from the table but keeps the structure
b) Deletes the entire table along with all its data and structure
c) Modifies the structure of the table
d) Creates a new table
22. Which of the following SQL commands is used to delete records from a table?
a) REMOVE b) DELETE c) DROP d) TRUNCATE
23. Which Python method is used to close a database connection?
a) db.end() b) db.close() c) db.quit() d) db.terminate()
24. In SQL, what is the purpose of the ORDER BY clause?
a) To sort the results of a query
b) To filter records based on a condition
c) To join multiple tables
d) To group records based on a specific column

25. What is the primary purpose of a database adapter in Python?


a) To format output data
b) To provide a way to connect and interact with databases
c) To optimize Python code execution
d) To create graphical user interfaces
26. Which library is commonly used as a database adapter for MySQL in Python?
a) SQLite3 b) psycopg2
c) MySQL Connector/Python d) SQLAlchemy
27. What is the correct way to establish a connection to a MySQL database using MySQL
Connector in Python?
a) connection = mysql.connect(host="localhost", user="user", password="pass",
database="db")
b) connection = mysql.connector.connect(host="localhost", user="user",
password="pass", database="db")
c) connection = MySQL.connect(host="localhost", user="user", password="pass",
database="db")
d) connection = mysql.connect()
28. What is the purpose of the cursor object in MySQL database operations?
a) To establish a connection to the database
b) To execute SQL queries and fetch results
c) To close the database connection
d) To create new database tables
29. Which method is used to execute a SQL statement using a cursor object in MySQL?
a) cursor.run() b) cursor.execute_query()
c) cursor.execute() d) cursor.execute_sql()
30. How can you fetch all results from a query executed with a cursor in MySQL?
a) cursor.get_all() b) cursor.fetch_all()
c) cursor.fetchall() d) cursor.all()
31. What is the correct SQL command to create a new table named "employees"?
a) CREATE TABLE employees (id INT, name VARCHAR(100));
b) ADD TABLE employees (id INT, name VARCHAR(100));
c) INSERT TABLE employees (id INT, name VARCHAR(100));
d) NEW TABLE employees (id INT, name VARCHAR(100));
32. Which of the following SQL commands would you use to insert a new record into the
"employees" table?
a) INSERT INTO employees (id, name) VALUES (1, 'John Doe');
b) ADD RECORD employees (1, 'John Doe');
c) NEW RECORD INTO employees (1, 'John Doe');
d) CREATE RECORD employees (1, 'John Doe');
33. What is the purpose of the commit() method when working with MySQL in Python?
a) To delete a record from the database
b) To save changes made during the current transaction
c) To create a new table
d) To establish a connection to the database
34. How do you close a connection to a MySQL database in Python?
a) connection.disconnect() b) connection.terminate()
c) connection.close() d) connection.end()
35. What does the DROP TABLE SQL command do in MySQL?
a) Deletes all rows in a table but keeps the structure
b) Deletes the entire table and all its data
c) Modifies the structure of a table
d) Creates a new table
36. Which of the following Python code snippets will retrieve data from the "employees"
table?
cursor.execute("SELECT * FROM employees")
a) cursor.get("SELECT * FROM employees")
b) cursor.execute("GET ALL FROM employees")
c) cursor.execute("SELECT * WHERE employees")
d) cursor.run("SELECT * FROM employees")
37. What is the purpose of the WHERE clause in a SQL query?
a) To filter results based on specific conditions
b) To sort the results of a query
c) To join multiple tables
d) To group records by a specific column
38. How would you handle exceptions while working with MySQL in Python?
a) Using try-except blocks b) Ignoring errors
c) Using multiple connections d) Not using cursors
39. What is the role of the fetchone() method in MySQL cursor objects?
a) To fetch all rows at once
b) To fetch a single row from the result set
c) To fetch the first column only
d) To count the total number of rows
40. What is the primary purpose of regular expressions in Python?
a) To perform mathematical calculations
b) To validate and manipulate strings based on patterns
c) To create graphical user interfaces
d) To handle file operations
41. Which Python module is used for working with regular expressions?
a) regex b) re c) regexp d) expressions
42. Which function in the re module is used to search for a pattern in a string?
a) re.find() b) re.match() c) re.search() d) re.lookup()
43. What does the re.findall() function return?
a) A single match of the pattern
b) A list of all non-overlapping matches of the pattern in a string
c) The first occurrence of the pattern
d) A count of matches in the string
44. Which of the following is a correct way to compile a regular expression in Python?
a) pattern = re.compile('abc') b) pattern = re.create('abc')
c) pattern = re.regex('abc') d) pattern = re.init('abc')
45. What does the ^ character signify in a regular expression?
a) End of a string b) Start of a string
c) Any character d) Digit character
46. What does the \d pattern match in a regular expression?
a) Any non-digit character b) Any whitespace character
c) Any digit character (0-9) d) Any letter character
47. Which function is used to replace occurrences of a pattern in a string with a specified
replacement?
a) re.replace() b) re.sub() c) re.change() d) re.update()
48. What does the {m,n} quantifier specify in a regular expression?
a) Matches the preceding element exactly m times
b) Matches the preceding element at least m times and at most n times
c) Matches the preceding element zero or more times
d) Matches the preceding element one or more times
49. Which of the following regular expressions would match a valid email address?

a) ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
b) ^\w+@\w+\.\w+$
c) ^[a-zA-Z0-9]+@[a-z]+\.[a-z]{2,3}$
d) ^.+@.+\..+$

50. How would you check if a string starts with the word "Hello"?
a) re.match("Hello", string) b) re.search("Hello", string)
c) re.findall("Hello", string) d) re.begin("Hello", string)
51. What does the \s pattern match in a regular expression?
a) A single whitespace character (space, tab, newline)
b) A non-whitespace character
c) A digit character
d) A letter character
52. Which of the following statements about the re.split() function is true?
a) It splits a string based on the matches of the pattern and returns a list.
b) It replaces occurrences of a pattern in a string with a specified replacement.
c) It searches for a pattern and returns the first match.
d) It compiles a regular expression pattern for future use.
53. How can you make a regular expression case-insensitive in Python?
a) By using the flag
b) By using the re.CASEINSENSITIVE flag
c) By using re.compile('pattern', re.I)
d) By using Pattern
54. Which of the following is NOT a valid use of regular expressions in Python?
a) Validating user input (e.g., email, phone number)
b) Searching for specific patterns in strings
c) Performing complex mathematical computations
d) Replacing substrings based on patterns
55. What does the # symbol represent in Python?
a) The start of a variable name b) A comment
c) An operator d) A string delimiter
56. Which of the following is the escape character in Python?
a) \ b) / c) # d) @
57. What is the purpose of the \n character in a string?
a) To represent a tab b) To represent a new line
c) To escape the next character d) To terminate the string
58. Which symbol is used to denote a string in Python?
a) " b) & c) # d) $
59. What does the \t character represent in a string?
a) A new line b) A tab character c) A backslash d) A space character
60. What is the function of the __ (double underscore) prefix in a Python class attribute?
a) It makes the attribute public.
b) It indicates a private variable with name mangling.
c) It makes the attribute static.
d) It indicates a global variable.
61. Which symbol is used for list comprehensions in Python?
a) [] b) {} c) () d) //
62. What does the * symbol do when used in a function definition?
a) It denotes multiplication.
b) It indicates variable-length arguments (arbitrary argument list).
c) It creates a list.
d) It signifies a generator.
63. What is the purpose of the @ symbol in Python?
a) To denote a variable b) To create decorators
c) To define lists d) To concatenate strings
64. What does the ** symbol indicate when used in function arguments?
a) It multiplies the arguments.
b) It allows for variable-length keyword arguments.
c) It indicates a type hint.
d) It denotes an unpacking of a list.

65. Which character is used to indicate the end of a statement in Python?


a) . b) ; c) : d) None of the above
66. What is the result of using the // operator in Python?
a) Division and return of the remainder
b) Regular division
c) Floor division
d) Exponentiation
67. Which of the following characters is used to define a dictionary in Python?
a) [] b) () c) {} d) <>
68. What does the :, when used in a function or class definition, signify?
a) It denotes the start of a comment.
b) It indicates the end of a statement.
c) It signifies the beginning of an indented block of code.
d) It is used to separate key-value pairs in a dictionary.
69. What is the purpose of the is keyword in Python?
a) It is used for assignment.
b) It checks for equality of values.
c) It checks for object identity (whether two references point to the same
object).
d) It defines a function.
70. What does the re module in Python provide?
a) A way to perform file operations
b) Functions for working with regular expressions
c) Tools for creating graphical user interfaces
d) A framework for web development
71. Which function is used to compile a regular expression pattern in Python?
a) re.make() b) re.create() c) re.compile() d) re.build()
72. What does the re.search() function do?
a) Searches for a pattern in a string and returns the first match
b) Finds all occurrences of a pattern in a string
c) Replaces a pattern in a string
d) Splits a string by a pattern
73. Which symbol is used to indicate a digit in a regular expression?
a) \D b) \d c) \s d) \w
74. How do you match any character except a newline in a regular expression?
a) . b) \n c) * d) \s
75. What does the re.findall() function return?
a) A single match of the pattern
b) A list of all non-overlapping matches of the pattern in a string
c) The first occurrence of the pattern
d) The count of matches in the string
76. Which character is used to denote the start of a string in a regular expression?
a) $ b) ^ c) * d) @
77. What does the re.sub() function do?
a) Searches for a pattern in a string
b) Replaces occurrences of a pattern with a specified string
c) Splits a string by a pattern
d) Finds all matches of a pattern
78. What is the purpose of the * quantifier in a regular expression?
a) Matches the preceding element zero or more times
b) Matches the preceding element one or more times
c) Matches the preceding element exactly n times
d) Matches any character
79. How can you make a regular expression case-insensitive in Python?
a) By using flag
b) By using the re.case_insensitive flag
c) By using the re.compile('pattern', re.I) method
d) By using pattern
80. Which function would you use to split a string based on a regex pattern?
a) re.split() b) re.partition() c) re.cut() d) re.separate()
81. What does the + quantifier mean in a regular expression?
a) Matches the preceding element one or more times
b) Matches the preceding element zero or more times
c) Matches exactly n times
d) Matches a single character
82. How do you escape special characters in a regular expression?
a) Using the escape character \\ b) Using single quotes
c) Using double quotes d) There is no need to escape special characters
83. What does the $ character signify in a regular expression?
a) End of a string b) Start of a string c) A special character d) A digit
84. Which of the following regular expressions would correctly match an email address?
a) r"\w+@\w+\.\w+"
b) r"{2,}"
c) r"^[a-zA-Z0-9]”
d) r"{2,3}"

You might also like