




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
This beginner-level course teaches Python programming from scratch. It covers basic syntax, data types, control flow, functions, and modules. Students will learn how to write Python scripts and work with libraries for data manipulation and web development.
Typology: Exams
1 / 115
This page cannot be seen from the preview
Don't miss anything!





























































































Question 1. What command checks the installed Python version from the command line? A) python --verify B) python - V C) python /check D) python - info Answer: B Explanation: The -V (or --version) flag prints the current Python interpreter version. Question 2. Which of the following is a valid identifier for a variable in Python? A) 2nd_place B) _totalScore C) class D) my-variable Answer: B Explanation: Identifiers may start with a letter or underscore; they cannot begin with a digit, use reserved keywords, or contain hyphens. Question 3. What is the output of the statement print("Hello", "World", sep="-")? A) Hello-World B) Hello World C) Hello,-World D) Hello- World Answer: A
Explanation: The sep argument replaces the default space between arguments with the specified string, here a hyphen. Question 4. When using the input() function, what type is the returned value? A) int B) float C) str D) bool Answer: C Explanation: input() always returns a string; conversion is required for other types. Question 5. Which statement correctly converts the string "123" to an integer? A) int("123") B) float("123") C) str(123) D) bool("123") Answer: A Explanation: The int() constructor parses a numeric string into an integer. Question 6. What is the result of 5 ** 3 in Python? A) 8 B) 15 C) 125 D) 53 Answer: C
Explanation: is tests object identity; small integers are cached, so 5 is 5 is True. Equality == would be False because of type mismatch. Question 10. What is the Boolean result of not (True and False)? A) True B) False C) None D) Error Answer: A Explanation: True and False evaluates to False; applying not yields True. Question 11. Which statement correctly uses a membership test to check if 'a' is in the list ['b', 'a', 'c']? A) 'a' in ['b', 'a', 'c'] B) ['b', 'a', 'c'] contains 'a' C) ['b', 'a', 'c'] .has 'a' D) 'a' == ['b', 'a', 'c'] Answer: A Explanation: The in operator checks for element presence in an iterable. Question 12. Which syntax represents a correct if‑elif‑else block? A) if x > 0: print("pos") elif x < 0: print("neg") else: print("zero") B) if (x > 0) {print("pos")} elif (x < 0) {print("neg")} else {print("zero")} C) if x > 0 then print("pos") else if x < 0 then print("neg") else print("zero") D) if x > 0; print("pos") elif x < 0; print("neg") else; print("zero")
Answer: A Explanation: Python uses colons and indentation; option A follows that rule. Question 13. What does the ternary expression result = "Even" if n % 2 == 0 else "Odd" do? A) Assigns "Even" to result only when n is odd. B) Assigns "Odd" to result only when n is even. C) Assigns "Even" when n is divisible by 2, otherwise "Odd". D) Raises a syntax error. Answer: C Explanation: The ternary operator value_if_true if condition else value_if_false selects based on the condition. Question 14. Which loop will run exactly three times? A) while True: pass B) for i in range(3): print(i) C) while i < 3: i += 1 (with i undefined) D) for i in [0,1,2,3]: break Answer: B Explanation: range(3) generates 0,1,2; the loop iterates three times. Question 15. What keyword exits a loop immediately? A) stop B) exit C) break
Answer: A Explanation: enumerate pairs each element with its index. Question 19. Which statement defines a function named add that returns the sum of two parameters? A) def add(a, b): return a + b B) function add(a, b) { return a + b } C) add = lambda a, b: a + b D) Both A and C are valid. Answer: D Explanation: Both the standard def syntax and a lambda assignment create callable objects named add. Question 20. How can you call a function greet with the argument "Alice" using a keyword argument? A) greet(name="Alice") B) greet("Alice") C) greet(Alice) D) greet = "Alice" Answer: A Explanation: Keyword arguments specify the parameter name; name="Alice" passes the value to the corresponding parameter. Question 21. What is the default value of a parameter defined as def foo(x, y=10): when foo(5) is called? A) 5
C) None D) Error Answer: B Explanation: If the caller omits y, the default 10 is used. Question 22. Which syntax correctly captures an arbitrary number of positional arguments? A) def func(*args): B) def func(**args): C) def func(args*): D) def func(args): Answer: A Explanation: *args collects extra positional arguments into a tuple. Question 23. How would you define a function that accepts any number of keyword arguments? A) def f(*kwargs): B) def f(**kwargs): C) def f(kwargs*): D) def f(kwargs): Answer: B Explanation: **kwargs gathers extra keyword arguments into a dictionary. Question 24. What will be printed by the following code?
Question 26. How do you import only the sqrt function from the math module? A) import math.sqrt B) from math import sqrt C) import sqrt from math D) include math.sqrt Answer: B Explanation: from module import name imports a specific attribute. Question 27. What does random.randint(1, 6) return? A) A random float between 1 and 6 B) A random integer including both 1 and 6 C) Always 1 D) An error because randint is not in random Answer: B Explanation: randint(a, b) returns an integer N such that a <= N <= b. Question 28. Which statement correctly creates a new module file named utils.py containing a function hello()? A) Write def hello(): print("Hi") inside a file called utils.py. B) Write module utils: def hello(): pass inside any file. C) Use import utils to automatically generate the file. D) Create a class named utils with method hello. Answer: A
Explanation: A module is simply a .py file; defining a function inside it makes it accessible after import. Question 29. Which of the following list methods modifies the list in place and returns None? A) sorted(mylist) B) mylist.append(5) C) mylist.copy() D) mylist + [5] Answer: B Explanation: append adds an element to the original list and returns None. sorted creates a new list. Question 30. What is the result of list(range(2, 8, 2))? A) [2, 4, 6] B) [2, 3, 4, 5, 6, 7] C) [0, 2, 4, 6, 8] D) [2, 8] Answer: A Explanation: range(start, stop, step) generates numbers 2,4,6 (stop is exclusive). Question 31. Which list comprehension produces a list of squares for numbers 0‑4? A) [x**2 for x in range(5)] B) list(x*x for x in range(5)) C) {x**2 for x in range(5)} D) ([x**2] for x in range(5))
try: t[0] = 4 except TypeError as e: print("Error")
A) `Error` B) `4` C) No output D) `TypeError` traceback Answer: A Explanation: Tuples are immutable; attempting item assignment raises `TypeError`, which is caught and prints "Error". Question 35. **Which dictionary method returns a view of all key‑value pairs?** A) `keys()` B) `values()` C) `items()` D) `get()` Answer: C Explanation: `dict.items()` provides a view object containing `(key, value)` tuples. Question 36. **How can you safely retrieve the value for key `'age'` from `person = {'name':'Bob'}` without raising an exception?** A) `person['age']` ## Certificate Practice Exam B) `person.get('age')` C) `person['age'] = None` D) `person.fetch('age')` Answer: B Explanation: `dict.get(key, default=None)` returns `None` (or a provided default) if the key is missing. Question 37. **What does the following code print?** ```python d = {'a':1, 'b':2} d['c'] = d.pop('a') print(d) A) {'b': 2, 'c': 1} B) {'a': 1, 'b': 2, 'c': 1} C) {'b': 2, 'c': 2} D) {'c': 1} Answer: A Explanation: pop('a') removes key 'a' and returns its value (1), which is then assigned to 'c'. Question 38. Which expression creates a set containing the numbers 1, 2, and 3? A) {1, 2, 3} B) [1, 2, 3]
D) The file is read line by line automatically. Answer: B Explanation: The context manager ensures f.close() is called on exit. Question 42. Which mode opens a file for appending, creating it if it does not exist? A) 'r' B) 'w' C) 'a' D) 'x' Answer: C Explanation: 'a' stands for append mode. Question 43. What is the output of the following code?
with open('tmp.txt','w') as f: f.write('Hello') print(f.closed) A) True B) False C) None D) Raises an error because f is out of scope Answer: A
Explanation: After the with block, the file is automatically closed; f.closed is True. Question 44. Which exception is raised when converting the string 'abc' to an integer? A) ValueError B) TypeError C) SyntaxError D) NameError Answer: A Explanation: Non‑numeric strings cause a ValueError during casting. Question 45. What does the finally block do in a try/except/finally construct? A) Executes only if an exception occurs. B) Executes only if no exception occurs. C) Executes regardless of whether an exception was raised. D) Skips execution if an exception is caught. Answer: C Explanation: finally runs after the try and any except blocks, always. Question 46. Which code correctly catches a ZeroDivisionError and prints "Cannot divide"? A)
try: 1/ ## Certificate Practice Exam ```python try: 1/ except ZeroDivisionError: raise Answer: A Explanation: Option A directly catches the specific exception and prints the message. Question 47. What is the purpose of the else clause in a try/except/else statement? A) Executes only if an exception occurs. B) Executes only if no exception occurs in the try block. C) Executes after the finally block. D) Re‑raises the caught exception. Answer: B Explanation: The else block runs when the try block finishes without raising an exception. Question 48. Which statement correctly defines a class named Animal with an initializer that sets species? A)
class Animal: ## Certificate Practice Exam def __init__(self, species): self.species = species B)
def class Animal: __init__(self, species): self.species = species C)
class Animal(): init(self, species): self.species = species D)
class Animal: def init(self, species):