Python Essentials 1 – Module 4 Test Answers (Completion)

1. Which one of the following lines properly starts a parameterless function definition?

  • def fun():
  • function fun():
  • def fun:
  • fun function():
Explanation: The correct way to declare a function in Python is to use the reserved keyword def followed by the name of the function, parentheses () and a colon ‘:’. Since it is parameterless, the parentheses are empty.

2. A function defined in the following way: (Select two answers)

def function(x=0):
    return x
  • may be invoked with exactly one argument
  • must be invoked without any argument
  • may be invoked without any argument
  • must be invoked with exactly one argument
Explanation: The function has a predefined value for the parameter x; therefore it can be invoked with or without it. However, more than one argument will generate a runtime error.

3. A built-in function is a function which:

  • has to be imported before use
  • has been placed within your code by another programmer
  • comes with Python, and is an integral part of Python
  • is hidden from programmers
Explanation: Built-in functions are integrated in Python. Once Python is installed, they are available and can be used.

4. The fact that tuples belong to sequence types means that:

  • they can be indexed and sliced like lists
  • they can be extended using the .append() method
  • they can be modified using the del instruction
  • they are actually lists
Explanation: Tuples are immutable objects, so they can be indexed and sliced like lists. However, during runtime they cannot be extended or modified. They are NOT lists.

5. What is the output of the following snippet?

def f(x):
    if x == 0:
        return 0
    return x + f(x - 1)
 
 
print(f(3))
  • 1
  • the code is erroneous
  • 3
  • 6
Explanation: Let’s analyze the code:

  • the f function is invoked with an integer argument of 3,
  • the function begins its execution with an integer value of 3 for the x variable.
  • the if conditional compares 3 == 0, and since it is false, it is not executed,
  • the function reaches the return statement, and an integer value of 3 is held in the memory, plus a recursive invocation of the f function with an integer argument of 2,
  • the if conditional compares 2 == 0, and since it is false, it is not executed,
  • the function reaches the return statement, and an integer value of 2 is held in the memory ,plus a recursive invocation of the f function with an integer argument of 1,
  • the if conditional compares 1 == 0, and since it is false, it is not executed,
  • the function reaches the return statement, and an integer value of 1 is held in the memory, plus a recursive invocation of the f function with an integer argument of 0,
  • the if conditional compares 0 == 0, and since it is true, the return statement 0 is executed and the recursive invocation is broken,
  • Each recursive invocation returns its value and the addition is printed on the console, which is 6.

6. What is the output of the following snippet?

def fun(x):
    x += 1
    return x
 
 
x = 2
x = fun(x + 1)
print(x)
  • the code is erroneous
  • 4
  • 5
  • 3
Explanation: Let’s analyze the code:

  • the x variable is assigned an integer value of 2,
  • the fun function is invoked with an argument of (2+1), and the result will be assigned to the x variable,
  • the execution of the fun function begins, which receives 3, and then increments it by 1, and returns 4,
  • the x variable receives the integer value of 4,
  • the variable x is printed on the console.

7. What code would you insert instead of the comment to obtain the expected output?
Expected output:

a
b
c
Code:

dictionary = {}
my_list = ['a', 'b', 'c', 'd']
 
for i in range(len(my_list) - 1):
    dictionary[my_list[i]] = (my_list[i], )
 
for i in sorted(dictionary.keys()):
    k = dictionary[i]
    # Insert your code here.
  • print(k[‘0’])
  • print(k[0])
  • print(k[“0”])
  • print(k)
Explanation: Let’s analyze the code:

  • an empty dictionary is created,
  • a list named my_list with the elements [‘a’, ‘b’, ‘c’, ‘d’] is created,
  • a for loop in the range of the list length minus one (0 to 3) is initialized, and the values that the i variable iterates are a,b,c,d,
  • for each iteration, a key-pair value will be inserted in the dictionary. The key is a String, and the value is a tuple with one element,
  • the resulting dictionary is: {‘a’: (‘a’,), ‘b’: (‘b’,), ‘c’: (‘c’,)}
  • another for loop is initialized, and the i variable iterates the sorted dictionary keys,
  • the k variable stores the value for each key,
  • since it is a tuple, it is necessary to select the print(k[0]) option in order to print the first and only element.

8. The following snippet:

def func(a, b):
    return a ** a
 
 
