Python ITS-303 Test Exam V (with questions from all areas) – Results
Back to result overview
Attempt 1
All domains
- 57 all
- 0 correct
- 0 incorrect
- 57 skipped
- 0 marked
Collapse all questions
Question 1Skipped
Q541 – Modules
What is the expected output of the following code?
- import random
- print(random.seed(3))
The code is erroneous.
Explanation
The code is not erroneous; it is using the random.seed() function correctly. However, the output of print(random.seed(3)) will be None because the function does not return any value.
None of the above.
Explanation
The correct output of the code print(random.seed(3)) is None, so none of the above choices accurately reflect the expected output.
Correct answer
None
Explanation
The random.seed() function sets the seed for the random number generator, but it does not return any value. Therefore, the output of print(random.seed(3)) will be None.
3
Explanation
The random.seed() function does not return the seed value that was set. It simply initializes the random number generator with the provided seed value. Therefore, the output of print(random.seed(3)) will not be 3.
Overall explanation
Topics: import random.seed()
Try it yourself:
- import random
- print(random.seed(3)) # None
Explanation:
The seed() method is used to initialize the random number generator.
The random number generator needs a number (a seed value) to start with.
By default the random number generator uses the current system time.
You can use the seed() method to customize
the start number of the random number generator.
The seed() method has no defined return value and therefore it returns None
Q541 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 2Skipped
Q538 – Modules
Which of the following functions can be used to check if a file exists?
os.isFile()
Explanation
The os.isFile() function does not exist in the Python os module. This is an invalid function name and cannot be used to check if a file exists.
Correct answer
os.path.isfile()
Explanation
The os.path.isfile() function is used to check if a path is an existing regular file. It returns True if the path exists and is a file, otherwise it returns False. This function is specifically designed for checking the existence of files.
os.path.isFile()
Explanation
The os.path.isFile() function does not exist in the Python os module. This is an invalid function name and cannot be used to check if a file exists.
os.path.exists()
Explanation
The os.path.exists() function is used to check if a path exists, regardless of whether it is a file or directory. While it can be used to check the existence of files, it is not specifically designed to only check if a file exists like the os.path.isfile() function.
Overall explanation
Topic: os.path.isfile()
Try it yourself:
-
First execute the following to create the needed folder and file:
-
with open(‘data.txt’, ‘w’) as f:
-
f.write('Hello') -
import os
-
if not os.path.isdir(‘folder’):
-
os.mkdir('folder') -
import os
-
print(os.path.isfile(‘data.txt’)) # True
-
print(os.path.isfile(‘folder’)) # False
-
print(os.path.exists(‘data.txt’)) # True
-
print(os.path.exists(‘folder’)) # True
-
print(os.isfile(‘data.txt’)) # AttributeError: …
-
print(os.path.isFile(‘data.txt’)) # AttributeError: …
Explanation:
The isfile() method is the right choice here.
It checks whether the passed argument is a file.
The exists() method checks if something exists at a given path.
But that could still be a folder.
Python is case sensitive and therefore you have to
write isfile() with a lowercase f
Q538 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 3Skipped
Q554 – Error Handling
What is the expected output of the following code?
- try:
-
print("5" / 0) - except ArithmeticError:
-
print("arith") - except ZeroDivisionError:
-
print("zero") - except:
-
print("some")
Correct answer
some
Explanation
The code will raise a ZeroDivisionError when trying to divide by zero, which will be caught by the except ZeroDivisionError block. Therefore, the output will be "zero".
0
Explanation
The code will raise a ZeroDivisionError when trying to divide by zero, which will be caught by the except ZeroDivisionError block. Therefore, the output will be "zero".
zero
Explanation
The code will raise a ZeroDivisionError when trying to divide by zero, which will be caught by the except ZeroDivisionError block. Therefore, the output will be "zero".
arith
Explanation
The code will raise a ZeroDivisionError when trying to divide by zero, which will be caught by the except ZeroDivisionError block. Therefore, the output will be "zero".
Overall explanation
Topics: try except ArithmeticError ZeroDivisionError TypeError
Try it yourself:
-
try:
-
print("5" / 0) -
except ArithmeticError:
-
print("arith") -
except ZeroDivisionError:
-
print("zero") -
except:
-
print("some") # some -
print("5" / 0) # TypeError
Explanation:
To use the division operator with a string raises a TypeError
and therefore the broad except: branch is executed.
Q554 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 4Skipped
Q513 – Operators
What is the expected output of the following code?
x = 2
y = 6
x += 2 ** 3
x //= y // 2 // 3
print(x)
0
Explanation
This choice is incorrect because it does not accurately reflect the calculations performed in the code. The correct output is 10, not 0.
Correct answer
10
Explanation
The code first calculates 2 raised to the power of 3, which is 8. Then, it adds 8 to the current value of x (2), resulting in x being 10. Next, it performs integer division by calculating y divided by 2 and then dividing the result by 3. Since y is 6, y // 2 // 3 equals 1. Finally, x is divided by 1, resulting in x being 10.
11
Explanation
This choice is incorrect because it does not accurately reflect the calculations performed in the code. The correct output is 10, not 11.
9
Explanation
This choice is incorrect because it does not accurately reflect the calculations performed in the code. The correct output is 10, not 9.
Overall explanation
Topics: exponentiation operator floor division operator
add and assign operator floor-divide and assign operator
operator precedence
Try it yourself:
-
x = 2
-
y = 6
-
x += 2 ** 3
-
x //= y // 2 // 3
-
print(x) # 10
-
x += 2 ** 3
-
x = x + (2 ** 3)
-
print(2 + (2 ** 3)) # 10
-
print(2 + 8) # 10
-
print(10) # 10
-
x //= y // 2 // 3
-
x = x // (y // 2 // 3)
-
print(10 // (6 // 2 // 3)) # 10
-
print(10 // ((6 // 2) // 3)) # 10
-
print(10 // (3 // 3)) # 10
-
print(10 // 1) # 10
-
print(10) # 10
Explanation:
The exponentiation operator has a much higher precedence
than the add and assign operator
And the floor division operator has a higher precedence
than the floor-divide and assign operator
Q513 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 5Skipped
Q502 – Data Aggregates
What is the expected output of the following code?
- data1 = ‘1’, ‘2’
- data2 = (‘3’, ‘4’)
- print(data1 + data2)
Correct answer
('1', '2', '3', '4')
Explanation
The expected output of the code is a tuple that combines the elements of data1 and data2. Since data1 and data2 are tuples, the concatenation operation using the plus (+) operator will result in a new tuple with all the elements from both tuples, resulting in (‘1’, ‘2’, ‘3’, ‘4’).
['1', '2', '3', '4']
Explanation
This choice is incorrect because the output will not be a list. The original data1 and data2 variables are tuples, so the output will also be a tuple, not a list.
The code is erroneous.
Explanation
This choice is incorrect as the code is not erroneous. The code correctly combines two tuples using the plus operator to create a new tuple with all the elements from both original tuples.
(1, 2, 3, 4)
Explanation
This choice is incorrect because the output will not be a tuple with integer values (1, 2, 3, 4). The original data1 and data2 variables contain strings, so the output will be a tuple of strings, not integers.
Overall explanation
Topics: plus operator tuple concatenation
Try it yourself:
- data1 = ‘1’, ‘2’
- data2 = (‘3’, ‘4’)
- print(data1 + data2) # (‘1’, ‘2’, ‘3’, ‘4’)
Explanation:
You do not need the parentheses to create a tuple
The rest is normal tuple concatenation.
Q502 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 6Skipped
Q546 – Error Handling
The unnamed except block …
must be the first one.
Explanation
Placing the unnamed except block as the first one is not valid in Python. The interpreter will match exceptions in the order they are defined, so having the unnamed block first would prevent any named blocks from being able to catch specific exceptions before the generic one.
Correct answer
must be the last one.
Explanation
The unnamed except block must be the last one in the sequence of except blocks. This is because Python will match exceptions in the order they are defined, and having the unnamed block last ensures that it catches any exceptions that were not handled by the named blocks before it.
can be placed anywhere.
Explanation
The unnamed except block must be the last one in the sequence of except blocks. Placing it anywhere else may result in specific exceptions not being caught by the named blocks before it, leading to unexpected behavior in error handling.
cannot be used if any named block has been used.
Explanation
The unnamed except block can still be used even if named blocks have been defined. However, it must be placed as the last except block in the sequence to ensure that it catches any exceptions that were not handled by the named blocks.
Overall explanation
Topic: except SyntaxError
Try it yourself:
-
try:
-
# user_input = input('Please enter a number!') -
user_input = 'one' # Just for convenience -
# user_input = 1 -
num = 100 / int(user_input) -
except ValueError:
-
print('You need to use digits!') -
except:
-
print('Error') -
else:
-
print('Result:', num) -
"""
-
try:
-
# user_input = input('Please enter a number!') -
user_input = 'one' # Just for convenience -
num = 100 / int(user_input) -
except: # SyntaxError: default ‘except:’ must be last
-
print('Error') -
except ValueError:
-
print('You need to use digits!') -
else:
-
print('Result:', num) -
"""
Explanation:
The unnamed except block always needs to be
the last one of the except blocks,
otherwise you will receive a SyntaxError
Q546 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 7Skipped
Q556 – Modules
What is the expected result of the following code?
-
from datetime import timedelta
-
delta = timedelta(weeks=1, days=7, hours=11)
-
print(delta * 2)
7 days, 22:00:00
Explanation
This choice is incorrect because the expected result of the code is not 7 days and 22 hours. The timedelta object created in the code has a duration of 1 week, 7 days, and 11 hours, and when multiplied by 2, it results in 28 days and 22 hours, not 7 days and 22 hours.
Correct answer
28 days, 22:00:00
Explanation
The code imports the timedelta class from the datetime module and creates a timedelta object with a duration of 1 week, 7 days, and 11 hours. When this timedelta object is multiplied by 2, the result is 28 days and 22 hours, as timedelta objects support multiplication by integers to create a new timedelta object with the specified duration.
The code will raise an exception.
Explanation
This choice is incorrect because the code will not raise an exception. The code imports the timedelta class correctly and performs valid operations on timedelta objects, resulting in a timedelta object with a duration of 28 days and 22 hours when multiplied by 2.
2 weeks, 14 days, 22 hours
Explanation
This choice is incorrect because the expected result of the code is not 2 weeks, 14 days, and 22 hours. The timedelta object created in the code has a duration of 1 week, 7 days, and 11 hours, and when multiplied by 2, it results in 28 days and 22 hours, not 2 weeks, 14 days, and 22 hours.
Overall explanation
Topics: datetime timedelta
Try it yourself:
- from datetime import timedelta
- delta = timedelta(weeks=1, days=7, hours=11)
- print(delta * 2) # 28 days, 22:00:00
Explanation:
When you print a timedelta object
you always get the output with days and hours.
It is formatted like that.
Q556 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 8Skipped
Q537 – Operators
What is the expected output of the following code?
- x, y, z = 3, 2, 1
- z, y, x = x, y, z
- print(x, y, z)
2 1 3
Explanation
This choice is incorrect because the values of x, y, and z are swapped in the code. Therefore, the output will not be 2 1 3.
1 2 2
Explanation
This choice is incorrect because the values of x, y, and z are swapped in the code. Therefore, the output will not be 1 2 2.
3 2 1
Explanation
This choice is incorrect because the values of x, y, and z are swapped in the code. Therefore, the output will not be 3 2 1.
Correct answer
1 2 3
Explanation
The code assigns the values of x, y, and z to 3, 2, and 1 respectively. Then, it reassigns the values of z, y, and x to the values of x, y, and z respectively. Therefore, the output will be 1 2 3, as the values have been swapped.
Overall explanation
Topic: multiple assignments
Try it yourself:
- x, y, z = 3, 2, 1
- z, y, x = x, y, z # z, y, x = 3, 2, 1
- print(x, y, z) # 1, 2, 3
Explanation:
Multiple assignment
y stays the same.
x and z change their values.
Q537 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 9Skipped
Q551 – Error Handling
What is the expected output of the following code?
-
class Ex(Exception):
-
def __init__(self, msg): -
Exception.__init__(self, msg + msg) -
self.args = (msg,) -
try:
-
raise Ex('ex') -
except Ex as e:
-
print(e) -
except Exception as e:
-
print(e)
Correct answer
ex
Explanation
The code raises a custom exception Ex with the message ‘ex’. In the Ex class, the __init__ method initializes the exception with the message concatenated with itself. When the exception is caught as Ex and printed, it will output the original message ‘ex’.
The code is erroneous.
Explanation
The code is not erroneous. It defines a custom exception Ex, raises it with the message ‘ex’, and catches it to print the message. The code structure and exception handling are valid, so there is no error in the code.
An empty line.
Explanation
The code does not result in an empty line. It raises a custom exception Ex with the message ‘ex’ and catches it as Ex or Exception to print the message. Therefore, the output will not be an empty line.
exex
Explanation
The code raises a custom exception Ex with the message ‘ex’. In the Ex class, the __init__ method initializes the exception with the message concatenated with itself. However, when the exception is caught as Ex and printed, it will output the message ‘ex’ concatenated with itself, resulting in ‘exex’.
Overall explanation
Topics: try except raise Exception
class __init__() self
Try it yourself:
-
class Ex(Exception):
-
def __init__(self, msg): -
Exception.__init__(self, msg + msg) -
self.args = (msg,) -
try:
-
raise Ex('ex') -
except Ex as e:
-
print(e) # ex -
except Exception as e:
-
print(e)
Explanation:
Without the line:
self.args = (msg,)
the solution would be: exex
The __init__() method of the parent class Exception gets called with
msg + msg which is 'exex'
But the args variable of the object itself gets assigned (msg,)
which is the tuple ('ex',)
and that gets printed, when the object itself is printed.
Q551 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 10Skipped
Q503 – Data Aggregates
What is the expected output of the following code?
- data = ((1, 2),) * 7
- print(len(data[3:8]))
5
Explanation
The code correctly slices the tuple data from index 3 to index 8. However, since the slice does not include the element at index 8, the length of the slice is 4, not 5.
Correct answer
4
Explanation
The code creates a tuple data by repeating the tuple (1, 2) seven times. When slicing data[3:8], it selects elements from index 3 up to, but not including, index 8. Since indexing starts at 0, this slice includes elements at indices 3, 4, 5, and 6, resulting in a length of 4.
6
Explanation
The code slices the tuple data from index 3 to index 8, but the slice does not include the element at index 8. Therefore, the length of the slice is 4, not 6.
The code is erroneous.
Explanation
The code is not erroneous. It correctly creates a tuple data and slices it to find the length of a specific range of elements. The expected output is 4, as the slice includes elements at indices 3, 4, 5, and 6.
Overall explanation
Topics: multiply operator tuple concatenation tuple slicing len()
Try it yourself:
-
data = ((1, 2),) * 7
-
print(len(data[3:8])) # 4
-
print(data)
-
((1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2))
-
print(len(data[3:100])) # 4
Explanation:
There is only going to be seven elements.
Therefore 6 is going to be the highest index.
And so the slicing ends up with the indexes 3, 4, 5 ,6
which are four elements.
Q503 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 11Skipped
Q519 – Functions
What is the expected output of the following code?
-
x = 42
-
def func():
-
global x -
print('1. x:', x) -
x = 23 -
print('2. x:', x) -
func()
-
print(‘3. x:’, x)
-
- x: 42
-
- x: 23
-
- x: 42
Explanation
This choice is incorrect because the value of x is updated to 23 within the func() function using the global keyword. Therefore, the output will not be 42 for the third print statement outside the function.
None of the above.
Explanation
This choice is incorrect as the code provided will produce an output, and it is not the case that none of the above choices accurately represent the expected output of the code.
-
- x: 42
-
- x: 42
-
- x: 42
Explanation
This choice is incorrect because the value of x is updated to 23 within the func() function using the global keyword. Therefore, the output will not be 42 for the second print statement inside the function or the third print statement outside the function.
Correct answer
-
- x: 42
-
- x: 23
-
- x: 23
Explanation
The code defines a global variable x with a value of 42. Inside the func() function, the global keyword is used to modify the global variable x. The first print statement inside func() prints the value of x before the assignment, which is 42. Then, x is reassigned to 23, and the second print statement inside func() prints the updated value of x, which is 23. Finally, outside the func() function, the last print statement prints the current value of x, which is still 23.
Overall explanation
Topics: def global scope
Try it yourself:
-
x = 42
-
def func():
-
global x -
print('1. x:', x) -
x = 23 -
print('2. x:', x) -
func()
-
print(‘3. x:’, x)
-
"""
-
- x: 42
-
- x: 23
-
- x: 23
-
"""
Explanation:
The variable x existed in the outer scope before the function call.
The global keyword turns the variable x into a global variable.
From now on it exists in the outer scope and in the function scope.
Therefore the change inside the function effect x in the outer scope.
Q519 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 12Skipped
Q557 – Operators
What is the expected output of the following code?
print(2 ** 3 ** 2 ** 1)
64
Explanation
This choice is incorrect because the calculation does not result in 64. The correct calculation involves multiple exponentiation operations, leading to a different output.
Correct answer
512
Explanation
The code uses the exponentiation operator (**) in a chain of operations. The order of operations for exponentiation is from right to left. Therefore, the calculation starts with 2 ** 1, which equals 2. Then, 3 ** 2 is calculated, resulting in 9. Finally, 2 ** 9 is calculated, resulting in 512 as the output.
16.0
Explanation
This choice is incorrect because the output is not a floating-point number. The calculation involves only integers and results in an integer output.
16
Explanation
This choice is incorrect because the calculation does not result in 16. The correct calculation involves multiple exponentiation operations, leading to a different output.
The code is erroneous.
Explanation
This choice is incorrect because the code is not erroneous. It performs a series of exponentiation operations, and the output can be determined through correct evaluation of the operators.
128.0
Explanation
This choice is incorrect because the output is not 128. The correct calculation involves multiple exponentiation operations, resulting in a different output.
Overall explanation
Topics: exponentiation operator associativity of operators
Try it yourself:
- print(2 ** 3 ** 2 ** 1) # 512
- print(2 ** 3 ** (2 ** 1)) # 512
- print(2 ** 3 ** 2) # 512
- print(2 ** (3 ** 2)) # 512
- print(2 ** 9) # 512
- print(512) # 512
Explanation:
This question is about associativity of operators
Most operators have the associativity from left to right.
That means if you have two operators that are the same
or of the same group the left one is executed first.
The exponentiation operator has an associativity from right to left
therefore the right one is executed first.
Just picture the expression on a piece of paper with your handwriting
where you write each exponent a little bit higher than its base.
Naturally you have to start at the top to resolve the expression.
Q557 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 13Skipped
Q514 – Operators
What is the expected output of the following code?
-
nums = [3, 7, 23, 42]
-
alphas = [‘p’, ‘p’, ‘m’, ‘j’]
-
print(nums is alphas)
-
print(nums == alphas)
-
nums = alphas
-
print(nums is alphas)
-
print(nums == alphas)
-
False
-
True
-
True
-
True
Explanation
The ‘is’ operator in Python checks if two variables refer to the same object in memory. Since ‘nums’ and ‘alphas’ are two different lists, the ‘is’ operator will return False. The ‘==’ operator, on the other hand, checks if the values of the two lists are the same, which is not the case here, so it will return False. After assigning ‘alphas’ to ‘nums’, both variables point to the same list object in memory, so ‘nums is alphas’ will return True. Since both variables now refer to the same list object, ‘nums == alphas’ will also return True.
Correct answer
- False
- False
- True
- True
Explanation
The ‘is’ operator in Python checks if two variables refer to the same object in memory. Since ‘nums’ and ‘alphas’ are two different lists, the ‘is’ operator will return False. The ‘==’ operator, on the other hand, checks if the values of the two lists are the same, which is not the case here, so it will also return False. After assigning ‘alphas’ to ‘nums’, both variables point to the same list object in memory, so ‘nums is alphas’ will return True. Since both variables now refer to the same list object, ‘nums == alphas’ will also return True.
- False
- True
- False
- True
Explanation
The ‘is’ operator in Python checks if two variables refer to the same object in memory. Since ‘nums’ and ‘alphas’ are two different lists, the ‘is’ operator will return False. The ‘==’ operator, on the other hand, checks if the values of the two lists are the same, which is not the case here, so it will return True. After assigning ‘alphas’ to ‘nums’, both variables point to the same list object in memory, so ‘nums is alphas’ will return True. Since the values of the lists are the same, ‘nums == alphas’ will return True.
- True
- False
- True
- False
Explanation
The ‘is’ operator in Python checks if two variables refer to the same object in memory. Since ‘nums’ and ‘alphas’ are two different lists, the ‘is’ operator will return False. The ‘==’ operator, on the other hand, checks if the values of the two lists are the same, which is not the case here, so it will return False. After assigning ‘alphas’ to ‘nums’, both variables point to the same list object in memory, so ‘nums is alphas’ will return True. However, since the values of the lists are not the same, ‘nums == alphas’ will return False.
Overall explanation
Topics: list identity operators equal to operator
Try it yourself:
-
nums = [3, 7, 23, 42]
-
alphas = [‘p’, ‘p’, ‘m’, ‘j’]
-
print(nums is alphas) # False
-
print(nums == alphas) # False
-
print(id(nums)) # e.g. 140539383947452
-
print(id(alphas)) # e.g. 140539383900864 (a different number)
-
nums = alphas
-
print(nums is alphas) # True
-
print(nums == alphas) # True
-
print(nums) # [‘p’, ‘p’, ‘m’, ‘j’]
-
print(alphas) # [‘p’, ‘p’, ‘m’, ‘j’]
-
print(id(nums)) # e.g. 140539652049216
-
print(id(alphas)) # e.g. 140539652049216 (the same number)
Explanation:
A list is a mutable data type.
The second list is a different object.
Therefore the two lists do not have the same identity and different values.
Then alphas gets assigned to nums
That creates a reference to the same object.
From now on they have the same values and the same identity.
Q514 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 14Skipped
Q517 – Control Flow
Consider the following code.
- nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- x = 0
- while x < 10: # Line 3
-
print(nums(x)) # Line 4 -
if nums[x] = 7: # Line 5 -
break # Line 6 -
else: # Line 7 -
x += 1 # Line 8
You want to print the numbers 1 to 7 to the monitor.
But the code does not work.
What do you have to change?
Choose two.
x = x + 1 # Line 8
Explanation
The statement x += 1 is correct for incrementing the value of x by 1 in each iteration of the loop. This statement ensures that x is updated to move to the next element in the list nums, allowing the loop to progress correctly.
Correct selection
if nums[x] == 7: # Line 5
Explanation
In Python, the equality comparison operator is ==, not =. Using == in the if statement will correctly compare the value at index x in the nums list to 7, allowing the break statement to execute when the condition is met.
while (x < 10): # Line 3
Explanation
The while loop condition x < 10 is already correct and does not need to be changed. This condition ensures that the loop continues as long as x is less than 10, which is necessary for iterating through the list nums.
Correct selection
print(nums[x]) # Line 4
Explanation
The correct way to access elements in a list in Python is by using square brackets [], not parentheses (). Therefore, changing nums(x) to nums[x] will correctly access the elements in the list nums.
Overall explanation
Topics: while break if else list equal to operator
Try it yourself:
- nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- x = 0
- while x < 10: # Line 3
-
print(nums[x]) # Line 4 -
if nums[x] == 7: # Line 5 -
break # Line 6 -
else: # Line 7 -
x += 1 # Line 8
Explanation:
Line 3 and Line 8 work just fine.
Line 4 needs brackets for the list indexing.
Line 5 needs the equal to operator
Q517 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 15Skipped
Q544 – Error Handling
What is the expected output of the following code?
-
def func():
-
try: -
return 1 -
finally: -
return 2 -
res = func()
-
print(res)
Correct answer
2
Explanation
The code will output 2 because the finally block will always execute, regardless of whether an exception is raised or not. In this case, the return 2 statement in the finally block will override the return 1 statement in the try block.
1
Explanation
The code will not output 1 because the return 1 statement in the try block is overridden by the return 2 statement in the finally block. The finally block always executes, so the return 2 statement takes precedence.
The code is erroneous.
Explanation
The code is not erroneous; it will execute without any syntax errors. However, the output will be 2, not 1, due to the behavior of the finally block overriding the try block return statement.
None of the above.
Explanation
None of the above is the expected output because the code will output 2, not 1. The finally block always executes, and the return statement within it takes precedence over the return statement in the try block.
Overall explanation
Topics: try finally def
Try it yourself:
-
def func():
-
try: -
return 1 -
finally: -
return 2 -
res = func()
-
print(res) # 2
-
For comparison:
-
def func2():
-
try: -
print(1) # 1 -
finally: -
print(2) # 2 -
func2()
Explanation:
This question is a little tricky.
The return in the finally block will indeed be the one, that is executed.
For example with print() it is different.
The one in the try block will be executed before the one in the finally block.
Q544 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 16Skipped
Q510 – Operators
What is the expected output of the following code?
- x = 1
- print(++++x)
Correct answer
1
Explanation
The expression "++++x" can be interpreted as "++ + x", where the first two plus signs are the increment operator, and the third plus sign is the unary plus operator. The increment operator does not work in Python, so the expression simplifies to "+ + x", which is equivalent to "1" when x is 1.
3
Explanation
The expression "++++x" should be broken down as "++ + x" in Python. Since the increment operator "++" is not valid in Python, the expression simplifies to "+ + x", resulting in the output of 1 when x is 1, not 3.
2
Explanation
In Python, the increment operator "++" is not supported. Therefore, the expression "++++x" should be interpreted as "+ + + x", which is equivalent to "1" when x is 1. The output will be 1, not 2.
4
Explanation
The expression "++++x" should be understood as "++ + x" in Python. Since the increment operator "++" is not a valid syntax in Python, the expression simplifies to "+ + x", which evaluates to 1 when x is 1. Therefore, the expected output is 1, not 4.
Overall explanation
Topic: operators
Try it yourself:
-
x = 1
-
print(++++x) # 1
-
print(+1) # 1
-
print(++1) # 1
-
print(+++1) # 1
-
print(++++1) # 1
-
print(-1) # -1
-
print(–1) # 1
-
print(—1) # -1
-
print(—-1) # 1
Explanation:
First of all there is no increment operator ++ in Python.
You can add as many plus signs as you like, the number stays positive.
By the way, the minus sign works differently.
Two times minus is plus.
Q510 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 17Skipped
Q552 – Error Handling
Select the true statements.
Choose two.
You cannot define new exceptions as subclasses
derived from predefined exceptions.
Explanation
In Python, you can define new exceptions as subclasses derived from predefined exceptions. This allows you to create custom exceptions that inherit behavior and attributes from existing exception classes, providing more specific error handling capabilities in your code.
The finally branch of the try statement
may be executed if special conditions are met.
Explanation
The finally branch of the try statement is always executed, regardless of any special conditions. It is meant to be a block of code that is guaranteed to run, providing a way to clean up resources or perform final actions before exiting the try block.
Correct selection
The finally branch of the try statement is always executed.
Explanation
The finally branch of the try statement is always executed, regardless of whether an exception is raised or not. It is typically used to perform cleanup actions, such as closing files or releasing resources, ensuring that the code block in the finally section is executed no matter what.
Correct selection
The args property is a tuple designed to gather all
arguments passed to the class constructor.
Explanation
The args property is indeed a tuple that is designed to gather all arguments passed to the class constructor. It is commonly used in custom exception classes to store information about the exception.
Overall explanation
Topics: try finally args
Try it yourself:
-
try:
-
raise Exception('Hello', 'World') -
except Exception as err:
-
print(err.args) # ('Hello', 'World') -
def f(x):
-
try: -
res = 10 // x -
except ZeroDivisionError: -
print('You can not divide by zero!', end='') -
else: -
print('The result is', str(res) + '!', end='') -
finally: -
print(' Always finally!') -
f(0) # You can not divide by zero! Always finally!
-
f(2) # The result is 5! Always finally!
Explanation:
Yes, the args property is a tuple designed to gather all
arguments passed to the class constructor.
And absolutely, the finally branch of the try statement is always executed.
And you most definitely can define new exceptions
as subclasses derived from predefined exceptions:
https://www.programiz.com/python-programming/user-defined-exception
Q552 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 18Skipped
Q509 – Data Types
What is the expected output of the following code if the user enters 2 and 4?
- x = int(input())
- y = int(input())
- print(x + y)
Correct answer
6
Explanation
The code takes two integer inputs from the user, adds them together, and then prints the result. If the user enters 2 and 4, the sum of these two numbers is 6, so the expected output is 6.
2
Explanation
This choice is incorrect because it only represents one of the input values (2) and does not consider the addition operation that follows. The code adds the two input values together, so the output will be the sum of 2 and 4, which is 6.
4
Explanation
This choice is incorrect because it only represents one of the input values (4) and does not consider the addition operation that follows. The code adds the two input values together, so the output will be the sum of 2 and 4, which is 6.
24
Explanation
This choice is incorrect because it represents the concatenation of the two input values (2 and 4) as a single string, resulting in the output of 24. However, the code performs addition on the input values, not string concatenation, so the expected output is the sum of 2 and 4, which is 6.
Overall explanation
Topics: input() int() addition operator
Try it yourself:
-
x = int(input()) # Input: 2
-
y = int(input()) # Input: 4
-
x, y = int(‘2’), int(‘4’) # Just for convenience
-
print(x + y) # 6
-
print(int(‘2’) + int(‘4’)) # 6
-
print(2 + 4) # 6
Explanation:
input() return a string but the int() function casts them to an integer
And then the two integers get added to each other.
Q509 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 19Skipped
Q555 – Basics
ASCII is:
a character name
Explanation
ASCII is not a character name, but rather a character encoding standard that assigns numerical values to characters for communication and processing in computers. It is used to represent text and control characters in various systems.
a predefined Python variable name
Explanation
ASCII is not a predefined Python variable name. It is a character encoding standard that assigns numerical values to characters for communication and processing in computers. It is used to represent text and control characters in various systems.
a standard Python module name
Explanation
ASCII is not a standard Python module name. It is a character encoding standard that predates Python and is used to represent text and control characters in computer systems.
Correct answer
short for American Standard Code for Information Interchange
Explanation
ASCII stands for American Standard Code for Information Interchange, which is a character encoding standard used in computers and communication equipment to represent text and control characters. It is not a character name, Python module name, or predefined Python variable name.
Overall explanation
Topic: ASCII
Explanation:
Read about it here:
https://en.wikipedia.org/wiki/ASCII
Q555 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics
Question 20Skipped
Q547 – I/O
If x is a file opened in read mode, what will the following line do?
data = x.read(1)
Correct answer
Read 1 character from the file.
Explanation
This choice is correct because the read(1) method in Python reads and returns the specified number of characters from the file, in this case, 1 character.
Read 1 line from the file.
Explanation
This choice is incorrect because the read(1) method reads a specified number of characters, not lines, from the file.
Read 1 buffer from the file.
Explanation
This choice is incorrect because the read(1) method reads a specified number of characters, not buffers, from the file.
Read 1 kilobyte from the file.
Explanation
This choice is incorrect because the read(1) method reads a specified number of characters, not kilobytes, from the file.
Overall explanation
Topic: read()
Try it yourself:
-
First execute the following to create the needed file:
-
with open(‘index.txt’, ‘w’) as f:
-
f.write('Peter, Paul, Mary') -
x = open(‘index.txt’, ‘r’)
-
print(x.read(1)) # P
Explanation:
file.read([size])
The read() method has one optional parameter.
If it is given, that number of characters are read.
If it is not given, the whole file is read.
Q547 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 21Skipped
Q506 – Data Aggregates
What is the expected output of the following code?
- data = {‘Peter’: 30, ‘Paul’: 31}
- print(list(data.keys()))
['Peter': 30, 'Paul': 31]
Explanation
The syntax ['Peter': 30, 'Paul': 31] is incorrect for defining key-value pairs in Python. In dictionaries, key-value pairs are separated by commas and enclosed in curly braces. Additionally, the keys in a list should be strings, not key-value pairs. Therefore, this syntax is not valid for the expected output.
('Peter': 30, 'Paul': 31)
Explanation
The syntax ('Peter': 30, 'Paul': 31) is incorrect for defining key-value pairs in Python. In dictionaries, key-value pairs are separated by commas and enclosed in curly braces. Therefore, this syntax is not valid for the expected output.
Correct answer
['Peter', 'Paul']
Explanation
The code uses the keys() method on the dictionary data to retrieve a list of all the keys in the dictionary. Therefore, the expected output is a list containing the keys ‘Peter’ and ‘Paul’.
('Peter', 'Paul')
Explanation
The syntax ('Peter', 'Paul') represents a tuple, not a list. In this code, the keys() method returns a list, so the output should be enclosed in square brackets, not parentheses.
Overall explanation
Topics: dictionary list() keys()
Try it yourself:
- data = {‘Peter’: 30, ‘Paul’: 31}
- print(list(data.keys())) # [‘Peter’, ‘Paul’]
- print(data.keys()) # dict_keys([‘Peter’, ‘Paul’])
Explanation:
The key() method returns the keys() in a dict_keys object.
list() turns that into a list
Q506 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 22Skipped
Q526 – Data Aggregates
Which of the following sentences is true?
- str1 = ‘Peter’
- str2 = str1[:]
Correct answer
str1 and str2 are different names of the same string.
Explanation
This choice is correct because when the slice operator [:] is used without specifying any start or end index, it creates a shallow copy of the original string. Therefore, both str1 and str2 refer to the same string object in memory.
str2 is longer than str1
Explanation
This choice is incorrect because str1 and str2 are not different strings but rather different names referring to the same string ‘Peter’. Therefore, there is no difference in length between str1 and str2.
str1 and str2 are different (but equal) strings.
Explanation
This choice is incorrect because although str1 and str2 are different variables, they are referencing the same string object. Therefore, they are not different (but equal) strings; they are the same string.
str1 is longer than str2
Explanation
This choice is incorrect because both str1 and str2 are referring to the same string ‘Peter’. There is no difference in length between str1 and str2 as they are essentially the same string.
Overall explanation
Topics: string slicing
Try it yourself:
-
str1 = ‘Peter’
-
str2 = str1[:]
-
str2 = str1 # The same thing
-
print(id(str1)) # e.g. 140539652049216
-
print(id(str2)) # e.g. 140539652049216 (the same number than str1)
-
print(str1 is str2) # True
-
print(str1 == str2) # True
Explanation:
Copying with [:] only works with mutable data types like a list
A string is an immutable data type.
Whether you slice the whole thing or just assign it,
you always end up with a reference to the same object.
Q526 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 23Skipped
Q532 – Data Types
Consider the following Python code:
- name = ‘Peter’
- age = 23
- flag = True
What are the types of the variables name, age and flag?
Correct answer
str, int, bool
Explanation
The variable ‘name’ is assigned a string value ‘Peter’, so its type is ‘str’. The variable ‘age’ is assigned an integer value 23, so its type is ‘int’. The variable ‘flag’ is assigned a boolean value True, so its type is ‘bool’.
int, bool, char
Explanation
The variable ‘name’ is assigned a string value ‘Peter’, so its type is ‘str’. The variable ‘age’ is assigned an integer value 23, so its type is ‘int’. The variable ‘flag’ is assigned a boolean value True, so its type is ‘bool’.
float, bool, str
Explanation
The variable ‘name’ is assigned a string value ‘Peter’, so its type is ‘str’. The variable ‘age’ is assigned an integer value 23, so its type is ‘int’. The variable ‘flag’ is assigned a boolean value True, so its type is ‘bool’.
str, int, int
Explanation
The variable ‘name’ is assigned a string value ‘Peter’, so its type is ‘str’. The variable ‘age’ is assigned an integer value 23, so its type is ‘int’. The variable ‘flag’ is assigned a boolean value True, so its type is ‘bool’.
Overall explanation
Topics: integer float boolean string
Try it yourself:
- print(type(‘Peter’)) # <class ‘str’>
- print(type(23)) # <class ‘int’>
- print(type(True)) # <class ‘bool’>
Explanation:
Nothing complicated is going on here.
'Peter' is a string.
23 is an integer.
True is a boolean.
Q532 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 24Skipped
Q550 – Control Flow
You are developing a Python application
for an online product distribution company.
You need the program to iterate through a list of products
and escape when a target product ID is found.
-
productIdList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-
index = 0
-
??? index < 10:
-
print(productIdList[index]) -
if productIdList[index] == 6: -
??? -
else: -
index += 1
What would you insert instead of ??? and ???
- for
- break
Explanation
Using a ‘for’ loop in this context would not be suitable as the program needs to iterate through the list until a specific condition is met. The ‘break’ statement is necessary to exit the loop when the target product ID is found.
Correct answer
- while
- break
Explanation
Using a ‘while’ loop allows the program to iterate through the list of product IDs until a specific condition is met. The ‘break’ statement is used to exit the loop when the target product ID is found.
- while
- for
Explanation
Combining a ‘while’ loop with a ‘for’ loop in this scenario would not make sense as it would result in unnecessary complexity. The ‘break’ statement is needed to exit the loop when the target product ID is found.
- break
- while
Explanation
Using only the ‘break’ statement without a loop structure would not allow the program to iterate through the list of product IDs. A loop, such as a ‘while’ loop, is necessary for iteration, and the ‘break’ statement is used to exit the loop when the target product ID is found.
- for
- while
Explanation
Combining a ‘for’ loop with a ‘while’ loop in this context would not be the most efficient approach. The ‘break’ statement is crucial for exiting the loop when the target product ID is found.
- if
- break
Explanation
Using an ‘if’ statement here would not be appropriate as it does not provide a mechanism for iteration through the list. The ‘break’ statement is essential for exiting the loop when the target product ID is found.
Overall explanation
Topics: list while for break if else
equal to operator
Try it yourself:
-
productIdList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-
index = 0
-
while index < 10:
-
print(productIdList[index]) # 0 1 2 3 4 5 6 -
if productIdList[index] == 6: -
break -
else: -
index += 1
Explanation:
The while loop is the loop, that works with a condition.
The break keyword ends a loop.
Q550 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 25Skipped
Q549 – Control Flow
You are coding a math utility by using Python.
You are writing a function to compute roots.
The function must meet the following requirements:
If a is non-negative, return a ** (1 / b)
If a is negative and even, return 'Result is an imaginary number'
If a is negaitve and odd, return -(-a) ** (1 / b)
Which of the following functions meets the requirements?
- def safe_root(a, b):
-
if a >= 0: -
answer = -(-a) ** (1 / b) -
elif a % 2 == 0: -
answer = 'Result is an imaginary number' -
else: -
answer = a ** (1 / b) -
return answer
Explanation
This function does not meet the requirements as it incorrectly calculates the result for the case where ‘a’ is non-negative. It should return ‘a ** (1 / b)’ instead of ‘-(-a) ** (1 / b)’ when ‘a’ is non-negative.
Correct answer
- def safe_root(a, b):
-
if a >= 0: -
answer = a ** (1 / b) -
elif a % 2 == 0: -
answer = 'Result is an imaginary number' -
else: -
answer = -(-a) ** (1 / b) -
return answer
Explanation
This function correctly follows the requirements by first checking if ‘a’ is non-negative and returning the result of ‘a ** (1 / b)’. Then, it checks if ‘a’ is negative and even, returning ‘Result is an imaginary number’. Lastly, if ‘a’ is negative and odd, it returns ‘-(-a) ** (1 / b)’ as specified.
- def safe_root(a, b):
-
if a % 2 == 0: -
answer = -(-a) ** (1 / b) -
elif a >= 0: -
answer = 'Result is an imaginary number' -
else: -
answer = a ** (1 / b) -
return answer
Explanation
This function does not meet the requirements as it incorrectly checks if ‘a’ is even before checking if it is non-negative. Additionally, the calculation for the case where ‘a’ is negative and odd is incorrect, as it should return ‘-(-a) ** (1 / b)’ instead of ‘a ** (1 / b)’.
- def safe_root(a, b):
-
if a % 2 == 0: -
answer = a ** (1 / b) -
elif a >= 0: -
answer = 'Result is an imaginary number' -
else: -
answer = -(-a) ** (1 / b) -
return answer
Explanation
This function does not meet the requirements as it incorrectly checks if ‘a’ is even before checking if it is non-negative. This order of conditions results in the function not returning the correct output for the given requirements.
Overall explanation
Topics: if elif else def
modulus operator equal to operator
division operator exponentiation operator
Try it yourself:
-
def safe_root(a, b):
-
if a >= 0: -
answer = a ** (1 / b) -
elif a % 2 == 0: -
answer = 'Result is an imaginary number' -
else: -
answer = -(-a) ** (1 / b) -
return answer -
print(safe_root(9, 2)) # 3.0
-
print(safe_root(-9, 2)) # -3.0
-
print(safe_root(-16, 2)) # Result is an imaginary number
Explanation:
All the non-negative numbers will enter the if clause: a >= 0
Only negative numbers will remain.
The even numbers will enter the elif clause: a % 2 == 0
Only negative and odd numbers will remain.
Those will enter the else clause.
Q549 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 26Skipped
Q501 – Functions
A built‑in function is a function which …
is hidden from programmers.
Explanation
Built-in functions are not hidden from programmers; they are actually designed to be easily accessible and used by developers. They are openly documented and widely known within the Python community.
has been placed within your code by another programmer.
Explanation
Built-in functions are not functions that have been placed within your code by another programmer. They are predefined functions that are part of the Python language itself and are accessible to all Python developers.
Correct answer
comes with Python, and is an integral part of Python.
Explanation
Built-in functions are predefined functions that are included in Python by default. They are readily available for use without the need for any additional imports or installations, making them an integral part of the Python programming language.
has to be imported before use.
Explanation
Unlike regular functions or modules that need to be imported before use, built-in functions do not require any import statements. They are automatically available in the Python environment without the need for explicit imports.
Overall explanation
Topic: built‑in function
Try it yourself:
-
To print out the built-in functions:
-
for i in dir(builtins):
-
if i[0] != '_' and i[0].islower(): -
print(i, end=', ') -
"""
-
abs, all, any, ascii, bin, bool, breakpoint, bytearray, bytes,
-
callable, chr, classmethod, compile, complex, copyright,
-
credits, delattr, dict, dir, divmod, enumerate, eval, exec,
-
exit, filter, float, format, frozenset, getattr, globals,
-
hasattr, hash, help, hex, id, input, int, isinstance,
-
issubclass, iter, len, license, list, locals, map, max,
-
memoryview, min, next, object, oct, open, ord, pow, print,
-
property, quit, range, repr, reversed, round, set, setattr,
-
slice, sorted, staticmethod, str, sum, super, tuple, type,
-
vars, zip
-
"""
Explanation:
The build-in functions do not have to be imported,
they are not hidden from programmers
and not place in your code by another programmer.
The built-in functions come with Python as an integral part of the language.
Just look at the list above.
You will recognize most of them.
Q501 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 27Skipped
Q504 – Data Aggregates
What is the expected output of the following code?
- data = {‘name’: ‘Peter’, ‘age’: 30}
- person = data.copy()
- print(id(data) == id(person))
0
Explanation
This choice is incorrect as the expected output of the code is a comparison of memory addresses using id(), not a numerical value like 0.
True
Explanation
This choice is incorrect because the comparison of memory addresses using id() will result in False, as ‘data’ and ‘person’ are two separate objects in memory.
Correct answer
False
Explanation
The code creates a dictionary ‘data’ with key-value pairs and then creates a copy of ‘data’ called ‘person’. Since ‘person’ is a copy of ‘data’, they are two separate objects in memory, so the comparison of their memory addresses using id() will result in False.
1
Explanation
This choice is incorrect as the expected output of the code is a comparison of memory addresses using id(), not a numerical value like 1.
Overall explanation
Topics: dictionary copy() id() equal to operator
Try it yourself:
-
data = {‘name’: ‘Peter’, ‘age’: 30}
-
person = data.copy()
-
print(id(data) == id(person)) # False
-
person = data
-
print(id(data) == id(person)) # True
Explanation:
The copy() method creates a copy of the dictionary
If you just assign the dictionary a reference is created.
Q504 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 28Skipped
Q539 – Functions
Which of the following enclose the input parameters or arguments of a function?
Quotation marks
Explanation
Quotation marks are not used to enclose the input parameters or arguments of a function in Python. Quotation marks are used for defining strings in Python.
Brackets
Explanation
Brackets are not used to enclose the input parameters or arguments of a function in Python. Brackets are typically used for indexing and slicing operations on lists, tuples, and dictionaries.
Curly braces
Explanation
Curly braces are not used to enclose the input parameters or arguments of a function in Python. Curly braces are used for defining dictionaries and sets in Python.
Correct answer
Parentheses
Explanation
Parentheses are used to enclose the input parameters or arguments of a function in Python. This is the standard syntax for defining and calling functions in Python.
Overall explanation
Topics: def arguments parameters
Try it yourself:
-
Parantheses enclose the input parameters of a function definition:
-
def func(para1, para2):
-
return para1 + para2 -
Parantheses enclose the arguments of a function call:
-
print(func(3, 4)) # 7
-
Example for the uses of brackets:
-
print([1, 2, 3]) # [1, 2, 3]
-
Example for the uses of curly braces:
-
print({1, 2, 3}) # {1, 2, 3}
-
Example for the uses of quotation marks:
-
Double quotes:
-
print("Hello") # Hello
-
Single quotes:
-
print(‘Hello’) # Hello
Explanation:
Parantheses enclose the input parameters or arguments of a function.
Q539 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 29Skipped
Q542 – Basics
What is the expected output of the following code?
- x = ‘\’
- print(len(x))
1
Explanation
The code will not run successfully due to the syntax error caused by the backslash at the end of the string. Therefore, the output of the code cannot be determined, and it will not return a length value of 1.
2
Explanation
The code contains a syntax error with the backslash at the end of the string. As a result, the code will not execute properly, and the length of the string cannot be calculated as 2.
3
Explanation
The code provided is not valid in Python syntax due to the backslash at the end of the string. Therefore, the length of the string cannot be determined as 3.
Correct answer
The code is erroneous.
Explanation
The code is erroneous because the backslash character "\" is used to escape characters in Python. In this case, the backslash at the end of the string is not followed by another character to escape, which results in a syntax error.
Overall explanation
Topics: escaping len()
Try it yourself:
-
print(len(”)) # SyntaxError: …
- print(len(‘\’)) # 1
-
print(len(‘\’)) # SyntaxError: …
Explanation:
The backslash is the character to escape another character.
If you write '\' the backslash escapes
the ending single quote to a normal character.
It takes its syntactical meaning and the single quote becomes a normal character
and it looses its ability to end the string and therefore we get the syntax error.
If you write '\\' the one backslash escapes the other
and you end up with a string with one normal backslash.
If you write '\\\' you again have the same problem
than with one single backslash.
The first backslash escapes the second one,
but the third backslash escape the ending single quote,
the string does not get closed and you get a syntax error.
(There is another question about the same topic Q227.)
Q542 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics
Question 30Skipped
Q520 – Functions
What is the expected output of the following code?
-
def func(x):
-
if x % 2 == 0: -
return 1 -
else: -
return -
print(func(func(2)) + 1)
None
Explanation
The code will output None because the return statement in the else block of the func function does not specify a value to return when x is odd. This will result in a None value being returned, which is then added to 1 in the print statement.
Correct answer
The code is erroneous.
Explanation
The code is erroneous because the return statement in the else block of the func function does not specify a value to return when x is odd. This will result in a None value being returned, leading to an error when trying to add 1 to it in the print statement.
2
Explanation
The code will not output 2 because the return statement in the else block of the func function does not specify a value to return when x is odd. This will result in a None value being returned, which cannot be added to 1 in the print statement.
1
Explanation
The code will not output 1 because the return statement in the else block of the func function does not specify a value to return when x is odd. This will result in a None value being returned, which cannot be added to 1 in the print statement.
Overall explanation
Topics: def return None if else
modulus operator addition operator
Try it yourself:
-
def func(x):
-
if x % 2 == 0: -
return 1 -
else: -
return -
print(func(func(2)) + 1) # TypeError: …
Explanation:
The condition x % 2 == 0 tests for even numbers.
The first function call func(2) passes an even number
and the return value will be 1
The second function call will therefore pass an odd number func(1)
The return with no value will return None
And you can not calculate with None
(There is a similar question Q620.)
Q520 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 31Skipped
Q543 – Basics
You have the following file.
- index.py:
- from sys import argv
- print(argv[1] + argv[2])
You run the file by executing the following command in the terminal.
python index.py 42 3
What is the expected oputput?
45
Explanation
The output ’45’ would be incorrect because the script concatenates the command line arguments ’42’ and ‘3’, not adds them together.
126
Explanation
The output ‘126’ would be incorrect because the script concatenates the command line arguments ’42’ and ‘3’, not multiplies them.
424242
Explanation
The output ‘424242’ would be incorrect because the script concatenates the command line arguments ’42’ and ‘3’ without repeating them.
Correct answer
423
Explanation
The expected output is ‘423’ because the script takes the command line arguments ’42’ and ‘3’ and concatenates them together, resulting in ‘423’.
The code is erroneous.
Explanation
The code is not erroneous; it simply concatenates the command line arguments ’42’ and ‘3’ and prints the result, which is ‘423’.
Overall explanation
Topic: sys.argv plus operator string concatenation
Try it yourself:
-
First execute the following to create the needed file:
-
code = ”’
-
from sys import argv
-
print(argv[1] + argv[2])
-
”’
-
with open(‘index.py’, ‘w’) as f:
-
f.write(code) -
In Terminal:
-
python index.py 42 3
Explanation:
The indexes 1 and 2 are the right ones
(Remember the filename always is in index 0).
All the values in argv are going to be strings.
Therefore string concatenation will take place
and the result will be the string '423'
To test it you have to open the folder
where you created the index.py file in a terminal
and run the file by executing python index.py 42 3
Q543 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics
Question 32Skipped
Q525 – Control Flow
The following is a program to validate customer numbers.
- customer_number = input(‘Enter the employee number (dd-ddd-dddd): ‘)
- parts = customer_number.split(‘-‘)
- valid = False
- if len(parts) == 3:
- if len(parts[0]) == 2 and len(parts[1]) == 3 and len(parts[2]) == 4:
-
if parts[0].isdigit() and parts[1].isdigit() and parts[2].isdigit(): -
valid = True - print(valid)
The number may only contain numbers and dashes.
The number must have the right format (dd-ddd-dddd).
What is true about this programm?
There will be no error but there will be an unwanted result.
Explanation
The program will not produce an unwanted result if the input meets the specified criteria. It will accurately determine the validity of the customer number based on the format and content requirements.
There will be a SyntaxError.
Explanation
There are no syntax errors in the program. It follows the correct Python syntax and structure for input handling, string manipulation, and conditional statements.
Correct answer
The program works properly.
Explanation
The program correctly validates customer numbers by checking if the input follows the format dd-ddd-dddd, contains only numbers and dashes, and has the correct lengths for each part. If all conditions are met, the program sets the valid variable to True and prints it.
There will be an AttributeError.
Explanation
There are no attribute errors in the program. It correctly uses the split() method to separate the input into parts based on dashes and accesses the length and digit properties of the parts.
Overall explanation
Topics: input() split() boolean len() if
equal to operator list isdigit()
Try it yourself:
-
customer_number = input(‘Enter the employee number (dd-ddd-dddd): ‘)
-
customer_number = ’12-345-6789′ # True
-
customer_number = ‘12345-6789’ # False
-
customer_number = ‘A2-345-6789’ # False
-
customer_number = ‘112-345-6789’ # False
-
parts = customer_number.split(‘-‘)
-
valid = False
-
if len(parts) == 3:
-
if len(parts[0]) == 2 and len(parts[1]) == 3 and len(parts[2]) == 4:
-
if parts[0].isdigit() and parts[1].isdigit() and parts[2].isdigit(): -
valid = True -
print(valid)
-
You might have to scroll a little to the right to see everything
Explanation:
Everything works fine here.
The string with the number gets splitted into a list.
Then there are three conditions.
First if the list has three parts.
Second if all the parts have the right length.
Third if all the parts only contain digits.
Q525 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 33Skipped
Q530 – Basics
You create a function to calculate the power of a number by using Python.
You need to ensure that the function is documented with comments
You create the following code. Line numbers are included for reference only.
- 01 # The calc_power function calculates exponents
- 02 # x is the base
- 03 # y is the exponent
- 04 # The value of x raised to the y power is returned
- 05 def calc_power(x, y):
- 06 comment = "# Return the value"
- 07 return x ** y # raise x to the y power
Which of the following statements are true?
Choose two.
The pond sign (#) is optional for lines 02 and 03.
Explanation
The pound sign (#) is not optional for lines 02 and 03 in Python. It is used to indicate that the following text is a comment. Without the pound sign, Python will interpret the text as part of the code and may result in syntax errors.
The string in Line 06 will be interpreted as a comment.
Explanation
The string in Line 06 is not interpreted as a comment in Python. It is assigned to the variable ‘comment’ but is not used or referenced anywhere in the function. Python will not treat it as a comment and will not affect the execution of the function.
Correct selection
Line 07 contains an inline comment.
Explanation
Line 07 contains an inline comment that explains the purpose of the return statement. Inline comments are used to provide additional information about the code on the same line. In this case, it clarifies the operation being performed by the return statement.
Correct selection
Lines 01 through 04 will be ignored for syntax checking.
Explanation
Lines 01 through 04 are considered as comments and documentation strings (docstrings) in Python. They are not executable code and are meant for providing information about the function. Therefore, they will be ignored for syntax checking.
Overall explanation
Topics: def return (inline) comment exponentiation operator
Try it yourself:
-
The calc_power function calculates exponents
-
x is the base
-
y is the exponent
-
The value of x raised to the y power is returned
-
def calc_power(x, y):
-
comment = "# Return the value" -
# print(comment) # '# Return the value' -
return x ** y # raise x to the y power -
print(calc_power(2, 8)) # 256
Explanation:
This question is about how to use a comment right.
The first four lines are commented out and that needs to be that way.
Line 07 has an inline comment
and the comment inside of a string does not work as a comment
Q530 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics
Question 34Skipped
Q548 – I/O
Which of the following commands can be used to read the next line from a file?
read(n)
Explanation
The read(n) command is used to read a specified number of bytes from a file, not specifically the next line. It reads the file in a continuous stream, without distinguishing between lines.
readlines()
Explanation
The readlines() command is used to read all lines from a file and return them as a list of strings. It does not specifically read the next line from the file, but rather reads all lines at once.
Correct answer
readline()
Explanation
The readline() command is used to read the next line from a file. It reads the file line by line, allowing the user to process each line individually.
read()
Explanation
The read() command is used to read a specified number of bytes from a file, not specifically the next line. It reads the file in a continuous stream, without distinguishing between lines.
Overall explanation
Topics: read() readline() readlines()
Try it yourself:
-
First execute the following to create the needed file:
-
data = ”’Peter
-
Paul
-
Mary
-
”’
-
with open(‘data.txt’, ‘w’) as f:
-
f.write(data) -
file = open(‘data.txt’, ‘r’)
-
print(file.readline()) # Peter
-
print(file.readline()) # Paul
-
print(file.readline()) # Mary
-
print(‘———-‘)
-
file = open(‘data.txt’, ‘r’)
-
print(file.readline()) # Peter
-
print(file.readlines()) # [‘Paul\n’, ‘Mary\n’]
-
print(‘———-‘)
-
file = open(‘data.txt’, ‘r’)
-
print(file.readline()) # Peter
-
print(file.read()) # Paul Mary
-
print(‘———-‘)
-
n = 7
-
file = open(‘data.txt’, ‘r’)
-
print(file.readline()) # Peter
-
print(file.read(n)) # Paul Ma
Explanation:
The readline() method is exactly what you need here.
The read() method will read the rest of the file in one string.
The readlines() method will read the rest of the file and put every line in a list.
read(n) reads n characters from the file.
That could theoretically work, if you know the right number of characters,
but that is definitely not meant here.
Q548 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 35Skipped
Q535 – Control Flow
Consider the following code.
- data = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]
- res = 0
Which of the following code snippets will expand the code,
so that 100 will be printed to the monitor?
Choose two.
- for i in (‘Peter’, ‘Steve’, ‘Jane’):
-
if i not in data: -
res += 50 - print(res)
Explanation
This code snippet iterates over the elements in the tuple (‘Peter’, ‘Steve’, ‘Jane’). For each element, it checks if the element is not in the ‘data’ list. Since ‘Steve’ is not in the ‘data’ list, the ‘res’ variable will be incremented by 50. Finally, it prints the value of ‘res’, which will be 50 in this case.
Correct selection
- for i in (‘Peter’, ‘Steve’, ‘Jane’):
-
if i in data: -
res += 50 - print(res)
Explanation
This code snippet iterates over the elements in the tuple (‘Peter’, ‘Steve’, ‘Jane’). For each element, it checks if the element is in the ‘data’ list. Since ‘Peter’ and ‘Jane’ are in the ‘data’ list, the ‘res’ variable will be incremented by 50 for each of them. Finally, it prints the value of ‘res’, which will be 100 in this case.
- for i in (‘Peter’, ‘Steve’, ‘Jane’):
-
if i in data: -
res += 100 - print(res)
Explanation
This code snippet iterates over the elements in the tuple (‘Peter’, ‘Steve’, ‘Jane’). For each element, it checks if the element is in the ‘data’ list. Since ‘Peter’ and ‘Jane’ are in the ‘data’ list, the ‘res’ variable will be incremented by 100 for each of them. Finally, it prints the value of ‘res’, which will be 200 in this case.
Correct selection
- for i in (‘Peter’, ‘Steve’, ‘Jane’):
-
if i not in data: -
res += 100 - print(res)
Explanation
This code snippet iterates over the elements in the tuple (‘Peter’, ‘Steve’, ‘Jane’). For each element, it checks if the element is not in the ‘data’ list. Since ‘Steve’ is not in the ‘data’ list, the ‘res’ variable will be incremented by 100. Finally, it prints the value of ‘res’, which will be 100 in this case.
Overall explanation
Topics: list for if membership operator not
Try it yourself:
-
data = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]
-
res = 0
-
for i in (‘Peter’, ‘Steve’, ‘Jane’):
-
if i not in data: -
res += 100 -
print(res) # 100
-
———————-
-
res = 0
-
for i in (‘Peter’, ‘Steve’, ‘Jane’):
-
if i in data: -
res += 50 -
print(res) # 100
-
———————-
-
res = 0
-
for i in (‘Peter’, ‘Steve’, ‘Jane’):
-
if i in data: -
res += 100 -
print(res) # 200
-
———————-
-
res = 0
-
for i in (‘Peter’, ‘Steve’, ‘Jane’):
-
if i not in data: -
res += 50 -
print(res) # 50
Explanation:
Only Steve is not in data
Therefore we need the += 100 there.
Peter and Jane are both in data
Therefore we need the += 50 there.
Q535 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 36Skipped
Q534 – Operators
What is the data type of x, y, z after executing the following snippet?
- x = 23 + 42
- y = ’23’ + ’42’
- z = ’23’ * 7
x is int,
y and z are invalid declarations
Explanation
The expression 23 + 42 results in an integer value, so x is of type int. When concatenating two strings ’23’ and ’42’, the result is a new string ‘2342’, so y is of type str. Multiplying a string ’23’ by 7 is a valid operation in Python, resulting in ‘23232323232323’, so z is also of type str.
Correct answer
int, str, str
Explanation
The expression 23 + 42 results in an integer value, so x is of type int. When concatenating two strings ’23’ and ’42’, the result is a new string ‘2342’, so y is of type str. Multiplying a string ’23’ by 7 results in ‘23232323232323’, so z is also of type str.
int, str, int
Explanation
The expression 23 + 42 results in an integer value, so x is of type int. When concatenating two strings ’23’ and ’42’, the result is a new string ‘2342’, so y is of type str. However, multiplying a string ’23’ by 7 results in ‘23232323232323’, which is still a string, so z is also of type str, not int.
int, int, int
Explanation
The expression 23 + 42 results in an integer value, so x is of type int. When concatenating two strings ’23’ and ’42’, the result is a new string ‘2342’, so y is of type str. Multiplying a string ’23’ by 7 results in ‘23232323232323’, which is still a string, so z is also of type str, not int.
Overall explanation
Topics: addition operator plus operator string concatenation
multiply operator string concatenation
Try it yourself:
- print(type(23 + 42)) # <class ‘int’>
- print(type(’23’ + ’42’)) # <class ‘str’>
- print(type(’23’ * 7)) # <class ‘str’>
- print(23 + 42) # 65
- print(’23’ + ’42’) # 2342
- print(’23’ * 7) # 23232323232323
Explanation:
The first one is a normal addition.
The second one is a string concatenation by addition.
The third one is a string concatenation by multiplication.
Q534 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 37Skipped
Q540 – Modules
You need a list of seven numbers of random integer values
from 1 (inclusive) to 7 (inclusive).
Which of the following code snippets should you use?
- import random
- nums = random.randrange(1, 7)
Explanation
This code snippet imports the random module and attempts to generate a single random integer value between 1 and 7 using the randrange() function. It does not create a list of seven numbers as required in the question.
Correct answer
- import random
- nums = [random.randint(1, 7) for i in range(1, 8)]
Explanation
This code snippet correctly imports the random module and generates a list of seven random integer values between 1 and 7 (inclusive) using the randint() function within a list comprehension.
- import random
- nums = [random.randint(1, 8) for i in range(1, 8)]
Explanation
This code snippet imports the random module and generates a list of seven random integer values between 1 and 8 (inclusive) using the randint() function within a list comprehension. However, the range should be from 1 to 7 to meet the specified requirements.
- import random
- nums = random.randint(1, 7)
Explanation
This code snippet imports the random module and generates a single random integer value between 1 and 7 using the randint() function. It does not create a list of seven numbers as required in the question.
Overall explanation
Topics: import random.randint() random.randrange()
list comprehension
Try it yourself:
- import random
- print([random.randint(1, 7) for i in range(1, 8)])
-
e.g. [6, 3, 7, 5, 1, 4, 2]
- print([random.randint(1, 8) for i in range(1, 8)])
-
e.g. [6, 7, 3, 1, 8, 7, 8]
- print(random.randrange(1, 7)) # e.g. 6
- print(random.randint(1, 7)) # e.g. 7
Explanation:
You need a list comprehension here to get a whole list of numbers.
range(1, 8) works to get a list of seven elements,
because with range() the stop is exclusive.
That is different with randint()
With randint() the stop is inclusive.
That is why you need: randint(1, 7)
Q540 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 38Skipped
Q553 – I/O
The two basic, mutually exclusive, file open modes are named:
binary and ternary
Explanation
The choice binary and ternary is incorrect because ternary is not a file open mode in Python. The two basic, mutually exclusive file open modes in Python are binary and text. Ternary is not a standard file open mode in Python and is not used for reading or writing data in files.
text and image
Explanation
The choice text and image is incorrect because image is not a file open mode in Python. While text mode is used for reading and writing text data, image is not a standard file open mode. In Python, images are typically handled using specific libraries and modules designed for image processing, not as a file open mode.
Correct answer
binary and text
Explanation
The correct choice is binary and text because these are the two basic, mutually exclusive file open modes in Python. The binary mode is used for reading and writing binary data, while the text mode is used for reading and writing text data. These modes are essential for handling different types of data in files efficiently.
Overall explanation
Topic: open() and its modes
Try it yourself:
-
First you have to run this to create the files:
-
with open(‘alphabet.bin’, ‘wb’) as f:
-
f.write(bytes([65, 66, 67])) -
with open(‘alphabet.txt’, ‘wt’) as f:
-
f.write('ABC') -
with open(‘alphabet.bin’, ‘rb’) as f:
-
print(f.read()) # b'ABC' -
with open(‘alphabet.txt’, ‘rt’) as f:
-
print(f.read()) # ABC
Explanation:
You have to decide, whether you use binary or text mode:
https://www.w3schools.com/python/ref_func_open.asp
Q553 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 39Skipped
Q522 – Functions
What is the expected output of the following code?
-
def func(x=2, y=3):
-
return x * y -
print(func(y=2))
The code is erroneous.
Explanation
This choice is incorrect because the code is not erroneous. The function func is defined correctly, and when called with y=2, it will return the correct output.
Correct answer
4
Explanation
The function func takes two parameters, x and y, with default values of 2 and 3, respectively. When calling the function func with y=2, it overrides the default value of y with 2. The function then returns the product of x and y, which is 2 * 2 = 4.
2
Explanation
This choice is incorrect because it does not consider the parameter y being passed as 2 when calling the function func. The function will return the product of the passed value of y (2) and the default value of x (2), resulting in 2 * 2 = 4.
6
Explanation
This choice is incorrect because it does not consider the parameter y being passed as 2 when calling the function func. The function will return the product of the passed value of y (2) and the default value of x (2), resulting in 2 * 2 = 4.
Overall explanation
Topics: def default parameter
Try it yourself:
-
def func(x=2, y=3):
-
return x * y -
print(func(y=2)) # 4
Explanation:
This is an easy question.
It is good to be able to detect that.
There is not always a hidden complexity.
Click the right answer and move on.
Q522 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 40Skipped
Q529 – Control Flow
What is the expected output of the following code?
-
data = [1, 2, [3, 4], [5, 6], 7, [8, 9]]
-
count = 0
-
for i in range(len(data)):
-
if type(data[i]) == list: -
count += 1 -
print(count)
9
Explanation
This choice is incorrect because it does not consider the condition in the code that increments the ‘count’ variable only when the element is a list. It does not represent the total number of elements in the ‘data’ list.
The code is erroneous.
Explanation
This choice is incorrect as the code is not erroneous. It correctly counts the number of elements that are lists in the ‘data’ list and prints the count at the end.
6
Explanation
This choice is incorrect because the ‘count’ variable is only incremented when the element in the ‘data’ list is a list. It does not count the total number of elements in the ‘data’ list.
Correct answer
3
Explanation
The code iterates through the elements of the ‘data’ list and checks if each element is a list. If the element is a list, the ‘count’ variable is incremented by 1. In this case, there are 3 elements in the ‘data’ list that are lists, so the final output will be 3.
Overall explanation
Topics: list for range() len() if type() equal to operator
Try it yourself:
-
data = [1, 2, [3, 4], [5, 6], 7, [8, 9]]
-
count = 0
-
for i in range(len(data)):
-
if type(data[i]) == list: -
count += 1 -
print(count) # 3
Explanation:
The snippet checks every element of the list, if it itself is a list
and counts the occurrences.
There are three lists inside of the list data: [3, 4], [5, 6] and [8, 9]
Q529 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 41Skipped
Q531 – I/O
The following line of code …
for line in open('data.txt', 'r'):
Correct answer
is valid as open returns an iterable object.
Explanation
This choice is correct because the open() function in Python returns a file object, which is an iterable object. Therefore, the code snippet is valid as it iterates over each line in the ‘data.txt’ file.
may be valid if line is a list.
Explanation
This choice is incorrect because the open() function returns a file object, not a list. Therefore, the code snippet is valid regardless of the data type of the variable ‘line’.
is invalid as open returns a non-iterable object.
Explanation
This choice is incorrect because the open() function in Python returns a file object, which is an iterable object. Therefore, the code snippet is valid and can iterate over each line in the ‘data.txt’ file.
is invalid as open returns nothing.
Explanation
This choice is incorrect because the open() function in Python returns a file object, not nothing. Therefore, the code snippet is valid as it iterates over the lines in the ‘data.txt’ file.
Overall explanation
Topics: open() for
Try it yourself:
-
First execute the following to create the needed file:
-
text = ”’Peter
-
Paul
-
Mary
-
”’
-
with open(‘data.txt’, ‘w’) as f:
-
f.write(text) -
for line in open(‘data.txt’, ‘r’):
-
print(line) -
"""
-
Peter
-
Paul
-
Mary
-
"""
-
print(type(open(‘data.txt’, ‘r’))) # <class ‘_io.TextIOWrapper’>
-
print(hasattr(open(‘data.txt’, ‘r’), ‘iter‘)) # True
Explanation:
The open() function returns an iterable object.
Therefore it can be iterated by the for loop.
Every iteration will return one line.
Q531 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 42Skipped
Q527 – Data Types
You want to write a programm that asks the user for a value.
For the rest of the programm you need a whole number,
even if the user enters a decimal value.
What would you have to write?
num = int('How many do you need?')
Explanation
This choice tries to convert the string ‘How many do you need?’ to an integer, which will result in an error. It does not handle user input or convert it to a whole number as required.
Correct answer
num = int(float(input('How many do you need?')))
Explanation
This choice first converts the user input to a float using the float() function, then converts it to an integer using the int() function. This way, even if the user enters a decimal value, the final num variable will be a whole number.
num = float(input('How many do you need?'))
Explanation
This choice directly takes the user input as a float, which means the num variable will store the decimal value entered by the user. It does not ensure that the num variable will be a whole number as required.
num = str(input('How many do you need?'))
Explanation
This choice takes the user input as a string, which means the num variable will store the input as a string. It does not convert the input to a whole number as required.
Overall explanation
Topics: input() float() int() str()
Try it yourself:
-
num = int(float(input(‘How many do you need?’)))
-
num = int(float(‘7.3’))
-
print(num) # 7
-
print(float(‘7.3’)) # 7.3
-
print(str(‘7.3’)) # ‘7.3’
-
print(int(‘7.3’)) # ValueError …
Explanation:
The input() function returns a string and in the end you need an integer
You can not use int() directly,
because you would get a ValueError if the user enters a decimal value.
Therefore you have to cast the input string to a float and then to an integer
Q527 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 43Skipped
Q515 – Operators
What would you insert instead of ???
so that the program prints True to the monitor?
- x = ‘Peter’
- y = ‘Peter’
- res = ???
- print(res)
x != y
Explanation
The ‘!=’ operator is used to check if two objects are not equal. Since x and y are assigned the same string value ‘Peter’, the expression ‘x != y’ will evaluate to False, not True as required by the question.
Correct answer
x is y
Explanation
The ‘is’ operator in Python is used to compare the memory addresses of two objects. In this case, since both x and y are assigned the same string value ‘Peter’, they will refer to the same memory address, making the expression ‘x is y’ evaluate to True.
x is not y
Explanation
The ‘is not’ operator is the negation of the ‘is’ operator and checks if two objects do not have the same memory address. In this case, since x and y are assigned the same string value ‘Peter’, the expression ‘x is not y’ will evaluate to False, not True as required by the question.
x < y
Explanation
The ‘<‘ operator is used for comparing the values of two objects. In this case, comparing two strings using the ‘<‘ operator will result in a False value, as ‘Peter’ is not less than ‘Peter’ in a string comparison.
Overall explanation
Topics: identity operator less than operator
not equal to operator not
Try it yourself:
-
x = ‘Peter’
-
y = ‘Peter’
-
res = x is y # True
-
print(res)
-
print(x < y) # False
-
print(x != y) # False
-
print(x is not y) # False
-
print(id(x)) # e.g. 140539652049216
-
print(id(y)) # e.g. 140539652049216 (the same number)
Explanation:
A string is an immutable data type.
If you create a second string of the same value,
Python will created a reference to the same object.
Therefore those two strings will have the same identity.
Q515 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 44Skipped
Q528 – Basics
You have the following file.
- index.py:
- from sys import argv
- sum = 0
- for i in range(2, len(argv)):
-
sum += float(argv[i]) - print(
-
"The average score for {0} is {1:.2f}" -
.format(argv[1], sum/(len(argv)-2)) - )
You want the following output.
The average score for Peter is 200.00
Which command do you have to execute in the command line?
python index.py Peter 100
Explanation
This choice is incorrect because it provides only one numerical value as an argument after the name argument. The script requires at least three numerical values after the name argument to calculate the average score, but this choice only provides one numerical value.
The code is erroneous.
Explanation
This choice is incorrect because the code is not erroneous. The script is written correctly to calculate the average score based on the provided arguments. The issue lies in the input provided when executing the script, not in the script itself.
Correct answer
python index.py Peter 100 200 300
Explanation
This choice is correct because it provides the necessary arguments for the script to run successfully. The script expects the first argument to be the name (Peter in this case) and the following arguments to be numerical values to calculate the average score. In this case, the average score will be calculated as (100 + 200 + 300) / 3 = 200, which matches the desired output.
python index.py Peter 100 200
Explanation
This choice is incorrect because it does not provide enough numerical values as arguments for the script to calculate the average score. The script requires at least three numerical values after the name argument to calculate the average score, but this choice only provides two numerical values.
Overall explanation
Topics: sys.argv for range() format() len()
Try it yourself:
-
First execute the following to create the needed file:
-
code = ”’
-
from sys import argv
-
sum = 0
-
for i in range(2, len(argv)):
-
sum += float(argv[i]) -
print(
-
"The average score for {0} is {1:.2f}" -
.format(argv[1], sum/(len(argv)-2)) -
)
-
”’
-
with open(‘index.py’, ‘w’) as f:
-
f.write(code) -
In Terminal:
-
python index.py Peter 100 200 300
Explanation:
range() starts at 2 because in index 0 always is the filename
and in index 1 will be the name Peter
format() is used here with numbered indexes.
The name 'Peter' from argv[1] will go to {0}
and the average will go to {1}
The numbered index {1} is also formated by {1:.2f}
with is responsible for the two fix point number format: 200.00
To test it, you have to open the folder
where you created the index.py file in a terminal
and run the file by executing python index.py Peter 100 200 300
Q528 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics
Question 45Skipped
Q536 – I/O
You want to be able to read and write data to a file.
The file needs to be automatically created, if it doesn’t exist.
If the file does already exist, you want to override the existing content.
Which of the following commands do you have to choose?
Correct answer
open('data.txt', 'w+')
Explanation
The ‘w+’ mode in the open() function allows you to read and write to a file. If the file does not exist, it will be automatically created. If the file already exists, the existing content will be overridden, making it the correct choice for the given requirements.
open('data.txt', 'r')
Explanation
The ‘r’ mode in the open() function only allows you to read from a file. It does not provide the functionality to write to the file or automatically create it if it doesn’t exist. Therefore, it is not the correct choice for the given requirements.
open('data.txt', 'r+')
Explanation
The ‘r+’ mode in the open() function allows you to read and write to a file, but it does not automatically create the file if it doesn’t exist. Additionally, it does not override the existing content by default, so it is not the best choice for the specified requirements.
open('data.txt', 'w')
Explanation
The ‘w’ mode in the open() function allows you to write to a file, but it does not provide the functionality to read from the file. While it can automatically create the file if it doesn’t exist, it does not meet the requirement of overriding the existing content. Therefore, it is not the correct choice for the given scenario.
Overall explanation
Topic: open() and its modes
Try it yourself:
-
This works:
-
file = open(‘data.txt’, ‘w+’)
-
file.write(‘Hello’)
-
file.seek(0)
-
data = file.read()
-
print(data) # Hello
-
file.close()
-
This would not create the not existing file:
-
To test it, delete the file before running it.
-
open(‘data.txt’, ‘r+’) # FileNotFoundError: …
-
"""
-
This only opens for reading:
-
file = open(‘data.txt’, ‘r’)
-
file.write(‘Hello’) # io.UnsupportedOperation: not writable
-
"""
-
"""
-
This only opens for writing:
-
file = open(‘data.txt’, ‘w’)
-
file.write(‘Hello’)
-
file.seek(0)
-
data = file.read() # io.UnsupportedOperation: not readable
-
"""
Explanation:
You need the plus sign + to have reading and writing.
But only w+ creates the not existing file.
Q536 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 46Skipped
Q508 – Data Aggregates
What is the expected output of the following code?
- data = (1, 2, 4, 8)
- data = data[-2:-1]
- data = data[-1]
- print(data)
(4)
Explanation
This choice is incorrect because the parentheses around the number 4 do not affect the output. The value assigned to the variable ‘data’ is an integer, not a tuple. The code directly assigns the integer 4 to the variable ‘data’ and prints it without any additional formatting.
(4,)
Explanation
This choice is incorrect because the code does not create a tuple with a single element. The value assigned to the variable ‘data’ is an integer, not a tuple. The code directly assigns the integer 4 to the variable ‘data’ and prints it without any additional formatting.
44
Explanation
This choice is incorrect because the code does not perform any operations that would result in the value being duplicated or concatenated. The code simply extracts and assigns specific elements from the tuple ‘data’ and prints the final value, which is 4.
Correct answer
4
Explanation
The code first assigns a new tuple containing elements from index -2 (inclusive) to index -1 (exclusive) to the variable ‘data’. This results in a tuple with a single element, which is 4. Then, the code assigns this single element to the variable ‘data’. Finally, the code prints the value of ‘data’, which is 4.
Overall explanation
Topics: tuple slicing tuple indexing
Try it yourself:
- data = (1, 2, 4, 8)
- data = data[-2:-1]
- print(data) # (4,)
- data = data[-1]
- print(data) # 4
Explanation:
The slicing start is -2 the second last element.
Here is the value 4
The slicing end is -1 the last element, which is exclusive.
That leaves the value 4 in the tuple
The indexing -1 also takes the last element, the value 4
(which is the only element)
Q508 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 47Skipped
Q545 – Error Handling
What is the expected output of the following code?
- try:
-
raise Exception - except BaseException:
-
print('1', end='') - else:
-
print('2', end='') - finally:
-
print('3', end='')
1
Explanation
The code will raise an exception of type Exception, which is a subclass of BaseException. The except block will catch the exception, and ‘1’ will be printed. Since there is no else block, ‘2’ will not be printed. Finally, the finally block will always execute, and ‘3’ will be printed. Therefore, the output is ’13’.
23
Explanation
The code will raise an exception of type Exception, which is a subclass of BaseException. The except block will catch the exception, and ‘1’ will be printed. Since there is no else block, ‘2’ will not be printed. The finally block will always execute, and ‘3’ will be printed. Therefore, the output is ’13’.
Correct answer
13
Explanation
The code will raise an exception of type Exception, which is a subclass of BaseException. The except block will catch the exception, and ‘1’ will be printed. Then, the finally block will always execute, regardless of whether an exception was caught or not, and ‘3’ will be printed. Therefore, the expected output is ’13’.
12
Explanation
The code will raise an exception of type Exception, which is a subclass of BaseException. The except block will catch the exception, and ‘1’ will be printed. Since there is no else block, ‘2’ will not be printed. The finally block will always execute, and ‘3’ will be printed. Therefore, the output is ’13’.
Overall explanation
Topics: try except else finally Exception BaseException
Try it yourself:
-
try:
-
raise Exception -
except BaseException:
-
print('1', end='') # 1 -
else:
-
print('2', end='') -
finally:
-
print('3', end='') # 3 -
print(issubclass(Exception, BaseException)) # True
Explanation:
BaseException is the top-most Exception in Python.
Therefore Exception (like any other exception class)
is a subclass of BaseException.
And that is why the except BaseException block is executed.
If an except block is executed, the else block is not executed.
The finally block is always executed.
Q545 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 48Skipped
Q523 – Data Types
How many arguments can the print() function take?
Just one argument.
Explanation
While the print() function can take just one argument, it is not limited to only one argument. Python allows for multiple arguments to be passed to the print() function, making it versatile for various printing needs.
Any number of arguments (excluding zero).
Explanation
The print() function in Python can take any number of arguments, excluding zero. This means that while it can print multiple values and expressions, at least one argument must be provided for the function to execute successfully.
Not more than seven arguments.
Explanation
The print() function in Python is not limited to a specific number of arguments, such as seven. It can take any number of arguments, making it suitable for printing a wide range of values and expressions.
Correct answer
Any number of arguments (including zero).
Explanation
The print() function in Python can take any number of arguments, including zero. This flexibility allows for printing multiple values, strings, variables, and expressions in a single function call.
Overall explanation
Topics: print()
Try it yourself:
- print(1) # 1
- print() # An empty line
- print(1, 2, 3, 4, 5, 6, 7, 8, 11) # 1 2 3 4 5 6 7 8 11
Explanation:
The print() function called without an argument will print an empty line.
The amount of possible arguments depends on the capacities of your computer
but it is going to be more than you will ever need.
Q523 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 49Skipped
Q524 – Control Flow
How many stars will the following snippet print to the monitor?
- for i in range(1):
-
print('*') - else:
-
print('*')
Correct answer
two
Explanation
The snippet will print two stars to the monitor because the loop will iterate once, printing one star, and then the ‘else’ block will execute, printing another star.
three
Explanation
The snippet will not print three stars to the monitor because the loop will iterate once, printing one star, and then the ‘else’ block will execute, printing another star.
zero
Explanation
The snippet will not print zero stars to the monitor because the loop will iterate once, printing one star, and then the ‘else’ block will execute, printing another star.
one
Explanation
The snippet will not print one star to the monitor because the loop will iterate once, printing one star, and then the ‘else’ block will execute, printing another star.
Overall explanation
Topics: for else (nobreak)
Try it yourself:
- for i in range(1):
-
print('i:', 1) # 1 -
print('*') # * - else:
-
print('*') # *
Explanation:
There will be just one iteration.
But because there is no break inside the for loop,
the else clause will execute and the second star will be printed.
Q524 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 50Skipped
Q505 – Data Aggregates
What is the expected output of the following code?
- data = [1, 2, 3, None, (), [], ]
- print(len(data))
3
Explanation
This choice is incorrect because the len() function counts all items in the list, including None, empty tuple, and empty list. Therefore, the output of the code will not be 3.
4
Explanation
This choice is incorrect because the len() function counts all items in the list, including None, empty tuple, and empty list. Therefore, the output of the code will not be 4.
5
Explanation
This choice is incorrect because the len() function counts all items in the list, including None, empty tuple, and empty list. Therefore, the output of the code will not be 5.
The code is erroneous.
Explanation
This choice is incorrect because the code is not erroneous. It creates a list and prints the length of the list, which is a valid operation in Python. The expected output can be determined by counting the items in the list.
Correct answer
6
Explanation
The code creates a list ‘data’ containing integers, None, an empty tuple, and an empty list. The len() function in Python returns the number of items in a container, so the output will be 6, as there are 6 items in the ‘data’ list.
Overall explanation
Topics: list len()
Try it yourself:
- data = [1, 2, 3, None, (), [], ]
- print(len(data)) # 6
Explanation:
An empty element is still an element.
That makes it six.
The trailing comma just gets ignored.
Q505 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 51Skipped
Q518 – Functions
What is the expected output of the following code?
-
def func(data):
-
data = [7, 23, 42] -
print('Function scope: ', data) -
data = [‘Peter’, ‘Paul’, ‘Mary’]
-
func(data)
-
print(‘Outer scope: ‘, data)
-
Function scope: [7, 23, 42]
-
Outer scope: [7, 23, 42]
Explanation
The function func assigns a new list [7, 23, 42] to the data variable within the function scope and prints it. However, this change is only within the function scope and does not affect the data variable in the outer scope, which remains as ['Peter', 'Paul', 'Mary'].
None of the above.
Explanation
None of the above choices are correct as the correct output is Function scope: [7, 23, 42] Outer scope: [‘Peter’, ‘Paul’, ‘Mary’].
- Function scope: [‘Peter’, ‘Paul’, ‘Mary’]
- Outer scope: [‘Peter’, ‘Paul’, ‘Mary’]
Explanation
The function func assigns a new list [7, 23, 42] to the data variable within the function scope and prints it. This change is only within the function scope and does not affect the data variable in the outer scope, which remains as ['Peter', 'Paul', 'Mary'].
Correct answer
- Function scope: [7, 23, 42]
- Outer scope: [‘Peter’, ‘Paul’, ‘Mary’]
Explanation
The function func takes a parameter data, assigns a new list [7, 23, 42] to the data variable within the function scope, and prints it. This change is only within the function scope and does not affect the data variable in the outer scope, which remains as ['Peter', 'Paul', 'Mary'].
Overall explanation
Topics: def list scope
Try it yourself:
-
def func(data):
-
data = [7, 23, 42] -
print('Function scope: ', data) # [7, 23, 42] -
data = [‘Peter’, ‘Paul’, ‘Mary’]
-
func(data)
-
print(‘Outer scope: ‘, data) # [‘Peter’, ‘Paul’, ‘Mary’]
Explanation:
The parameter data will become a new entity with the function as its scope.
The variable data in the outer scope is a different entity.
Q518 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 52Skipped
Q512 – Operators
What is the expected output of the following code?
print(3 * 'abc' + 'xyz')
3abcxyz
Explanation
This choice does not accurately reflect the concatenation and multiplication operations happening in the code snippet. It does not represent the correct output of the given code.
abcabcxyzxyz
Explanation
This choice incorrectly combines the repeated ‘abc’ string and the ‘xyz’ string in an incorrect order. It does not accurately represent the expected output of the code snippet.
Correct answer
abcabcabcxyz
Explanation
The code snippet multiplies the string ‘abc’ by 3, resulting in ‘abcabcabc’, and then concatenates ‘xyz’ to the end. Therefore, the expected output is ‘abcabcabcxyz’.
abcxyzabcxyzabcxyz
Explanation
This choice incorrectly repeats the ‘abc’ and ‘xyz’ strings in an alternating pattern, which is not the expected output of the given code snippet. It does not accurately represent the concatenation operation in the code.
Overall explanation
Topics: multiply operator string concatenation
plus operator string concatenation operator precedence
Try it yourself:
- print(3 * ‘abc’ + ‘xyz’) # abcabcabcxyz
- print((3 * ‘abc’) + ‘xyz’) # abcabcabcxyz
- print(‘abcabcabc’ + ‘xyz’) # abcabcabcxyz
- print(‘abcabcabcxyz’) # abcabcabcxyz
Explanation:
Only string concatenation is taking place here.
Still you have the usual operator precedence
Multiplication comes before addition.
Q512 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 53Skipped
Q521 – Functions
What is the expected output of the following code?
-
def func(x, y):
-
if x == y: -
return x -
else: -
return -
func(x, y=1)
-
print(func(0, 3))
1
Explanation
The function func will return None when called with arguments 0 and 3 because the condition if x == y is not satisfied. The output will not be 1.
0
Explanation
The code will not reach the return x statement in the function func because the condition if x == y is not satisfied when calling func(0, 3). Therefore, the function will return None, and the output will not be 0.
Correct answer
The code is erroneous.
Explanation
The code is erroneous because the function func is defined with parameters x and y, but when calling the function func(x, y=1), the variable x is not defined. This will result in a NameError as x is not defined in the function call.
3
Explanation
The function func will return None when called with arguments 0 and 3 because the condition if x == y is not satisfied. The output will not be 3.
Overall explanation
Topics: def argument if else equal to operator NameError
Try it yourself:
-
def func(x, y):
-
if x == y: -
return x -
else: -
return -
func(x, y=1) # NameError: name ‘x’ is not defined
-
print(func(0, 3))
Explanation:
The argument x is not defined.
There is a possibility to save time here.
Once you see the error, click the corresponding answer and move on.
Q521 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 54Skipped
Q533 – Data Types
You want to print the sum of two number.
What snippet would you insert in the line indicated below:
- x = input(‘Enter the first number: ‘)
- y = input(‘Enter the second number: ‘)
-
insert your code here
print('The Result is ' + (int(x + y)))
Explanation
This choice attempts to concatenate the input values x and y as strings directly inside the print statement without converting them to integers first. This would result in a concatenation of the two input strings, not their sum. To calculate the sum of the two numbers, they need to be converted to integers before adding them together.
Correct answer
print('The Result is ' + str(int(x) + int(y)))
Explanation
This choice correctly converts the input values x and y to integers using int() function, adds them together, and then converts the result back to a string using str() function before concatenating it with the rest of the print statement. This ensures that the sum of the two numbers is printed as a string along with the specified message.
print('The Result is ' + (int(x) + int(y)))
Explanation
This choice attempts to add the input values x and y as integers directly inside the print statement without converting them first. This would result in a TypeError because the addition operation cannot be performed on strings. The correct approach is to convert the input values to integers before performing the addition.
print('The Result is ' + str(int(x + y)))
Explanation
This choice attempts to concatenate the input values x and y as a single string inside the print statement without converting them to integers first. This would result in a concatenation of the two input strings, not their sum. To calculate the sum of the two numbers, they need to be converted to integers before adding them together. Additionally, the result should be converted back to a string before concatenating it with the rest of the print statement.
Overall explanation
Topic: int() str() input()
Try it yourself:
-
x = input(‘Enter the first number: ‘)
-
y = input(‘Enter the second number: ‘)
-
x, y = ‘7’, ’11’ # Just for convenience
-
You cannot concatenate a string and an integer
-
print(‘The Result is ‘ + (int(x) + int(y))) # TypeError
-
print(‘The Result is ‘ + (int(x + y))) # TypeError
-
This works, but you get the wrong result,
-
because there is a string concatenation
-
before the type casting to integer:
-
print(‘The Result is ‘ + str(int(x + y))) # 711
-
print(‘The Result is ‘ + str(int(x) + int(y))) # 18
Explanation:
As always input() returns a string
Before you add them to each other you need to cast both of them to an integer
You need to cast the result to a string
to be able to concatenate it to the other string
Q533 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 55Skipped
Q511 – Operators
What is the expected output of the following code?
-
list1 = [3, 7, 23, 42]
-
list2 = [3, 7, 23, 42]
-
print(list1 is list2)
-
print(list1 == list2)
-
True
-
False
Explanation
This explanation is incorrect because the ‘is’ operator checks for object identity, not object equality. Since list1 and list2 are two separate objects in memory, the ‘is’ operator will return False. The ‘==’ operator, however, will return True because the values of the two lists are the same.
Correct answer
- False
- True
Explanation
The ‘is’ operator in Python checks if two variables refer to the same object in memory. In this case, list1 and list2 are two separate objects, even though they have the same values. Therefore, the ‘is’ operator will return False. The ‘==’ operator, on the other hand, checks if the values of the two objects are equal, which is True in this case.
- False
- False
Explanation
This explanation is incorrect because both the ‘is’ and ‘==’ operators will not return False for both statements. The ‘is’ operator will return False because list1 and list2 are two separate objects, while the ‘==’ operator will return True because the values of the two lists are the same.
- True
- True
Explanation
This explanation is incorrect because the ‘is’ operator will not return True for both statements. The ‘is’ operator checks for object identity, and since list1 and list2 are two separate objects, it will return False. The ‘==’ operator will return True because the values of the two lists are the same.
Overall explanation
Topics: list equal to operator identity operator
Try it yourself:
-
list1 = [3, 7, 23, 42]
-
list2 = [3, 7, 23, 42]
-
print(list1 is list2) # False
-
print(list1 == list2) # True
-
print(id(list1)) # e.g. 140532269484352
-
print(id(list2)) # e.g. 140532269935296 (a different number)
Explanation:
A list is a mutable data type.
If you create a second list (even one with the same values)
it will always be a new object.
You can test that with the id() function.
It returns a unique integer, the identity of the object.
The equal to operator compares the values, which are the same.
Q511 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 56Skipped
Q516 – Control Flow
What is the expected output of the following code?
marks = [80, 70, 90, 90, 80, 100]
average = sum(marks) // len(marks)
grade = ''
-
if 90 <= average <= 100:
-
grade = 'A' -
elif 80 <= average < 90:
-
grade = 'B' -
elif 70 <= average < 80:
-
grade = 'C' -
elif 65 <= average < 70:
-
grade = 'D' -
else:
-
grade = 'F' -
print(grade)
C
Explanation
The code assigns a grade based on the average calculated from the marks. However, the average does not fall between 70 and 80, so the grade ‘C’ is not expected as the output.
Correct answer
B
Explanation
The code calculates the average of the marks and assigns a grade based on the average. In this case, the average falls between 80 and 90, so the expected output is ‘B’.
The code is erroneous.
Explanation
The code is correct and error-free, so the output is expected to be one of the defined grades (‘A’, ‘B’, ‘C’, ‘D’, or ‘F’).
D
Explanation
The code assigns a grade based on the average calculated from the marks. Since the average does not fall between 65 and 70, the grade ‘D’ is not expected as the output.
F
Explanation
The code assigns a grade based on the average calculated from the marks. Since the average does not fall below 65, the grade ‘F’ is not expected as the output.
A
Explanation
The code assigns a grade based on the average calculated from the marks. Since the average falls between 80 and 90, the grade is expected to be ‘B’.
Overall explanation
Topics: if elif else list sum() len() chained comparison
Try it yourself:
-
marks = [80, 70, 90, 90, 80, 100]
-
average = sum(marks) // len(marks)
-
grade = ”
-
if 90 <= average <= 100:
-
grade = 'A' -
elif 80 <= average < 90:
-
grade = 'B' -
elif 70 <= average < 80:
-
grade = 'C' -
elif 65 <= average < 70:
-
grade = 'D' -
else:
-
grade = 'F' -
print(grade) # B
-
print(sum(marks)) # 510
-
print(average) # 85
Explanation:
Here you really have to do a little mental arithmetic.
80 + 70 + 90 + 90 + 80 + 100 -> 510
510 // 6 -> 85
85 is a the grade B
Q516 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 57Skipped
Q507 – Data Aggregates
What is the expected output of the following code?
-
data = {‘one’: ‘two’, ‘two’: ‘three’, ‘three’: ‘one’}
-
res = data[‘three’]
-
for _ in range(len(data)):
-
res = data[res] -
print(res)
three
Explanation
The code initializes a dictionary ‘data’ with key-value pairs. It then assigns the value corresponding to the key ‘three’ to the variable ‘res’. In the loop, the code iterates through the dictionary ‘data’ for the length of the dictionary, updating ‘res’ with the value corresponding to the current value of ‘res’. However, the final value of ‘res’ will not be ‘three’, so this choice is incorrect.
Correct answer
one
Explanation
The code initializes a dictionary ‘data’ with key-value pairs. It then assigns the value corresponding to the key ‘three’ to the variable ‘res’. In the loop, the code iterates through the dictionary ‘data’ for the length of the dictionary, updating ‘res’ with the value corresponding to the current value of ‘res’. Eventually, ‘res’ will be updated to ‘one’, which is the expected output.
('one', 'two', 'three')
Explanation
The code initializes a dictionary ‘data’ with key-value pairs. It then assigns the value corresponding to the key ‘three’ to the variable ‘res’. In the loop, the code iterates through the dictionary ‘data’ for the length of the dictionary, updating ‘res’ with the value corresponding to the current value of ‘res’. The final value of ‘res’ will not be a tuple containing ‘one’, ‘two’, and ‘three’, so this choice is incorrect.
two
Explanation
The code initializes a dictionary ‘data’ with key-value pairs. It then assigns the value corresponding to the key ‘three’ to the variable ‘res’. In the loop, the code iterates through the dictionary ‘data’ for the length of the dictionary, updating ‘res’ with the value corresponding to the current value of ‘res’. However, the final value of ‘res’ will not be ‘two’, so this choice is incorrect.
Overall explanation
Topics: dictionary for range() len()
Try it yourself:
-
data = {‘one’: ‘two’, ‘two’: ‘three’, ‘three’: ‘one’}
-
res = data[‘three’]
-
for _ in range(len(data)):
-
print(res) # one - two - three -
res = data[res] -
print(res) # one
Explanation:
Before the for loop res is 'one'
data['one']->'two'->data['two']->'three'->data['three']->'one'
After the for loop, res again is 'one'
Q507 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates