Exam-2024 Flashcards
What happens if you run the following code?
a = (4, 5, 6)
a [1] = 10
a) a wil be automatically converted to a list.
b) The code will raise a TypeError because tuples are immutable.
c) The tuple a wil be modified in place.
d) a wil contain the tuple (4, 10, 6)
b is correct
After executing the following code
x = 42
y = x
how many times is 42 stored in memory?
a) O because it is a constant.
b) 1
c) 42
d) 2
b is correct
A Python dictionary …
a. … allows keys of different data types.
b … allows access to values using keys.
c. … stores keys in sorted order.
d. … is mutable.
a, b, d is correct
A Python set …
- a) … can store duplicate elements.
- b) . . . maintains the order of elements as they are added.
- c) … supports set operations like union and intersection.
- d) … automaticaly removes duplicate elements.
c, d is correct
Assume that my_arr is a NumPy array with shape (2, 3 , 4 , 5 , 6). When executing the code partial = my_arr ( : , 0 , 0), what would the shape of the resulting NumPy array partial be?
a) (2, 0, 0, 5, 6)
b) (4, 5, 6)
c) (2, 3, 4)
d) (2, 3, 4, 5, 6, 0, 0)
e) (2, 5, 6)
e is correct
The slicing operation my_arr[:, 0, 0] means:
: selects all elements along the first dimension (size 2).
0 selects the first element along the second dimension (size 3).
0 selects the first element along the third dimension (size 4).
Consider a NumPy array with shape (2, 5). Which of the following shapes are valid (i.e., no error) when reshaping this array?
a. (10, 1)
b. (-1, 10)
c. (10,)
d. (2, 5, 10)
e. (1, 2, 5)
f. (7,)
g. (5, 2)
a, b, c, e, g are correct
Consider the following code and assume that function a_function() raises a ValueError:
try: a_function() raise TypeError except ValueError: print("there was an exception!") finally: print ("done!")
Which of the following statements are correct?
Note: The order of the answers can be ignored.
a) The ValueError is caught and a TypeError is then raised afterwards.
b) “there was an exception!” is printed.
c) The ValueError is not caught.
d) Nothing is printed.
e) “done!” is printed.
f) The ValueError is caught and the program continues normall
b, e, f are correct
Consider the following code:
What is the output when calling f (5)?
Note: Errors in the answers below indicate that the function call ended with this error currently being raised.
a)
g1
g2
f4
b)
f4
c)
f3
f4
d)
g1
g2
f1
f3
f4
e)
g1
g2
ValueError
d is correct
Consider the following function:
Which of the following statements are correct?
- a) The function only works with integer numbers.
- b) If passing two integer numbers for a and b, the return type is indicated to be an integer number.
- c) The type hints indicate that the function should only be used with integer numbers.
- d) Passing two floating point numbers for a and b wil crash the program.
b, c is correct
Consider the following (partial) code and assume some_condition is True:
Which of the following statements are true?
- a) A ValueError is raised and function g is exited immediately.
- b) If function f has an error handling code for a ValueError, the error is caught and this code is executed.
- c) A ValueError is raised after function g executed its remaining code below the raise statement.
- d) If function f does not have any error handling code for a ValueError, the error remains active and f is exited immediately (after potentially executing a finally clause in case there is one).
a, b, d are correct
Given a function
def fun(a, b, *args, c, **kwargs): #some code
what would a r g s and kwargs contain after the following invocation:
my_list = [1, 2] my_dict = {"c": 3} fun(0, *my_list, **my_dict)
?
a) a r g s = ( 0 , 1 , 2 ) and kwargs = {"C" }
b) a r g s = ( 1 , 2 ) and kwargs = { }
c) a r g s = (2,) and kwargs = {"c": 3 }
d) a r g s = ( 2 , ) and kwargs = { }
e) args = ( 0 , 1 , 2) and kwargs = 0
f) a r g s = ( 1 , 2 ) and kwargs = {"c": 3}
d is correct
Let me analyze this step by step:
1) In the function call fun(0, *my_list, **my_dict)
:
- The first argument 0
goes to parameter a
- *my_list
unpacks [1, 2]
which starts filling from parameter b
- **my_dict
unpacks {"c": 3}
2) Looking at the function definition def fun(a, b, *args, c, **kwargs)
:
- a
gets 0
- b
gets 1
(first element from unpacked my_list)
- The remaining 2
from my_list goes into *args
- c
gets the value 3
from the unpacked dictionary {"c": 3}
- Since no more keyword arguments remain, **kwargs
will be empty
3) Therefore:
- args
will contain (2,)
- a tuple with just one element
- kwargs
will be {}
- an empty dictionary
4) Looking at option d: args = (2,) and kwargs = {}
This matches exactly what we determined!
The answer d is indeed correct because:
- It correctly shows that args
captures the remaining positional argument 2
after a
and b
are assigned
- It correctly shows that kwargs
is empty since the only keyword argument went to parameter c
The key insight is understanding how the positional arguments are distributed first to a
and b
, with the remainder going to args
, while the keyword argument c
is filled from my_dict
, leaving kwargs
empty.
When used in a function definition (like *args): It
Single asterisk *:
Given a function (see image)
def my_func(a, b=1, *args): # some code
, which of the following invocations are valid (i.e., no error)?
a. my_func(100, 200, 300)
b. my_ func ()
c. my_ func(100, 200)
d. my_ func (100)
e. my_func (b=200)
f. my_func(a=100, c=300)
g. my_ func (a=100)
a, c, d, g are correct
Given a list my_list of length 20, what does the followina code do?
my_ list [5: :4]
- a) It returns a list of every fourth element starting from index 5.
- b) It raises an IndexError because the step size is too large.
- c) It returns a list of the first four elements starting from index 5.
- d) It returns an empty list.
a is correct
Given a nested list nested = [["apple", "banana"], ["cherry", "date"]]
, which code snippet extracts the string “cherry”?
a) n e s t e d [1] [ 0 ]
b) nested [0] [“cherry”]
c) n e s t e d [ 0 ] ( 1 ]
d) n e s t e d [ 1 ] [“cherry”]|
a is corret
Given the following code that represents an animal, choose the best implementation of the subclass Cat!
b is correct
This is correct because it:
- Properly inherits from Animal using class Cat(Animal)
- Uses super().__init__(age) to call the parent’s initialization, which includes the age validation
- Then sets the Cat-specific fur_color attribute
How can you print a variable’s value to the console in Python?
a. print(variable_name)
b. echo(variable_name)
c. write(variable_name)
d. console.log(variable_name)
a is correct
Python is a dynamically typed language, which means that ..
- a) … Python is an object-oriented programming language.
- b) … data types are fixed and cannot change once assigned.
- c) … the data type is associated with the value rather than the variable and is determined during run time.
- d) … variables must be explicitly declared with a data type.
c is correct
Select all valid (i.e., no error) indexing and slicing code snippets for a list my_list of length 10.
a) my_list[10]
b) my_list[-1]
c) my_list[0:5]
d) my_list[9]
e) my_list[2.5]
f) my_list[::-1]
b, c, d, f are correct
Select all values of a for which the following boolean expression evaluates to True
(a < 0 or a > 5) and a != 3
a) 0
b) -1
c) 6
d) 10
e) 3
b, c, d are correct
Select the correct function implementations that fulfill the following task:
Write a function that takes a list of integers as input. All negative numbers in this list are replaced with their positive values. The function does
not return anything, i.e., the passed list must be changed directly (in-place).
Note: You can assume correct arguments.
a, b, d are correct
a.
Explanation:
* The function modifies some_list in place.
* It iterates through the list using enumerate, which provides both the index i and the value v.
b.
Explanation:
* This function uses a list comprehension to create a new list where each value is replaced by its absolute value (-v for negative values, v otherwise).
* The [:] notation ensures the original list some_list is updated in place.
* Behavior: Modifies the list in place.
c.
Explanation:
* This function uses a list comprehension to create a new list where each value is replaced by its absolute value.
* However, assigning some_list = … creates a new list and rebinds the local variable some_list to this new list.
* The original list passed to the function is not modified.
* Behavior: Does not modify the original list.
d.
Explanation:
* This function modifies some_list in place.
* It iterates over the list by index (i) using range(len(some_list)).
* If the element at index i is negative, it replaces it with its positive counterpart.
* Behavior: Modifies the list in place.
What happens when you execute the following code?
my_dict = {"a": 1, "b": 2} my_dict{"c"} = 3
- a) Nothing happens because dictionaries are immutable.
- b) The dictionary is replaced with a new one containing only the key “c”.
- c) A new key-value pair (“c”: 3) is added to my_dict.
- d) The code raises a KeyError since “c” does not exist in my_dict.*
c is correct
What does the following code do?
with open("data.txt", "a") as f: f.write("New data")
- a) It opens the specified file in append mode and reads the file content into f .
- b) It opens the specified file in write mode, writes “New data” to the file, and then closes the file.
- c) It opens the specified file in read mode and appends “New data” to the file content.
- d) It opens the specified file in append mode, writes “New data” to the file, and then closes the file.
d is correct
What is the difference between object/instance attributes and class attributes?
- a) Object attributes belong to the object and exist for each such object. Class attributes belong to the class and are copied for every created object.
- b) Object attributes belong to the object and exist for each such object. Class attributes belong to the class and exist only once.
- c) Object attributes and class attributes are synonyms and function the same way.
- d) Object attributes belong to the object but exist only once and are shared across all objects. Class attributes belong to the class and exist only once.
b is correct
What is the output when executing the following code?
class Animal: def eat(self): print("Animal eats") class Fish(Animal): pass class Shark(Fish): def eat(self): print("Shark eats") for a in [Animal(), Fish(), Shark()]: a.eat()
a)
Animal eats
Shark eats
Shark eats
b)
Animal eats
Animal eats
Shark eats
c)
Animal eats
Shark eats
(no output because class Fish does not produce any output)
d)
There will be an error because class Fish does not have a method eat.
e)
Animal eats
Fish eats
Shark eats
f)
Animal eats
Animal eats
Animal eats
b is correct
See image
(b), c are correct
b is misleading though because inheritance happens automatically (e.g. see image