print(func(2))
  • will return None
  • will output 4
  • will output 2
  • is erroneous
Explanation: The code snippet is erroneous because the function is invoked with one argument, but two are needed, since both parameters don’t have a predefined value.

9. The following snippet:

def func_1(a):
    return a ** a
 
 
def func_2(a):
    return func_1(a) * func_1(a)
 
 
print(func_2(2))
  • is erroneous
  • will output 2
  • will output 16
  • will output 4
Explanation: Let’s analyze the code:

  • the func_2 function is invoked with the integer 2 as its argument,
  • the func_2 function returns the product of func_1(2) * func_1(2)
  • the func_1 function is invoked twice with an integer argument of 2,
  • the func_1 function returns 2*2, which is 4,
  • the func_2 function returns the product of 4 * 4, which is 16,
  • the result is printed on the console.

10. Which of the following lines properly starts a function using two parameters, both with zeroed default values?

  • fun fun(a, b=0):
  • def fun(a=b=0):
  • fun fun(a=0, b):
  • def fun(a=0, b=0):
Explanation: The correct way to define parameters with default values is to state the name of the variable, the assignment sign (=), and the default value, e.g. a=0. If there are more default values, separate them with commas.

11. Which of the following statements are true? (Select two answers)

  • The None value can be assigned to variables
  • The None value cannot be used outside functions
  • The None value can be compared with variables
  • The None value can be used as an argument of arithmetic operators
Explanation: The None value can be assigned to any variable, inside and outside of functions. It can also be used in conditionals and loops. However, it cannot be used in arithmetic operations.

12. What is the output of the following snippet?

def fun(x):
    if x % 2 == 0:
        return 1
    else:
        return
 
 
print(fun(fun(2)) + 1)
  • 2
  • the code will cause a runtime error
  • None
  • 1
Explanation: Let’s analyze the code:

  • the inner parentheses in the print function are executed first,
  • the fun function is invoked with the integer 2 as an argument,
  • the if conditional 2 % 2 == 0 returns True, so the fun function returns 1,
  • the fun function is invoked with the integer 1 as its argument,
  • the if conditional 1 % 2 == 0 returns False, so the fun function returns None,
  • The arithmetic operation None + 1 is attempted,
  • A runtime error is generated: TypeError: unsupported operand type(s) for +: ‘NoneType’ and ‘int’.

13. What is the output of the following snippet?

def fun(x):
    global y
    y = x * x
    return y
 
 
fun(2)
print(y)
  • None
  • 2
  • 4
  • the code will cause a runtime error
Explanation: Let’s analyze the code:

  • the fun function is invoked with the integer 2 as its argument,
  • the fun function makes the y variable a global variable, which can be used both inside and outside of the function,
  • the operation y = 2 * 2 is performed, and the answer is the integer 4,
  • the function returns the y variable value,
  • the print(y) instruction prints the integer 4 on the console.

14. What is the output of the following snippet?

def any():
    print(var + 1, end='')
 
 
var = 1
any()
print(var)
  • 12
  • 11
  • 21
  • 22
Explanation: Let’s analyze the code:

  • the var variable is assigned the integer 1 as its value,
  • the any& function is invoked, and it executes the arithmetic operation 1+1 and prints the result 2 on the console. The instruction end=” prevents a newline jump,
  • the instruction print(var) prints 1 on the console.

15. Assuming that my_tuple is a correctly created tuple, the fact that tuples are immutable means that the following instruction:

my_tuple[1] = my_tuple[1] + my_tuple[0]
  • can be executed if and only if the tuple contains at least two elements
  • is fully correct
  • may be illegal if the tuple contains strings
  • is illegal
Explanation: The operation is illegal because the ‘tuple’ object does not support item assignment.

16. What is the output of the following snippet?

my_list = ['Mary', 'had', 'a', 'little', 'lamb']
 
 
def my_list(my_list):
    del my_list[3]
    my_list[3] = 'ram'
 
 
print(my_list(my_list))
  • [‘Mary’, ‘had’, ‘a’, ‘ram’]
  • no output, the snippet is erroneous
  • [‘Mary’, ‘had’, ‘a’, ‘lamb’]
  • [‘Mary’, ‘had’, ‘a’, ‘little’, ‘lamb’]
