Python Review Questions
Python Review Questions
The following questions are meant to help you review introductory concepts in Python. They are based on the Python 3 Tutorial and Python 3 Documentation and were written to accompany a 5 lecture series on Python.
There are three types of questions:
- Verify the Code: Determine the output of a code snippet.
- Fill in the Code: Fill in the code to complete a code snippet.
- Create the Function: Create a function that satisfies the given requirements.
Verify the Code
-
Operations on Strings
print("Hello" + " " + "World" * 2)What will the output be?
Solution
Hello World WorldExplanation: The
+operator concatenates strings, and the*operator repeats strings. -
Looping Over Lists
for i in [1, 2, 3]: print(i * 2)What will the output be?
Solution
2 4 6Explanation: The
forloop iterates over the elements of the list. -
Mutability of Strings
s = "hello" s[0] = "H"Is this code valid? If not, why?
Solution
This code is not valid. Strings are immutable, so you cannot change their elements.
-
Static Methods vs. Instance Methods
class MyClass: def instance_method(self): return 'instance method' @staticmethod def static_method(): return 'static method' obj = MyClass() print(obj.instance_method()) print(MyClass.static_method())What will the output be?
Solution
instance method static methodExplanation: Instance methods are called on an instance of a class, whereas static methods are called on the class itself.
-
yieldKeyword Exampledef my_gen(): yield "A" yield "B" gen = my_gen() print(next(gen)) print(next(gen)) print(next(gen))What will the output be?
Solution
A B Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIterationExplanation: The
yieldkeyword is used to create generators. Generators are iterators that can be iterated over only once. -
Type Validation
x = 42 print(isinstance(x, int))What will the output be?
Solution
TrueExplanation: The
isinstancefunction checks if an object is of a certain type. -
inputAlways Returns astrx = input("Enter a number: ") print(type(x) is int)If the user enters
42, what will the output be?Solution
FalseExplanation: The
inputfunction always returns astr, even if the user enters a number. -
Search in List Example
my_list = [1, 2, 3, 4, 5] print(3 in my_list)What will the output be?
Solution
TrueExplanation: The
inoperator checks if an element is in a list. -
Formatted Printing
name = "Alice" age = 30 print(f"{name} is {age} years old.")What will the output be?
Solution
Alice is 30 years old.Explanation: The
fprefix allows you to use formatted strings. -
Equality Versus
isx = [1, 2, 3] y = [1, 2, 3] print(x == y) print(x is y)What will the output be?
Solution
True FalseExplanation: The
==operator checks if two objects are equal, whereas theisoperator checks if two objects are the same object. -
CSV Line to List Using
splitline = "apple,banana,cherry" fruits = line.split(',') print(fruits)What will the output be?
Solution
['apple', 'banana', 'cherry']Explanation: The
splitmethod splits a string into a list of strings using a delimiter. -
Deep vs. Shallow Copy
import copy a = [1, [2, 3]] b = copy.copy(a) c = copy.deepcopy(a) a[1][0] = 99 print(b) print(c)What will the output be?
Solution
[1, [99, 3]] [1, [2, 3]]Explanation: The
copyfunction creates a shallow copy, whereas thedeepcopyfunction creates a deep copy. -
Access Class Variable vs. Instance Variable
class Dog: kind = 'canine' def __init__(self, name): self.name = name d = Dog('Fido') print(d.kind) print(d.name)What will the output be?
Solution
canine FidoExplanation: The
kindvariable is a class variable, whereas thenamevariable is an instance variable. -
Accessing
globalVariablex = 10 def foo(): global x x += 5 print(x) foo()What will the output be?
Solution
15Explanation: The
globalkeyword allows you to access a global variable inside a function.
Fill in the Code
-
Looping Over 2D Lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # Fill in the code to print each element in the 2D list.Solution
for row in matrix: for element in row: print(element)Explanation: The outer loop iterates over the rows, and the inner loop iterates over the elements in each row.
-
Static Methods vs. Instance Methods
class Calculator: @staticmethod def add(a, b): return a + b # Fill in the code to create an instance method that multiplies two numbers.Solution
class Calculator: @staticmethod def add(a, b): return a + b def multiply(self, a, b): return a * bExplanation: Instance methods take
selfas the first argument. -
List Comprehension for 2D List
# Fill in the code to create a 2D list with list comprehension. # The 2D list should contain rows from 0 to 4 and columns from 0 to 4, # where each element is the sum of its row and column index.Solution
matrix = [[row + col for col in range(5)] for row in range(5)]Explanation: The outer loop iterates over the rows, and the inner loop iterates over the columns.
-
Dictionary Add, Iterating Over Keys and Values
my_dict = {'apple': 1, 'banana': 2} # Fill in the code to add a key-value pair ('cherry', 3) to my_dict and print all keys and values.Solution
my_dict['cherry'] = 3 for key in my_dict: print(key, my_dict[key])Explanation: The
forloop iterates over the keys of the dictionary. -
Add List to Existing List (Zip vs. Extend)
list1 = [1, 2, 3] list2 = [4, 5, 6] # Fill in the code to append the elements of list2 to list1.Solution
list1.extend(list2)Explanation: The
extendmethod appends the elements of a list to another list. -
Override Special Method So Class Can Be Sorted
class Person: def __init__(self, name, age): self.name = name self.age = age # Fill in the code to make instances of this class sortable by age.Solution
class Person: def __init__(self, name, age): self.name = name self.age = age def __lt__(self, other): return self.age < other.ageExplanation: The
__lt__method overrides the<operator. Either this method or the__gt__method must be defined for the class to be sortable.
Create the Function
-
Reading Input From the User
numbers = read_numbers_from_user(5) print("The sum is:", sum(numbers))Create the function
read_numbers_from_userthat takes an integer ( n ) and reads ( n ) numbers from the user.Solution
def read_numbers_from_user(n): numbers = [] for i in range(n): numbers.append(int(input("Enter a number: "))) return numbersExplanation: The
inputfunction reads a string from the user. Theintfunction converts a string to an integer. -
Match Statement vs. If-Elif-Else
print(match_fruit_color("apple"))Create the function
match_fruit_colorthat takes a fruit name and returns its color using a match statement.Solution
def match_fruit_color(fruit): match fruit: case "apple": return "red" case "banana": return "yellow" case "cherry": return "red" case _: return "unknown"Explanation: The
matchstatement is used to compare a value against a number of patterns. It is similar to theswitchstatement in other languages. -
Formatted Printing
print_formatted_string("John", 25)Create the function
print_formatted_stringthat takes a name and an age and prints them in a formatted string.Solution
def print_formatted_string(name, age): print(f"{name} is {age} years old.")Explanation: The
fprefix allows you to use formatted strings. -
Type Validation
print(is_valid_number("42"))Create the function
is_valid_numberthat takes a string and returns True if it can be converted to an integer or a float, otherwise False.Solution
def is_valid_number(s): try: float(s) return True except ValueError: return FalseExplanation: The
trystatement allows you to handle exceptions. Thefloatfunction converts a string to a float. If a string could be converted to afloat, it can also be converted to anint. -
Accessing
globalVariableincrement_global_x() print(x)Create the function
increment_global_xthat increments the global variable ( x ) by 1.Solution
def increment_global_x(): global x x += 1Explanation: The
globalkeyword allows you to access a global variable inside a function.