Explanation: Let’s analyze the code:

  • a list named my_list is created,
  • a function named my_list is created,
  • the print function tries to invoke the my_list function using the list my_list as an argument. However, the list my_list no longer exists because the function has the same name, and the function replaces the list,
  • the code will end in a runtime error because the function does not support item deletion.

17. What is the output of the following snippet?

def fun(x, y, z):
    return x + 2 * y + 3 * z
 
 
print(fun(0, z=1, y=3))
  • 0
  • 3
  • the snippet is erroneous
  • 9
Explanation: Let’s analyze the code:

  • the fun function is invoked, and the arguments take these values: x = 0, y = 3, z = 1. Remember that positional arguments should be placed before keyword arguments,
  • the fun function returns the result of the following arithmetic operation: 0 + 2 * 3 + 3 * 1,
  • the products are carried out first: 0 + 6 + 3,
  • the addition is performed, and the result is 9,
  • the print function shows 9 in the console.

18. What is the output of the following snippet?

def fun(inp=2, out=3):
    return inp * out
 
 
print(fun(out=2))
  • 6
  • 4
  • the snippet is erroneous
  • 2
Explanation: Let’s analyze the code:

  • the fun function is invoked, and the argument used is out = 2, which replaces the predefined value of out = 3,
  • the fun function takes the predefined value of inp = 2, since it is not defined in the invocation of the function,
  • the fun function performs the operation 2*2 and returns it,
  • the print function shows 4 on the console.

19. What is the output of the following code?

dictionary = {'one': 'two', 'three': 'one', 'two': 'three'}
v = dictionary['one']
 
for k in range(len(dictionary)):
    v = dictionary[v]
 
print(v)
  • one
  • three
  • two
  • (‘one’, ‘two’, ‘three’)
Explanation: Let’s analyze the code:

  • the following dictionary is defined: dictionary = {‘one’: ‘two’, ‘three’: ‘one’, ‘two’: ‘three’}
  • the v variable stores the value for key ‘one’, which is ‘two’,
  • a for loop is initialized in the range of the dictionary’s length. It will iterate 3 times,
  • in the first iteration, the v variable will store the value for key ‘two’, which is ‘three’,
  • in the second iteration, the v variable will store the value for key ‘three’, which is ‘one’,
  • in the third iteration, the v variable will store the value for key ‘one’, which is ‘two’,
  • the for loop is exited and the print function shows ‘two’ on the console.

20. What is the output of the following code?

tup = (1, 2, 4, 8)
tup = tup[1:-1]
tup = tup[0]
print(tup)
  • (2)
  • (2, )
  • 2
  • the snippet is erroneous
Explanation: Let’s analyze the code:

  • a tuple named tup with the following elements is defined: (1, 2, 4, 8)
  • the tuple tupis replaced with a shorter version of itself. The indices are [1:-1], which means it will start at position 1 to the second-last element of the tuple. The new tuple is (2, 4)
  • the tuple tup is again replaced with its first element only: tup[0], and the result is no longer a tuple,
  • the print function shows 2 on the console.

21. Select the true statements about the try-except block in relation to the following example. (Select two answers.)

try:
    # Some code is here...
except:
    # Some code is here...
  • If you suspect that a snippet may raise an exception, you should place it in the try block.
  • The code that follows the try statement will be executed if the code in the except clause runs into an error.
  • The code that follows the except statement will be executed if the code in the try clause runs into an error.
  • If there is a syntax error in code located in the try block, the except branch will not handle it, and a SyntaxError exception will be raised instead.
Explanation: If the code placed inside a try block raises an exception, the following code lines within the block will not be executed, and the exceptions defined below will try to handle the error generated.

22. What is the output of the following code?

try:
    value = input("Enter a value: ")
    print(value/value)
except ValueError:
    print("Bad input...")
except ZeroDivisionError:
    print("Very bad input...")
except TypeError:
    print("Very very bad input...")
except:
    print("Booo!")
  • Very bad input…
  • Very very bad input…
  • Booo!
  • Bad input…
Explanation: Let’s analyze the code:

  • the value variable will store whatever the user inputs as a string,
  • the print function will try to divide the value by itself,
  • since strings cannot be divided, a TypeError exception is raised,
  • the exception TypeError will be compared sequentially with the defined exceptions,
  • when it reaches except TypeError, the print function will show Very very bad input… on the console.

Leave a Reply

Your email address will not be published. Required fields are marked *