Python ITS-303 Test Exam III (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
Q327 – Data Types
What is the expected output of the following code?
print(type(1J))
Correct answer
<type 'complex'>
Explanation
The code print(type(1J)) will output “ because the value 1J represents a complex number in Python. The type() function returns the type of the object passed to it, and in this case, it will return the type as complex.
<type 'dict'>
Explanation
The choice “ is incorrect because the value 1J is not a dictionary type in Python. The correct type for the complex number 1J is complex, not dict.
<type 'float'>
Explanation
The choice “ is incorrect because the value 1J is not a floating-point number in Python. It is specifically used to represent a complex number, so the output will not be of type float.
<type 'unicode'>
Explanation
The choice “ is incorrect because the value 1J is not a Unicode string in Python. It is a complex number, so the output will not be of type unicode.
Overall explanation
Topics: type() complex
Try it yourself:
-
print(type(1J)) # <class ‘complex’>
-
c = 1j
-
print(c.real) # 0.0
-
print(c.imag) # 1.0
-
print(type(0 + 1j)) # <class ‘complex’>
Explanation:
You can use J or j for complex numbers.
1j is a complex number where the real part is 0 and the imaginary part is 1
Q327 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 2Skipped
Q347 – Error Handling
What is the expected output of the following code?
- try:
-
if '1' != 1: -
raise FirstError -
else: -
print('FirstError has not occured.') - except FirstError:
-
print('FirstError has occured.') - else:
-
print('None of the above.')
None of the above.
Explanation
This choice is incorrect because the code will not reach the "else" block as there is an error in the exception handling part. The code will raise a NameError before reaching the "else" block.
FirstError has occured.
Explanation
This choice is incorrect because the exception "FirstError" is not defined or imported in the code, so it will raise a NameError when trying to raise it. Therefore, the output will not be ‘FirstError has occured.’
Correct answer
The code is erroneous.
Explanation
The code contains an error in the exception handling part. The exception "FirstError" is not defined or imported in the code, so it will raise a NameError when trying to raise it. This makes the code erroneous.
FirstError has not occured.
Explanation
This choice is incorrect because the code will not reach the "else" block as there is an error in the exception handling part. The code will raise a NameError before reaching the "else" block, so the output will not be ‘FirstError has not occurred.’
Overall explanation
Topics: try except if else raise
Try it yourself:
-
"""
-
class FirstError(Exception):
-
pass -
"""
-
try:
-
if '1' != 1: # True -
raise FirstError -
else: -
print('FirstError has not occured.') -
except FirstError:
-
print('FirstError has occured.') -
else:
-
print('None of the above.') -
NameError: name ‘FirstError’ is not defined
Explanation:
FirstError is not a know Python exception.
If you use you own exception class,
it needs to inherit from an existing Python exception class.
Q347 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 3Skipped
Q357 – Control Flow
What is the expected output of the following snippet?
- s = ‘python’
- for i in range(len(s)):
-
i = s[i].upper() - print(s, end=”)
Correct answer
python
Explanation
The code iterates over each character in the string ‘python’ and converts it to uppercase, but the changes are not reflected back to the original string ‘s’. Therefore, the output remains ‘python’.
The code is erroneous.
Explanation
The code does not have any errors in terms of syntax, but it fails to update the original string ‘s’ with the uppercase characters. As a result, the output remains ‘python’.
P Y T H O N
Explanation
The code attempts to convert each character in the string ‘python’ to uppercase, but since the modifications are not applied to the original string ‘s’, the output remains ‘python’ without any spaces.
P y t h o n
Explanation
The code iterates over each character in the string ‘python’ and converts it to uppercase, but the changes are not saved back to the original string ‘s’. Therefore, the output remains ‘python’ without any spaces.
PYTHON
Explanation
Although the code tries to convert each character in the string ‘python’ to uppercase, the modifications are not stored back in the original string ‘s’. As a result, the output remains ‘python’.
Python
Explanation
The code attempts to convert each character in the string ‘python’ to uppercase, but since the changes are not applied to the original string ‘s’, the output remains ‘python’.
Overall explanation
Topics: for range() len() upper() string indexing
Try it yourself:
- s = ‘python’
- for i in range(len(s)):
-
i = s[i].upper() -
# s[i] = s[i].upper() # TypeError: ... - print(s, end="") # python
Explanation:
A string is immutable.
You can not change it, even if you tried.
Here it is not even tried
otherwise the code would cause a TypeError
Q357 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 4Skipped
Q325 – Operators
Which of the following code snippets will print True to the monitor?
Correct selection
- print(‘is’ in ‘This IS Python code.’)
Explanation
The ‘in’ operator in Python checks if a specified value exists in a sequence (string, list, tuple, etc.). In this code snippet, the ‘is’ operator is used to check if the string ‘is’ is present in the string ‘This IS Python code.’. Since the substring ‘is’ is present in the string, the expression will evaluate to True.
Correct selection
- print(‘t’ in ‘Peter’)
Explanation
The ‘in’ operator in Python checks if a specified value exists in a sequence (string, list, tuple, etc.). In this code snippet, the ‘t’ character is checked for in the string ‘Peter’. Since the character ‘t’ is present in the string, the expression will evaluate to True.
- x = ‘Peter Wellert’
- y = ‘Peter Wellert’.lower()
- print(x is y)
Explanation
The ‘is’ operator in Python checks if two variables refer to the same object in memory. In this code snippet, the variable x is assigned the string ‘Peter Wellert’, while y is assigned the lowercase version of the same string. Since the two strings are stored in different memory locations due to the case difference, the expression will evaluate to False.
- x = 42
- y = 42
- print(x is not y)
Explanation
The ‘is’ operator in Python checks if two variables refer to the same object in memory. In this code snippet, the variables x and y are assigned the same integer value of 42. However, since integers are immutable objects in Python, they are stored in different memory locations. Therefore, the expression will evaluate to False.
- x = [‘Peter’, ‘Paul’, ‘Mary’]
- y = [‘Peter’, ‘Paul’, ‘Mary’]
- print(x is y)
Explanation
The ‘is’ operator in Python checks if two variables refer to the same object in memory. In this code snippet, two lists x and y are created with the same elements. Even though the elements are the same, lists are mutable objects in Python, and each list is stored in a different memory location. Therefore, the expression will evaluate to False.
Overall explanation
Topics: lower() identity operator membership operator list
Try it yourself:
-
print(‘is’ in ‘This IS Python code.’) # True
-
print(‘t’ in ‘Peter’) # True
-
x = 42
-
y = 42
-
print(x is not y) # False
-
x = ‘Peter Wellert’
-
y = ‘Peter Wellert’.lower()
-
print(x is y) # False
-
x = ‘Peter Wellert’
-
y = ‘Peter Wellert’
-
print(x is y) # True
-
x = [‘Peter’, ‘Paul’, ‘Mary’]
-
y = [‘Peter’, ‘Paul’, ‘Mary’]
-
print(x is y) # False
-
print(x == y) # True
Explanation:
The membership operator works very good with strings.
It looks for a string in a string.
The identity operator with immutable data types (here int and string):
The 42 in x and y will reference to the same object.
Therefore they have the same identity
and the not identity operator will evaluate to False
One string will be changed by lower() to peter wellert
and therefore they will not have the same identity.
The identity operator with mutable data types (here list):
A new list will be a new object even if the values are the same.
Therefore they will not have the same identity.
But they will have the same values,
which you can check with the equal to operator
Q325 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 5Skipped
Q309 – Control Flow
How many stars will the following snippet print to the monitor?
-
data = [[x for x in range(y)] for y in range(3)]
-
for d in data:
-
if len(d) < 2: -
print('*')
Correct answer
two
Explanation
The list comprehension generates lists with varying lengths: [0], [0, 1], and [0, 1, 2]. The loop iterates over each list and checks if the length is less than 2. Only the first list [0] has a length less than 2, so the print statement will execute once, resulting in two stars being printed.
three
Explanation
The list comprehension generates lists with lengths [0], [0, 1], and [0, 1, 2]. The print statement inside the loop only executes when the length of the list is less than 2. Since only the first list [0] meets this condition, the print statement will execute once, resulting in three stars being printed.
one
Explanation
The list comprehension generates lists with lengths [0], [0, 1], and [0, 1, 2]. The print statement inside the loop only executes when the length of the list is less than 2. Since only the first list [0] meets this condition, only one star will be printed to the monitor.
zero
Explanation
The list comprehension generates lists with lengths [0], [0, 1], and [0, 1, 2]. However, the print statement inside the loop only executes when the length of the list is less than 2. Since only the first list [0] meets this condition, no stars will be printed to the monitor.
Overall explanation
Topics: list comprehension if len()
Try it yourself:
-
data = [[x for x in range(y)] for y in range(3)]
-
print(data) # [[], [0], [0, 1]]
-
for d in data:
-
print('d:', d) # [] -> [0] -> [0, 1] -
if len(d) < 2: -
print('*') # * *
Explanation:
The list comprehension produces a two-dimensional list.
The outer list has three elements.
Each of which is as long as its index: [], [0] and [0, 1]
The if in the for loop checks that length.
Two of the three are smaller than 2 and therefore two stars are printed.
Q309 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 6Skipped
Q355 – Modules
You want to find the hypotenuse of a right-angled triangle where perpendicular and base are known:
-
Line 1
- parendicular = 3
- base = 4
- print(hypot(parendicular, base))
What is missing in Line 1?
Correct answer
from math import hypot
Explanation
The correct choice is to import the hypot function from the math module in order to use it in the code. This allows the code to access the hypot function from the math module and calculate the hypotenuse of the triangle.
Nothing at all.
Explanation
Importing the hypot function from the math module is required in order to use it for calculating the hypotenuse. Without importing the hypot function from the math module, the code will not recognize the hypot function and will result in a NameError.
import math
Explanation
While importing the entire math module is a valid option, it is not necessary to import the entire module when only the hypot function is needed. Importing the entire math module may result in unnecessary overhead and decrease code readability.
import hypot
Explanation
There is no standalone hypot module in Python, so importing ‘hypot’ directly will result in a ModuleNotFoundError. The hypot function is a part of the math module, so importing ‘math’ and then using ‘hypot’ from it is the correct approach.
Overall explanation
Topics: math.hypot()
Try it yourself:
- from math import hypot
- parendicular = 3
- base = 4
- print(hypot(parendicular, base)) # 5.0
Explanation:
If you want to use the hypot() function without having to write math
in front of it you have to import it like this.
The alternative would be:
- import math
- parendicular = 3
- base = 4
- print(math.hypot(parendicular, base)) # 5.0
Q355 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 7Skipped
Q341 – Error Handling
What is the expected output of the following code?
- try:
-
file = open('data.txt', 'r') -
file.write('Hello file!') - except:
-
print('An error occurred.') - else:
-
print('The content is written successfully.')
The code is erroneous.
Explanation
The code is not erroneous, but it will raise an error when trying to write to a file opened in read mode (‘r’). The output will not be ‘The code is erroneous.’
Hello file!
Explanation
The code will not reach the ‘file.write()’ line because the file is opened in read mode (‘r’). Therefore, the ‘try’ block will not be able to write to the file, and the output will not be ‘Hello file!’
Correct answer
An error occurred.
Explanation
The code will raise an error when trying to write to a file that is opened in read mode (‘r’). The ‘except’ block will be executed, and the output will be ‘An error occurred.’
The content is written successfully.
Explanation
Since the file is opened in read mode (‘r’), the ‘file.write()’ line will raise an error, causing the ‘except’ block to be executed. Therefore, the output will not be ‘The content is written successfully.’
Overall explanation
Topics: try except else open() write()
io.UnsupportedOperation
Try it yourself:
-
try:
-
file = open('data.txt', 'r') -
file.write('Hello file!') -
except:
-
print('An error occurred.') # An error occurred. -
else:
-
print('The content is written successfully.') -
This happens, when the file doesn’t exist:
-
file = open(‘data.txt’, ‘r’) # FileNotFoundError
-
This happens, when the file exists:
-
file = open(‘data.txt’, ‘w’)
-
file.close()
-
file = open(‘data.txt’, ‘r’)
-
file.write(‘Hello file!’). # io.UnsupportedOperation: not writable
Explanation:
If a file gets opened with the modus r it is only readable.
But if the file does not exist, you will get a FileNotFoundError
The except block will be executed.
If the file did exist,
in the next line the write() method will fail,
because the file is only opened for reading.
You will get an io.UnsupportedOperation error
and the except block will be executed.
Q341 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 8Skipped
Q317 – Data Aggregates
What is the expected output of the following code?
- data = ()
- print(data.len())
1
Explanation
This choice is incorrect because the code initializes an empty tuple, so the length of the tuple is 0. Therefore, the expected output is not 1.
Correct answer
0
Explanation
The code initializes an empty tuple named ‘data’ and then uses the len() method to get the length of the tuple. Since the tuple is empty, the length of the tuple is 0, so the expected output is 0.
The code is erroneous.
Explanation
This choice is incorrect because the code is not erroneous. It correctly initializes an empty tuple and prints the length of the tuple, which is 0.
None
Explanation
This choice is incorrect because the code explicitly calls the len() method on the tuple ‘data’ and prints the result. It does not return None as the output.
Overall explanation
Topics: __len__() tuple
Try it yourself:
-
data = ()
-
print(data.len()) # 0
-
print(len(data)) # 0
-
print(type(data)) # <class ‘tuple’>
Explanation:
Every object has the method __len__()
Normally we use the function len() which calls the method __len__()
And sure, the length of an empty tuple is 0
Q317 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 9Skipped
Q326 – Functions
What is the expected output of the following code?
-
def test(x=1, y=2):
-
x = x + y -
y += 1 -
print(x, y) -
test()
3 1
Explanation
This choice is incorrect because the value of x is updated to x + y, which makes x equal to 3. However, y is incremented by 1, resulting in y being equal to 3. Therefore, the correct output is 3 3, not 3 1.
1 1
Explanation
This choice is incorrect because the values of x and y are not left unchanged. The function modifies the values of x and y according to the defined operations, resulting in x = 3 and y = 3.
1 3
Explanation
This choice is incorrect because the value of x is updated to x + y, which makes x equal to 3. However, y is incremented by 1, resulting in y being equal to 3. Therefore, the correct output is 3 3, not 1 3.
Correct answer
3 3
Explanation
The default values for x and y are 1 and 2, respectively. In the function, x is updated to x + y, which results in x being 3 (1 + 2). Then, y is incremented by 1, making y equal to 3. Therefore, the output of the function will be 3 3.
The code is erroneous.
Explanation
This choice is incorrect because the code provided is not erroneous. The function definition and execution are valid, and the output can be determined based on the operations performed within the function.
Overall explanation
Topics: def parameters
Try it yourself:
-
def test(x=1, y=2):
-
x = x + y # 1 + 2 -> 3 -
y += 1 # 2 + 1 -> 3 -
print(x, y) # 3 3 -
test()
Explanation:
The function gets called without an argument.
The parameter x and y get filled with their default values.
Then two little calculations and the printing.
Q326 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 10Skipped
Q334 – Modules
Assuming that all three files x.py, y.py, and z.py reside in the same folder,
what will be the output produced by running the z.py file?
x.py:
- print(‘x’, end=”)
y.py:
- import x
- print(‘y’, end=”)
z.py:
- print(‘z’, end=”)
- import x
- import y
zyx
Explanation
This choice is incorrect because the correct order of execution will be ‘zxy’, not ‘zyx’. The z.py file first prints ‘z’, then imports the x module which prints ‘x’, and finally imports the y module which prints ‘y’.
zxxy
Explanation
This choice is incorrect because the correct output will not have two ‘x’s in it. The order of execution will be ‘zxy’, with ‘z’ printed first, followed by ‘x’ and then ‘y’.
The code is erroneous.
Explanation
This choice is incorrect as the code is not erroneous. The output will be ‘zxy’ as explained in the correct choice. The code imports the x and y modules correctly and prints ‘z’, ‘x’, and ‘y’ in the expected order.
Correct answer
zxy
Explanation
The output will be ‘zxy’ because the z.py file first prints ‘z’, then imports the x module which prints ‘x’, and finally imports the y module which prints ‘y’. The order of execution will be z -> x -> y.
Overall explanation
Topic: import
Try it yourself:
-
First execute the following to create the needed files:
-
text = ”’
-
print(‘x’, end=”)
-
”’
-
with open(‘x.py’, ‘w’) as f:
-
f.write(text) -
text = ”’
-
import x
-
print(‘y’, end=”)
-
”’
-
with open(‘y.py’, ‘w’) as f:
-
f.write(text) -
text = ”’
-
print(‘z’, end=”)
-
import x
-
import y
-
”’
-
with open(‘z.py’, ‘w’) as f:
-
f.write(text) -
import z # zxy
Explanation:
Remember that imported files get executed only once.
When you import them a second time, they will not get executed again.
When you run the file z.py z gets printed.
x gets imported and x gets printed.
Then y gets imported.
That will not import x again, because x has already been import.
y gets printed and that’s it.
Q334 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 11Skipped
Q333 – Data Types
Consider the following python code:
-
x1 = ’23’
-
y1 = 7
-
z1 = x1 * y1
-
x2 = 42
-
y2 = 7
-
z2 = x2 / y2
-
x3 = 4.7
-
y3 = 1
-
z3 = x3 / y3
What are the data types of the variables z1, z2 and z3?
str, int, float
Explanation
The variable z1 is the result of multiplying a string (’23’) by an integer (7), which will result in a string. The variable z2 is the result of dividing an integer (42) by another integer (7), which will result in an integer. The variable z3 is the result of dividing a float (4.7) by an integer (1), which will result in a float.
str, int, int
Explanation
The variable z1 is the result of multiplying a string (’23’) by an integer (7), which will result in a string. The variable z2 is the result of dividing an integer (42) by another integer (7), which will result in an integer. The variable z3 is the result of dividing a float (4.7) by an integer (1), which will result in an integer.
str, str, str
Explanation
The variable z1 is the result of multiplying a string (’23’) by an integer (7), which will result in a string. The variable z2 is the result of dividing an integer (42) by another integer (7), which will result in an integer. The variable z3 is the result of dividing a float (4.7) by an integer (1), which will result in a string.
Correct answer
str, float, float
Explanation
The variable z1 is the result of multiplying a string (’23’) by an integer (7), which will result in a string. The variable z2 is the result of dividing an integer (42) by another integer (7), which will result in a float. The variable z3 is the result of dividing a float (4.7) by an integer (1), which will also result in a float.
Overall explanation
Topics: string integer float division operator
multiply operator string concatenation
Try it yourself:
-
x1 = ’23’
-
y1 = 7
-
z1 = x1 * y1
-
print(’23’ * 7) # ‘23232323232323’
-
x2 = 42
-
y2 = 7
-
z2 = x2 / y2
-
print(42 / 7) # 6.0
-
x3 = 4.7
-
y3 = 1
-
z3 = x3 / y3
-
print(4.7 / 1) # 4.7
-
print(type(z1)) # <class ‘str’>
-
print(type(z2)) # <class ‘float’>
-
print(type(z3)) # <class ‘float’>
Explanation:
First the string 23 will be multiplied by 7
Second the integer 42 is divided by the integer 7
The result is the float 6.0
Remember the division operator always returns a float
Third the float 4.7 is divided by the integer 1
and surely the result is the float 4.7
Q333 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 12Skipped
Q310 – Operators
What is the expected output of the following code?
-
x = True
-
y = False
-
z = False
-
if x or y and z:
-
print('TRUE') -
else:
-
print('FALSE')
The code is erroneous.
Explanation
The code is not erroneous as it follows the correct syntax and logic of Python. The output of the code will be ‘TRUE’ based on the evaluation of the logical operators used in the if statement.
None of the above.
Explanation
None of the above choices are correct as the expected output of the code is ‘TRUE’ based on the evaluation of the logical operators used in the if statement.
Correct answer
TRUE
Explanation
The expected output of the code is ‘TRUE’ because the ‘or’ operator has a higher precedence than the ‘and’ operator. Therefore, the expression ‘x or y and z’ will be evaluated as ‘x or (y and z)’, resulting in ‘True or (False and False)’, which simplifies to ‘True or False’, and since ‘True’ is one of the operands, the result is ‘True’.
FALSE
Explanation
The expected output of the code is not ‘FALSE’ because the ‘or’ operator has a higher precedence than the ‘and’ operator. Therefore, the expression ‘x or y and z’ will be evaluated as ‘x or (y and z)’, resulting in ‘True or (False and False)’, which simplifies to ‘True or False’, and since ‘True’ is one of the operands, the result is ‘True’, not ‘False’.
Overall explanation
Topics: logical operators operator precedence if else
Try it yourself:
-
x = True
-
y = False
-
z = False
-
if x or y and z:
-
print('TRUE') # TRUE -
else:
-
print('FALSE') -
print(x or y and z) # True
-
print(True or False and False) # True
-
print(True or (False and False)) # True
-
print(True or False) # True
-
print(True) # True
Explanation:
The one important thing here is, that the logical and operator
has a higher precedence than the logical or operator
Q310 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 13Skipped
Q314 – Functions
What is the expected output of the following code?
-
def func(item):
-
item += [1] -
data = [1, 2, 3, 4]
-
func(data)
-
print(len(data))
4
Explanation
The output is not 4 because the function func modifies the original list data by adding an element to it. As a result, the length of the data list will be 5, not 4.
The code is erroneous.
Explanation
The code is not erroneous. The function func modifies the original list data by adding an element to it, and the length of the modified data list is printed correctly.
2
Explanation
The output is not 2 because the function func modifies the original list data by adding an element to it. As a result, the length of the data list will be 5, not 2.
Correct answer
5
Explanation
The expected output of the code is 5 because the function func takes a list item as a parameter, appends the value 1 to it, and modifies the original list data. Therefore, the length of the modified data list will be 5.
Overall explanation
Topics: list plus operator list concatenation mutable argument
Try it yourself:
-
def func(item):
-
item += [1] # [1, 2, 3, 4] + [1] -> [1, 2, 3, 4, 1] -
data = [1, 2, 3, 4]
-
func(data)
-
print(len(data)) # 5
-
print(data) # [1, 2, 3, 4, 1]
-
x = [1, 2, 3, 4]
-
x.append([1])
-
print(x) # [1, 2, 3, 4, [1]]
Explanation:
Inside the function a list concatenation by plus operator takes place.
The plus operator merges the elements of the second list into the first list.
append() would insert the list itself into the other list.
Q314 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 14Skipped
Q353 – Basics
UNICODE is a standard:
Correct answer
like ASCII, but much more expansive.
Explanation
UNICODE is a standard that encompasses a much wider range of characters compared to ASCII. It includes characters from various languages, symbols, emojis, and special characters, making it more expansive and versatile for encoding text.
used by coders from universities.
Explanation
UNICODE is a standard used by a wide range of developers, organizations, and industries, not just coders from universities. It is a fundamental standard for text encoding and character representation in various software applications, websites, and communication protocols.
for coding floating-point numbers.
Explanation
UNICODE is primarily designed for encoding text characters and symbols, not specifically for coding floating-point numbers. Floating-point numbers are typically represented using different standards or formats, such as IEEE 754, rather than UNICODE.
honored by the whole universe.
Explanation
While UNICODE is a widely accepted and used standard for encoding text, it is not necessarily honored by the entire universe. It is a standard adopted by many organizations, software developers, and industries, but its usage may vary depending on the specific requirements and technologies used.
Overall explanation
Topics: Unicode ASCII
Explanation:
Read about it here:
https://en.wikipedia.org/wiki/Unicode
Q353 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics
Question 15Skipped
Q303 – Operators
What is the expected output of the following code?
x = 4.5
y = 2
print(x // y)
2.5
Explanation
This choice is incorrect because the floor division operator (//) always rounds down to the nearest integer. In this case, 4.5 divided by 2 results in 2.0, not 2.5.
2.25
Explanation
This choice is incorrect because the floor division operator (//) always rounds down to the nearest integer. In this case, 4.5 divided by 2 results in 2.0, not 2.25.
2
Explanation
This choice is incorrect because the floor division operator (//) always rounds down to the nearest integer. In this case, 4.5 divided by 2 results in 2.0, not 2.
Correct answer
2.0
Explanation
The floor division operator (//) in Python performs division where the result is the quotient rounded down to the nearest integer. In this case, 4.5 divided by 2 results in 2.0 as the output.
Overall explanation
Topic: floor division operator
Try it yourself:
- print(4.5 // 2) # 2.0
- print(4.5 // 2.0) # 2.0
- print(4 // 2.0) # 2.0
- print(4 // 2) # 2
Explanation:
If one operand is a float, the floor division operator returns a float.
Only if both operands are an integer,
the floor division operator returns an integer.
Q303 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 16Skipped
Q305 – Control Flow
What is the expected output of the following code?
-
my_list = [[3-i for i in range(3)] for j in range(3)]
-
result = 0
-
for i in range(3):
-
result += my_list[i][i] -
print(result)
Correct answer
6
Explanation
The code creates a 3×3 nested list where each element is the result of subtracting the inner loop variable i from 3. The for loop then iterates over the main list and adds the diagonal elements (my_list[i][i]) to the result variable. In this case, the diagonal elements are [3, 2, 1], which sum up to 6.
4
Explanation
The code does not sum up all elements of the nested list, but only the diagonal elements. The diagonal elements are [3, 2, 1], which sum up to 6. Therefore, the output is not 4.
7
Explanation
The code does not sum up all elements of the nested list, but only the diagonal elements. The diagonal elements are [3, 2, 1], which sum up to 6. Therefore, the output is not 7.
2
Explanation
The code does not sum up all elements of the nested list, but only the diagonal elements. The diagonal elements are [3, 2, 1], which sum up to 6. Therefore, the output is not 2.
Overall explanation
Topics: list comprehension list indexing for
Try it yourself:
-
data = [[3-i for i in range(3)] for j in range(3)]
-
print(data) # [[3, 2, 1], [3, 2, 1], [3, 2, 1]]
-
res = 0
-
for i in range(3):
-
print('data[' + str(i) + '][' + str(i) + ']: ', data[i][i]) -
""" -
data[0][0]: 3 -
data[1][1]: 2 -
data[2][2]: 1 -
""" -
res += data[i][i] -
print(res) # 6 (3 + 2 + 1)
Explanation:
The list comprehension produces a two-dimensional list.
The three elements of the outer list also each have three elements:
the numbers 3, 2, 1
The for loop will add together
the first element of the first list 3
the second element of the second list 2
and the third element of the third list 1
3 + 2 + 1 -> 6
Q305 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 17Skipped
Q350 – Error Handling
Select the true statements.
Choose two.
You cannot use multiple except: branches to handle multiple exceptions coming from the same try: branch.
Explanation
This statement is incorrect. In Python, you can use multiple except: branches to handle multiple exceptions coming from the same try: block. This flexibility allows for more precise error handling based on the specific exceptions that may be raised.
Different except: branches may have unique exception names.
Explanation
Different except: branches in Python may have unique exception names to distinguish between different types of exceptions. This helps in providing specific error handling for each type of exception that may occur in the try: block.
Correct selection
Different except: branches must have unique exception names.
Explanation
In Python, different except: branches must have unique exception names to handle different types of exceptions separately. This allows for specific error handling based on the type of exception raised in the try: block.
Correct selection
You can use multiple except: branches to handle multiple exceptions coming from the same try: branch.
Explanation
You can use multiple except: branches in Python to handle multiple exceptions coming from the same try: block. This allows for more granular error handling by specifying different actions for different types of exceptions that may occur.
Overall explanation
Topics: try except
Try it yourself:
-
Example 1:
-
try:
-
number = int(input('Please enter a number:\n')) -
result = 42 / number -
except ValueError:
-
print('You can only use digits.') -
except ZeroDivisionError:
-
print('Do not enter a zero.') -
else:
-
print(result) -
Example 2:
-
try:
-
number = int(input('Please enter a number:\n')) -
result = 42 / number -
except ValueError:
-
print('You can only use digits.') -
except ZeroDivisionError:
-
print('Do not enter a zero.') -
except ZeroDivisionError:
-
print('This code is unreachable.') -
else:
-
print(result)
Explanation:
Yes, you can absolutely use multiple except: branches
with the same try: branch (Example 1).
And yes, different except: branches must have unique exception names.
You don’t get an error message, but you would have unreachable code.
Like in Example 2:
The first except ZeroDivisionError: branch will be executed
and the second except ZeroDivisionError: branch can never be executed.
Q350 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 18Skipped
Q328 – Data Types
What is the expected output of the following code?
print(ord('c') – ord('a'))
Correct answer
2
Explanation
The ord() function in Python returns the Unicode code point of a character. In this case, ord(‘c’) returns 99 and ord(‘a’) returns 97. Subtracting these values (99 – 97) gives the output of 2.
3
Explanation
This choice is incorrect because subtracting the Unicode code points of ‘c’ and ‘a’ (99 – 97) does not result in 3.
1
Explanation
This choice is incorrect because subtracting the Unicode code points of ‘c’ and ‘a’ (99 – 97) does not result in 1.
0
Explanation
This choice is incorrect because subtracting the Unicode code points of ‘c’ and ‘a’ (99 – 97) does not result in 0.
Overall explanation
Topic: ord()
Try it yourself:
- print(ord(‘c’) – ord(‘a’)) # 2
- print(ord(‘c’)) # 99
- print(ord(‘a’)) # 97
Explanation:
ord() returns an integer representing the Unicode character.
You do not need to remember the number of each character,
but like in the alphabet c is two after a
Q328 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 19Skipped
Q343 – Control Flow
Consider the following programm to calculate a discount percentage:
-
day = input(‘Enter the day of the week:’)
-
discount = 3
-
if day == ‘Wednesday’:
-
discount += 5 -
elif day == ‘Thursday’:
-
discount += 7 -
elif day == ‘Saturday’:
-
discount += 10 -
elif day == ‘Sunday’:
-
discount += 20 -
else:
-
discount += 2
Which of the following inputs will get the user a discount of 5 %?
Wednesday
Explanation
Wednesday is explicitly mentioned in the if-elif chain, and it will trigger the discount increase by 5, resulting in a total discount of 8%.
Saturday
Explanation
Saturday is explicitly mentioned in the if-elif chain, and it will trigger the discount increase by 10, resulting in a total discount of 13%.
Sunday
Explanation
Sunday is explicitly mentioned in the if-elif chain, and it will trigger the discount increase by 20, resulting in a total discount of 23%.
Correct answer
Friday
Explanation
Friday is not explicitly mentioned in the if-elif chain, so the default discount of 3 will be applied, resulting in a 5% discount for the user.
Thursday
Explanation
Thursday is explicitly mentioned in the if-elif chain, and it will trigger the discount increase by 7, resulting in a total discount of 10%.
Overall explanation
Topic: if elif else
Try it yourself:
-
day = input(‘Enter the day of the week:’)
-
day = ‘Friday’ # Just for convenience
-
day = ‘Wednesday’ # 8
-
day = ‘Thursday’ # 10
-
day = ‘Saturday’ # 13
-
day = ‘Sunday’. # 23
-
discount = 3
-
if day == ‘Wednesday’:
-
discount += 5 -
elif day == ‘Thursday’:
-
discount += 7 -
elif day == ‘Saturday’:
-
discount += 10 -
elif day == ‘Sunday’:
-
discount += 20 -
else:
-
discount += 2 -
print(discount) # 5
Explanation:
Friday is in none of the conditions and therefore the else clause gets executed.
And 3 plus 2 is 5
Q343 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 20Skipped
Q313 – Functions
What is the expected output of the following code?
-
def func(x, y=2):
-
num = 1 -
for i in range(y): -
num = num * x -
return num -
print(func(4))
-
print(func(4, 4))
-
128
-
512
Explanation
This choice is incorrect because it does not match the expected output of the code. The function func calculates the result of x raised to the power of y, so the output values should be 16 and 256 for the given input values.
Correct answer
- 16
- 256
Explanation
The function func takes two parameters, x and y, with a default value of 2 for y. It then initializes num to 1 and multiplies x by num y times using a for loop. When func(4) is called, it calculates 4^2, which is 16. When func(4, 4) is called, it calculates 4^4, which is 256.
- 32
- 1024
Explanation
This choice is incorrect because it does not match the expected output of the code. The function func calculates the result of x raised to the power of y, so the output values should be 16 and 256 for the given input values.
- 8
- 16
Explanation
This choice is incorrect because it does not match the expected output of the code. The function func calculates the result of x raised to the power of y, so the output values should be 16 and 256 for the given input values.
Overall explanation
Topics: def for range()
Try it yourself:
-
def func(x, y=2):
-
num = 1 -
for i in range(y): -
num = num * x -
return num -
print(func(4)) # 16 (4 * 4)
-
print(func(4, 4)) # 256 (4 * 4 * 4 * 4)
-
import math
-
print(math.pow(4, 2)) # 16.0
-
print(math.pow(4)) # TypeError: pow expected 2 arguments, got 1
Explanation:
The second parameter determines
how often the first parameter is multiplied by itself.
Like the method math.pow() but additionally with a default parameter
for the exponent with the default value of 2
Q313 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 21Skipped
Q308 – Control Flow
What is the expected output of the following code?
print(len([i for i in range(0, -2)]))
Correct answer
0
Explanation
The range function in Python generates a sequence of numbers starting from the first parameter (0 in this case) up to, but not including, the second parameter (-2 in this case). Since there are no numbers between 0 and -2, the list comprehension will not generate any elements, resulting in a length of 0 for the list.
2
Explanation
The range function in Python generates a sequence of numbers starting from the first parameter (0 in this case) up to, but not including, the second parameter (-2 in this case). Since there are no numbers between 0 and -2, the list comprehension will not generate any elements, resulting in a length of 0 for the list, not 2.
3
Explanation
The range function in Python generates a sequence of numbers starting from the first parameter (0 in this case) up to, but not including, the second parameter (-2 in this case). Since there are no numbers between 0 and -2, the list comprehension will not generate any elements, resulting in a length of 0 for the list, not 3.
1
Explanation
The range function in Python generates a sequence of numbers starting from the first parameter (0 in this case) up to, but not including, the second parameter (-2 in this case). Since there are no numbers between 0 and -2, the list comprehension will not generate any elements, resulting in a length of 0 for the list, not 1.
Overall explanation
Topics: list comprehension range() len()
Try it yourself:
-
print(len([i for i in range(0, -2)])) # 0
-
Those make more sense:
-
print(len([i for i in range(0, -2, -1)])) # 2
-
print(len([i for i in range(-2, 0)])) # 2
Explanation:
The "problem" here is the range(0, -2)
The start value 0 has to be lower than the end value -2
Otherwise range() does not return an element.
Q308 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 22Skipped
Q335 – Modules
What is the expected output of the following code?
- import math
- print(dir(math))
Correct answer
A list of all the entities residing in the math module.
Explanation
The dir() function in Python returns a list of all the entities (functions, classes, variables, etc.) residing in the specified module. In this case, dir(math) will return a list of all the entities in the math module.
A string containing the fully qualified name of the module.
Explanation
The dir() function does not return a string containing the fully qualified name of the module; it returns a list of entities within the module. This choice is incorrect.
The number of all the entities residing in the math module.
Explanation
The dir() function does not return the number of entities in a module; instead, it returns a list of all the entities. Therefore, this choice is incorrect.
The code is erroneous.
Explanation
The code is not erroneous; it is a valid Python code snippet that imports the math module and prints the list of entities in the module using the dir() function. Therefore, this choice is incorrect.
Overall explanation
Topics: import dir()
Try it yourself:
-
import math
-
print(dir(math))
-
"""
-
[‘doc‘, ‘file‘, ‘loader‘, ‘name‘, ‘package‘,
-
‘spec‘, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’,
-
‘atanh’, ‘ceil’, ‘comb’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’,
-
‘dist’, ‘e’, ‘erf’, ‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’,
-
‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’, ‘gcd’, ‘hypot’, ‘inf’,
-
‘isclose’, ‘isfinite’, ‘isinf’, ‘isnan’, ‘isqrt’, ‘lcm’, ‘ldexp’,
-
‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘log2’, ‘modf’, ‘nan’,
-
‘nextafter’, ‘perm’, ‘pi’, ‘pow’, ‘prod’, ‘radians’, ‘remainder’,
-
‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘tau’, ‘trunc’, ‘ulp’]
-
"""
Explanation:
The dir() function returns the names of all entities (properties and methods)
of the passed module (or object).
(There is another question about the same topic Q444.)
Q335 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 23Skipped
Q349 – Modules
What is the expected output of the following code?
-
from random import randint
-
for i in range(2):
-
print(randint(1, 2), end='')
There are millions of possible combinations,
and the exact output cannot be predicted.
Explanation
While it is true that there are millions of possible combinations due to the random nature of the randint() function, the output is limited to the range specified in the function (1 to 2). Therefore, the exact output can be predicted within the constraints of the specified range.
Correct answer
11, 12, 21, or 22
Explanation
The randint() function generates a random integer between the specified range (inclusive). In this case, the range is from 1 to 2. Therefore, the output can be either 1 or 2 for each iteration of the loop, resulting in possible combinations of 11, 12, 21, or 22.
12
Explanation
This choice does not account for the fact that the randint() function can generate either 1 or 2 for each iteration. It only considers the possibility of 12 as the output, which is not accurate based on the random nature of the function.
12, or 21
Explanation
This choice only considers the specific combinations of 12 and 21 as the output, which is not correct. Since the randint() function can generate either 1 or 2 randomly, the output can also include combinations like 11 and 22.
Overall explanation
Topics: import random randint() for range()
Try it yourself:
-
from random import randint
-
for i in range(2):
-
print(randint(1, 2), end='') # 11, 12, 21, or 22
Explanation:
The for loop will have two iterations.
Each time a 1 or a 2 will be printed.
Therefore the result can be 11, 12, 21, or 22
Q349 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 24Skipped
Q336 – I/O
You are creating a function that reads a data file
and prints each line of the file.
You write the following code.
- import os # Line 01
- def read_file(file): # Line 02
-
line = None # Line 03 -
if os.path.isfile(file): # Line 04 -
data = open(file, 'r') # Line 05 -
while line != '': # Line 06 -
line = data.readline() # Line 07 -
print(line) # Line 08
The code attempts to read the file even if the file does not exist.
You need to correct the code.
Which lines have indentation problems?
Each correct answer presents part of the solution.
Choose three.
Correct selection
Line 07
Explanation
Line 07 should be indented to be inside the while loop block. This ensures that the code reads a line from the file and prints it for each iteration of the while loop.
Correct selection
Line 08
Explanation
Line 08 should be indented to be inside the while loop block. This ensures that the line read from the file is printed for each iteration of the while loop.
Line 04
Explanation
Line 04 does not have an indentation problem. It is correctly placed inside the if statement block that checks if the file exists.
Line 02
Explanation
Line 02 does not have an indentation problem. It is correctly placed at the beginning of the function definition block.
Line 05
Explanation
Line 05 does not have an indentation problem. It is correctly placed inside the if statement block that checks if the file exists.
Correct selection
Line 06
Explanation
Line 06 should be indented to be inside the if statement block that checks if the file exists. This ensures that the while loop only runs when the file exists.
Line 01
Explanation
Line 01 does not have an indentation problem. It is correctly placed at the beginning of the code.
Line 03
Explanation
Line 03 does not have an indentation problem. It is correctly placed inside the function definition block.
Overall explanation
Topics: import def None if os.path.isfile() open()
while readline() not equal to operator
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) -
import os # Line 01
-
def read_file(file): # Line 02
-
line = None # Line 03 -
if os.path.isfile(file): # Line 04 -
data = open(file, 'r') # Line 05 -
while line != '': # Line 06 -
line = data.readline() # Line 07 -
print(line) # Line 08 -
read_file(‘data.txt’)
Explanation:
The while loop needs to be inside of the if statement
in order to only read the lines if the file exists.
Q336 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 25Skipped
Q304 – Control Flow
How many elements will the following list contain?
data = [i for i in range(-1, 2)]
four
Explanation
The list comprehension [i for i in range(-1, 2)] generates elements for each value of i in the range from -1 to 1 (inclusive). Since the range includes three values, the list will not contain four elements.
Correct answer
three
Explanation
The list comprehension [i for i in range(-1, 2)] generates elements for each value of i in the range from -1 to 1 (inclusive). Since the range includes -1, 0, and 1, the list will contain three elements.
one
Explanation
The list comprehension [i for i in range(-1, 2)] generates elements for each value of i in the range from -1 to 1 (inclusive). Since the range includes three values, the list will contain more than one element.
two
Explanation
The list comprehension [i for i in range(-1, 2)] generates elements for each value of i in the range from -1 to 1 (inclusive). As the range includes three values, the list will contain more than two elements.
zero
Explanation
The list comprehension [i for i in range(-1, 2)] generates elements for each value of i in the range from -1 to 1 (inclusive). As this range includes three values, the list will not be empty and will contain elements.
Overall explanation
Topics: list comprehension for
Try it yourself:
-
data = [i for i in range(-1, 2)]
-
print(data) # [-1, 0, 1]
-
print(len(data)) # 3
-
print(list(range(-1, 2))) # [-1, 0, 1]
Explanation:
In data is going be a list with the element -1, 0 and 1
The list comprehension is not necessary if I does not get changed.
The start of range() is inclusive -1
and the end is exclusive, meaning 2 is excluded.
Q304 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 26Skipped
Q319 – Data Aggregates
What is the expected output of the following code?
- nums = [1, 2, 3]
- data = (‘Peter’,) * (len(nums) – nums[::-1][0])
- print(data)
('Peter', 'Peter')
Explanation
This choice is incorrect because the code does not output a tuple with two elements ‘Peter’, ‘Peter’ but an empty tuple ().
PeterPeter
Explanation
This choice is incorrect because the code does not output a string ‘PeterPeter’ but an empty tuple ().
Correct answer
()
Explanation
The code initializes a list ‘nums’ with [1, 2, 3] and a tuple ‘data’ with a single element ‘Peter’. The expression (len(nums) – nums[::-1][0]) evaluates to (3 – 3) which is 0. Multiplying a tuple by 0 results in an empty tuple, so the expected output is ().
The code is erroneous.
Explanation
This choice is incorrect because the code is not erroneous. It correctly calculates the length of the list ‘nums’ and creates a tuple ‘data’ based on that length. The output is an empty tuple ().
('Peter')
Explanation
This choice is incorrect because the code does not output a string ‘Peter’ but an empty tuple ().
Overall explanation
Topics: len() list tuple list slicing list indexing
multiply operator tuple concatenation
Try it yourself:
-
nums = [1, 2, 3]
-
data = (‘Peter’,) * (len(nums) – nums[::-1][0])
-
print(data) # ()
-
print(len(nums) – nums[::-1][0]) # 0
-
print(len([1, 2, 3]) – [1, 2, 3][::-1][0]) # 0
-
print(3 – [3, 2, 1][0]) # 0
-
print(3 – 3) # 0
-
print(0) # 0
-
print((‘Peter’,)) # (‘Peter’,)
-
print(type((‘Peter’,))) # <class ‘tuple’>
-
print(type((‘Peter’))) # <class ‘str’>
-
print((‘Peter’,) * 0) # ()
-
print((1, 2, 3) * 0) # ()
Explanation:
The length of nums is 3
[::-1] reverses the list and then 3 is the first index.
3 minus 3 makes 0
The trailing comma marks the tuple with one element.
Otherwise it would be a string with additional parentheses.
Any tuple multiplied by 0 becomes an empty tuple.
Q319 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 27Skipped
Q331 – I/O
Which of the following commands is used
to open a file in binary format for writing only?
open('data.txt', 'wb+')
Explanation
The command open(‘data.txt’, ‘wb+’) is used to open a file for reading and writing in binary mode. While this mode allows both reading and writing operations on the file, it does not restrict the file to be opened in binary format for writing only, as the ‘wb’ mode does.
open('data.txt', 'w+')
Explanation
The command open(‘data.txt’, ‘w+’) is used to open a file for reading and writing in text mode, not binary mode. This mode allows both reading and writing operations on the file, but it does not specifically open the file in binary format for writing only.
open('data.txt', 'w')
Explanation
The command open(‘data.txt’, ‘w’) is used to open a file for writing in text mode, not binary mode. This mode is suitable for writing text data to a file but does not handle binary data as efficiently as the ‘wb’ mode.
Correct answer
open('data.txt', 'wb')
Explanation
The command open(‘data.txt’, ‘wb’) is used to open a file in binary format for writing only. The ‘wb’ mode specifies that the file should be opened for writing in binary mode, ensuring that the file is treated as a binary file and not a text file.
Overall explanation
Topic: open() and its modes
Try it yourself:
-
data = open(‘data.txt’, ‘wb’)
-
print(type(data)) # <class ‘_io.BufferedWriter’>
-
print(data.read()) # io.UnsupportedOperation: read
-
data = open(‘data.txt’, ‘wb+’)
-
print(type(data)) # <class ‘_io.BufferedRandom’>
-
print(data.read()) # b”
-
data = open(‘data.txt’, ‘w’)
-
print(type(data)) # <class ‘_io.TextIOWrapper’>
-
data = open(‘data.txt’, ‘w+’)
-
print(type(data)) # <class ‘_io.TextIOWrapper’>
Explanation:
You will need the w for writing and the b for the binary format.
But that’s it.
You do not want the + because than it will not be writing only,
but updating (writing and reading).
Q331 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 28Skipped
Q340 – Data Types
You are an intern for ABC electric cars company.
You must create a function that calculates the average velocity
of their vehicles on a 1320 foot (1/4 mile) track.
Consider the following code.
-
distance = ???(input(‘Enter the distance travelled in feet’))
-
distance_miles = distance/5280 # convert to miles
-
time = ???(input(‘Enter the time elapsed in seconds’))
-
time_hours = time/3600 # convert to hours
-
velocity = distance_miles/time_hours
-
print(‘The average Velocity : ‘, velocity, ‘miles/hour’)
The output must be as precise as possible.
What would you insert instead of ??? and ???
- float
- int
Explanation
Using the float function for the distance input and the int function for the time input may result in loss of precision during the conversion process. Since time is typically measured in seconds, using int for the time input could lead to rounding errors when converting to hours, affecting the accuracy of the average velocity calculation.
Correct answer
- float
- float
Explanation
Using the float function for both distance and time inputs ensures that the values entered by the user are treated as floating-point numbers, allowing for more precise calculations when converting to miles and hours respectively. This precision is necessary to accurately calculate the average velocity.
- int
- int
Explanation
Selecting the int function for both distance and time inputs might lead to significant loss of precision during the conversion process. Given that distance and time are typically measured in decimal values, using int could round down the numbers, potentially causing errors in the final average velocity calculation. Utilizing float data types is essential for maintaining accuracy in this scenario.
- int
- float
Explanation
Using the int function for the distance input and the float function for the time input may also result in loss of precision. While distance is usually measured in feet, converting it to miles requires decimal points, making float a more suitable choice. Introducing an integer value for distance could lead to inaccurate results when calculating velocity.
Overall explanation
Topics: input() float() int() division operator
Try it yourself:
-
distance = float(input(‘Enter the distance travelled in feet’))
-
distance = float(‘437723.42’) # Just for convenience
-
distance_miles = distance/5280
-
time = float(input(‘Enter the time elapsed in seconds’))
-
time = float(‘1723.9’) # Just for convenience
-
time_hours = time/3600 # convert to hours
-
velocity = distance_miles/time_hours
-
print(‘The average Velocity : ‘, velocity, ‘miles/hour’)
-
The average Velocity : 173.1236071486956 miles/hour
-
print((float(‘437723.42’)/5280) / (float(‘1723.9’)/3600))
-
173.1236071486956
-
print((int(‘437723.42’)/5280) / (int(‘1723.9’)/3600))
-
ValueError
-
print((int(float(‘437723.42’))/5280) / (int(float(‘1723.9’))/3600))
-
173.21387115496228
Explanation:
To be as precise as possible means,
that you do not want to loose the numbers after the decimal point,
if they are given by the user.
Therefore you need float() for both inputs.
Assuming the user enters a float
the function int() would raise a ValueError anyway.
Q340 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 29Skipped
Q354 – I/O
Which of the following open modes allow you to perform read operations?
Choose two.
w
Explanation
The ‘w’ mode in Python allows you to open a file for writing only. This mode is used when you want to create a new file or overwrite the contents of an existing file. It does not allow read operations on the file.
Correct selection
r
Explanation
The ‘r’ mode in Python allows you to open a file for reading only. This mode is used when you want to perform read operations on a file without modifying its contents.
a
Explanation
The ‘a’ mode in Python allows you to open a file for appending data. This mode is used when you want to add new data to the end of an existing file, but it does not allow direct read operations on the file.
Correct selection
r+
Explanation
The ‘r+’ mode in Python allows you to open a file for both reading and writing. In addition to reading data from the file, you can also write data to it. This mode is useful when you need to perform both read and write operations on a file.
Overall explanation
Topic: open() and its modes
Try it yourself:
-
First execute the following to create the needed file:
-
with open(‘data.txt’, ‘w’) as f:
-
f.write('Hello') -
with open(‘data.txt’, ‘r’) as f:
-
print(f.read()) # Hello -
with open(‘data.txt’, ‘r+’) as f:
-
print(f.read()) # Hello -
"""
-
with open(‘data.txt’, ‘a’) as f:
-
print(f.read()) # io.UnsupportedOperation: not readable -
"""
-
"""
-
with open(‘data.txt’, ‘w’) as f:
-
print(f.read()) # io.UnsupportedOperation: not readable -
"""
Explanation:
The mode r opens in read only mode
and the mode r+ opens in read & write mode.
Q354 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 30Skipped
Q324 – Operators
What is the expected output of the following code if the user enters 2 and 4?
- x = float(input())
- y = float(input())
- print(y ** (1 / x))
0.0
Explanation
The output will not be 0.0. The calculation involves raising y to the power of (1/x), which will result in a non-zero value when x and y are both non-zero.
1.0
Explanation
The output will not be 1.0. The calculation involves raising y to the power of (1/x), which will not necessarily result in 1.0 when x and y are 2 and 4, respectively.
4.0
Explanation
The output will not be 4.0. The calculation involves raising y to the power of (1/x), which will not result in 4.0 when x and y are 2 and 4, respectively.
Correct answer
2.0
Explanation
The code takes two float inputs from the user and calculates y to the power of (1/x). In this case, if the user enters 2 and 4, the output will be 2.0 as 4 to the power of (1/2) is equal to 2.0.
Overall explanation
Topics: input() float() exponentiation operator
division operator square root
Try it yourself:
-
x = float(input())
-
y = float(input())
- x, y = float(‘2’), float(‘4’) # Just for convenience
- print(y ** (1 / x)) # 2.0
- print(4.0 ** (1 / 2)) # 2.0
- print(4.0 ** 0.5) # 2.0
- import math
- print(math.sqrt(4)) # 2.0
Explanation:
As always input() returns a string
They both get casted to a float
Here you need a little bit of mathematical knowledge.
You can take the square root of a number by raising it to the power of 0.5
Q324 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 31Skipped
Q332 – I/O
You want to write a new player to a file
and print the whole file content to the monitor.
What snippet would you insert in the line indicated below:
- customer = ‘Peter Wellert’
- with open(‘customers.txt’, ‘a+’) as f:
-
f.write(customer) -
# insert your code here -
data = f.read() -
print(data)
f.begin()
Explanation
There is no f.begin() method in Python file handling. This choice is incorrect as it does not correspond to any valid file operation in Python. It is not applicable to the scenario where you need to read the full file content after writing to it.
f.close()
Explanation
f.close() is used to close the file after reading or writing operations, but if you close the file before reading the content, you won’t be able to access the file data. This choice is incorrect for this scenario where you want to print the whole file content to the monitor after writing a new player.
Correct answer
f.seek(0)
Explanation
Using f.seek(0) will move the file cursor to the beginning of the file, allowing you to read the entire content of the file after writing the new player’s name. This is the correct choice to ensure that you can read the full file content after writing to it.
f.flush()
Explanation
f.flush() is used to flush the internal buffer of the file, but it does not move the file cursor or enable you to read the entire content of the file. It is not the correct choice for this scenario where you need to read the full file content after writing to it.
Overall explanation
Topics: with open() write() seek() read() flush() close()
Try it yourself:
-
First execute the following to create a file
-
with already existing players:
-
players = ”’Peter
-
Paul
-
Mary
-
Jane
-
”’
-
with open(‘players.txt’, ‘w’) as f:
-
f.write(players) -
player = ‘Steve’
-
with open(‘players.txt’, ‘a+’) as f:
-
f.write(player) -
f.seek(0) -
# f.flush() # -> no error, but also no output -
# f.begin() # AttributeError: ... -
# f.close() # In the next line: ValueError: ... -
data = f.read() -
print(data) -
"""
-
Peter
-
Paul
-
Mary
-
Jane
-
Steve
-
"""
Explanation:
seek(0) sets the file position back to zero (to the beginning of the file).
The flush() method only clears the internal buffer of the file,
but the file position would still be behind the last entry
and read() would start reading from there and find nothing.
Q332 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 32Skipped
Q311 – Functions
Which of the following function definition does not return any value?
A function that returns a random integer from 1 to 100.
Explanation
This function definition explicitly returns a random integer from 1 to 100, so it does return a value. The function has a return statement that provides a specific output.
A function that converts an uppercase letter to lowercase.
Explanation
This function definition converts an uppercase letter to lowercase and returns the lowercase letter as the output. It explicitly returns a value, making it different from a function that does not return any value.
Correct answer
A function that prints integers from 1 to 100.
Explanation
This function definition prints integers from 1 to 100 but does not explicitly return any value. It performs an action (printing) without returning a specific value or result.
Overall explanation
Topics: def return
Try it yourself:
-
A function that prints integers from 1 to 100:
-
def f1():
-
for i in range(1, 101): -
print(i) -
print(f1()) # None
-
Not to return a value means to return "None"
-
A function that returns a random integer from 1 to 100:
-
def f2():
-
from random import randint -
return randint(1, 100) -
print(f2()) # e.g. 87
-
It returns the random number.
-
A function that converts an uppercase letter to lowercase:
-
def f3(s):
-
return s.lower() -
print(f3(‘X’)) # x
-
This function would return the lower letter
Explanation:
The function f1() does not have the return keyword.
Therefore it would return None
Every function, that does not return anything, returns None
Q311 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 33Skipped
Q321 – Data Aggregates
What is the expected output of the following code?
- data = {‘a’: 1, ‘b’: 2, ‘c’: 3}
- print(data[‘a’, ‘b’])
[1,2]
Explanation
This choice is incorrect because the code is trying to access values from a dictionary using multiple keys (‘a’ and ‘b’) within a single set of square brackets, which is not valid syntax for dictionary access. The expected output would not be a list containing the values 1 and 2.
{'a':1,'b':2}
Explanation
This choice is incorrect because the code is trying to access values from a dictionary using multiple keys (‘a’ and ‘b’) within a single set of square brackets, which is not valid syntax for dictionary access. The expected output would not be a dictionary containing the key-value pairs ‘a’: 1 and ‘b’: 2.
(1,2)
Explanation
This choice is incorrect because the code is trying to access values from a dictionary using multiple keys (‘a’ and ‘b’) within a single set of square brackets, which is not valid syntax for dictionary access. The expected output would not be a tuple containing the values 1 and 2.
Correct answer
The code is erroneous.
Explanation
The code is erroneous because when accessing values from a dictionary in Python, you need to provide a single key within square brackets. In this case, the code is trying to access values using multiple keys (‘a’ and ‘b’) within a single set of square brackets, which is not valid syntax for dictionary access.
Overall explanation
Topics: dictionary indexing
Try it yourself:
-
data = {‘x’: 1, ‘y’: 2, ‘z’: 3}
-
print(data[‘x’, ‘y’]) # KeyError: (‘x’, ‘y’)
-
print(data[‘x’], data[‘y’]) # 1 2
-
data = {(‘x’, ‘y’): 1}
-
print(data[‘x’, ‘y’]) # 1
Explanation:
You can have a tuple as key of a dictionary
but that is not given here.
Q321 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 34Skipped
Q301 – Operators
What is the expected output of the following code?
print(type(1 / 2))
<type 'number'>
Explanation
‘number’ is not a valid type in Python. The output of the code will be a specific data type, not a generic ‘number’ type.
<type 'tuple'>
Explanation
The output of the code is not a tuple. The division operation does not return a tuple type.
<type 'int'>
Explanation
The division of two integers in Python results in a floating-point number, not an integer. Therefore, the output of the code will not be ‘int’.
Correct answer
<type 'float'>
Explanation
The code snippet performs division between two integers, which results in a floating-point number. Therefore, the output of the code will be the type ‘float’.
<type 'double'>
Explanation
‘double’ is not a valid type in Python. Python uses ‘float’ to represent floating-point numbers, so the output of the code will be ‘float’.
Overall explanation
Topics: division operator type()
Try it yourself:
- print(type(1 / 2)) # <type ‘float’>
- print(1 / 2) # 0.5
- print(1 / 1) # 1.0
Explanation:
The division operator always returns a float.
Q301 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 35Skipped
Q316 – Data Aggregates
What is the expected output of the following code?
-
fruits1 = [‘Apple’, ‘Pear’, ‘Banana’]
-
fruits2 = fruits1
-
fruits3 = fruits1[:]
-
fruits2[0] = ‘Cherry’
-
fruits3[1] = ‘Orange’
-
res = 0
-
for i in (fruits1, fruits2, fruits3):
-
if i[0] == 'Cherry': -
res += 1 -
if i[1] == 'Orange': -
res += 10 -
print(res)
0
Explanation
The code modifies fruits2 and fruits3 but does not change the first element of fruits1 to ‘Cherry’ or the second element of fruits1 to ‘Orange’. Therefore, none of the conditions in the loop are met, and the ‘res’ variable remains 0, resulting in an output of 0.
11
Explanation
The code modifies fruits2 and fruits3, but only the first condition in the loop is met when checking fruits2 for ‘Cherry’. The second condition is not met for any list. Therefore, the ‘res’ variable is incremented by 1, resulting in an output of 1.
22
Explanation
The code modifies fruits2 and fruits3, and both conditions in the loop are met when checking fruits2 for ‘Cherry’ and fruits3 for ‘Orange’. The ‘res’ variable is incremented by 1 and 10, respectively, resulting in an output of 22.
Correct answer
12
Explanation
The code creates three lists, fruits1, fruits2, and fruits3, with the same initial values. Then, it modifies fruits2 and fruits3 by changing the first element of fruits2 to ‘Cherry’ and the second element of fruits3 to ‘Orange’. The loop checks each list for specific values and increments the ‘res’ variable accordingly. As a result, the expected output is 12.
Overall explanation
Topics: for copy vs. reference list slicing list indexing
Try it yourself:
-
fruits1 = [‘Apple’, ‘Pear’, ‘Banana’]
-
fruits2 = fruits1
-
fruits3 = fruits1[:]
-
fruits2[0] = ‘Cherry’
-
fruits3[1] = ‘Orange’
-
res = 0
-
for i in (fruits1, fruits2, fruits3):
-
if i[0] == 'Cherry': -
res += 1 -
if i[1] == 'Orange': -
res += 10 -
print(res) # 12
-
print(id(fruits1)) # e.g. 140539383900864
-
print(id(fruits2)) # e.g. 140539383900864 (the same number)
-
print(id(fruits3)) # e.g. 140539652049216 (a different number)
Explanation:
A list is a mutable data type.
Assigning it will create a reference.
Slicing it from start to end [:] will create a copy.
Therefore Cherry goes in fruits2 and thereby also in fruits1
Orange only goes in fruits3
Q316 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 36Skipped
Q306 – Control Flow
What is the expected output of the following code?
-
data = [1, {}, (2,), (), {3}, [4, 5]]
-
points = 0
-
for i in range(len(data)):
-
if type(data[i]) == list: -
points += 1 -
elif type(data[i]) == tuple: -
points += 10 -
elif type(data[i]) == set: -
points += 100 -
elif type(data[i]) == dict: -
points += 1000 -
else: -
points += 10000 -
print(points)
Correct answer
11121
Explanation
The code iterates through the elements in the ‘data’ list and checks the type of each element. For lists, it adds 1 to ‘points’, for tuples it adds 10, for sets it adds 100, for dictionaries it adds 1000, and for any other type it adds 10000. In this case, the list contains a list, a dictionary, a tuple, a set, and an empty dictionary. Therefore, the expected output is 1 + 1000 + 10 + 10000 + 100 = 11121.
10212
Explanation
The code iterates through the elements in the ‘data’ list and checks the type of each element. For lists, it adds 1 to ‘points’, for tuples it adds 10, for sets it adds 100, for dictionaries it adds 1000, and for any other type it adds 10000. In this case, the list contains a list, a dictionary, a tuple, a set, and an empty dictionary. Therefore, the expected output is not 10212.
21102
Explanation
The code iterates through the elements in the ‘data’ list and checks the type of each element. For lists, it adds 1 to ‘points’, for tuples it adds 10, for sets it adds 100, for dictionaries it adds 1000, and for any other type it adds 10000. In this case, the list contains a list, a dictionary, a tuple, a set, and an empty dictionary. Therefore, the expected output is not 21102.
10221
Explanation
The code iterates through the elements in the ‘data’ list and checks the type of each element. For lists, it adds 1 to ‘points’, for tuples it adds 10, for sets it adds 100, for dictionaries it adds 1000, and for any other type it adds 10000. In this case, the list contains a list, a dictionary, a tuple, a set, and an empty dictionary. Therefore, the expected output is not 10221.
11112
Explanation
The code iterates through the elements in the ‘data’ list and checks the type of each element. For lists, it adds 1 to ‘points’, for tuples it adds 10, for sets it adds 100, for dictionaries it adds 1000, and for any other type it adds 10000. In this case, the list contains a list, a dictionary, a tuple, a set, and an empty dictionary. Therefore, the expected output is not 11112.
Overall explanation
Topics: if elif else type() list tuple set dict
equal to operator add and assign operator
Try it yourself:
-
data = [1, {}, (2,), (), {3}, [4, 5]]
-
points = 0
-
for i in range(len(data)):
-
if type(data[i]) == list: -
points += 1 -
elif type(data[i]) == tuple: -
points += 10 -
elif type(data[i]) == set: -
points += 100 -
elif type(data[i]) == dict: -
points += 1000 -
else: -
points += 10000 -
print(points) # 11121
Explanation:
Every element of data gets tested in the for loop.
There is one integer, which executes the else clause.
There is one dictionary: {}
There is one set: {3}
There are two tuples: (2,) and ()
There is one list: [4, 5]
Q306 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 37Skipped
Q329 – Data Aggregates
What is the expected output of the following code?
- w = [7, 3, 23, 42]
- x = w[1:]
- y = w[1:]
- z = w
- y[0] = 10
- z[1] = 20
- print(w)
[10, 20, 42]
Explanation
This choice suggests that only the elements at index 0 of ‘y’ and ‘z’ are modified. However, the element at index 1 of ‘z’ is also changed in the code. Therefore, the output is not [10, 20, 42].
Correct answer
[7, 20, 23, 42]
Explanation
The code creates a list ‘w’ with elements [7, 3, 23, 42]. Then, it assigns a slice of ‘w’ starting from index 1 to list ‘x’ and ‘y’. ‘z’ is assigned a reference to the original list ‘w’. When the elements at index 0 of ‘y’ and index 1 of ‘z’ are modified, it directly affects the original list ‘w’. Therefore, the expected output is [7, 20, 23, 42].
[7, 3, 23, 42]
Explanation
This choice does not consider the modifications made to the ‘y’ and ‘z’ lists. Since ‘y’ and ‘z’ are references to the original list ‘w’, any changes made to them will reflect in ‘w’. Therefore, the output is not [7, 3, 23, 42].
[10, 20, 23, 42]
Explanation
This choice considers the modification made to the element at index 0 of ‘y’ but overlooks the change made to the element at index 1 of ‘z’. Since ‘z’ is a reference to the original list ‘w’, the modification to ‘z’ affects ‘w’. Therefore, the output is not [10, 20, 23, 42].
Overall explanation
Topics: list slicing list indexing
Try it yourself:
-
w = [7, 3, 23, 42]
-
x = w[1:] # [3, 23, 42]
-
y = w[1:] # [3, 23, 42]
-
z = w # A reference
-
print(z) # [7, 3, 23, 42]
-
y[0] = 10 # Changes only y
-
z[1] = 20 # Changes z and w
-
print(w) # [7, 20, 23, 42]
-
print(id(x)) # e.g. 140539383900864
-
print(id(y)) # e.g. 140539383947456 (a different number)
-
print(id(w)) # e.g. 140539652049216 (the same number than z)
-
print(id(z)) # e.g. 140539652049216 (the same number than w)
Explanation:
The two list slicings create new lists.
Therefore the change of y does not effect w
The assigning of the list creates a reference to the same object
Therefore the change of z does also effect w
Q329 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 38Skipped
Q337 – Basics
You have the following file.
index.py:
- from sys import argv
- print(argv[0])
You run the file by executing the following command in the terminal.
python index.py Hello
What is the expected oputput?
Hello
Explanation
The output will not be "Hello" because argv[0] in the script refers to the name of the script itself, not the arguments passed to the script. Therefore, the output will be the name of the script, which is "index.py".
Correct answer
index.py
Explanation
The expected output is "index.py" because when the script is executed with the command "python index.py Hello", the value of argv[0] in the script refers to the name of the script itself, which is "index.py".
IndexError
Explanation
The output will not be "IndexError" as there is no indexing error in the script provided. The script simply prints the value of argv[0], which refers to the name of the script itself, so there should be no IndexError in this case.
ImportError
Explanation
The output will not be "ImportError" as there is no import error in the script provided. The script imports the argv module from sys correctly, so there should be no ImportError in this case.
Overall explanation
Topic: sys.argv
Try it yourself:
-
First execute the following to create the needed file:
-
code = ”’
-
from sys import argv
-
print(argv[0])
-
”’
-
with open(‘index.py’, ‘w’) as f:
-
f.write(code) -
In Terminal:
-
python index.py Hello
-
"""
-
index.py
-
"""
Explanation:
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 Hello
The first index (the index 0) of the argv variable is always the filename.
If you want Hello to be the output, you have to write print(argv[1])
Q337 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics
Question 39Skipped
Q356 – Modules
The sys.stderr stream is normally associated with:
the keyboard
Explanation
The sys.stderr stream is not associated with the keyboard. It is used for error messages and output to the screen, while the keyboard is used for input. The sys.stdin stream is typically associated with reading input from the keyboard in Python.
the printer
Explanation
The sys.stderr stream is not normally associated with the printer. It is specifically used for error messages and outputting to the screen, rather than sending data to a physical printer device.
Correct answer
the screen
Explanation
The sys.stderr stream is typically used for error messages and is associated with the screen, where these error messages are displayed to the user. It is the standard error output stream in Python, separate from the standard output stream sys.stdout.
a null device
Explanation
The sys.stderr stream is not typically associated with a null device. A null device is used to discard data, whereas sys.stderr is specifically used for error messages to be displayed on the screen.
Overall explanation
Topic: sys.stderr
Try it yourself:
- import sys
- print(‘Error 1’, file=sys.stderr) # Error 1
- sys.stderr.write(‘Error 2’) # Error 2
Explanation:
Here are two different ways to send a string to the sys.stderr stream.
You will see both messages on the screen,
because the sys.stderr stream is normally associated with the screen.
Q356 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 40Skipped
Q346 – Control Flow
The ABC company is creating a program
that allows customers to log the number of miles biked.
The program will send messages based on how many miles the customer logs.
You create the following Python code.
-
???
-
name = input('What is your name? ') -
return name -
???
-
calories = miles * calories_per_mile -
return calories -
distance = int(input(‘How many miles did you bike this week? ‘))
-
burn_rate = 50
-
biker = get_name()
-
calories_burned = calc_calories(distance, burn_rate)
-
print(biker + ‘, you burned about’, calories_burned, ‘calories.’)
What would you insert instead of ??? and ???
def calc_calories():
Explanation
The function calc_calories() is incorrectly defined without any parameters, but it needs to receive the miles biked and the burn rate to calculate the calories burned accurately. It should be defined with two parameters: miles and burn_rate.
def get_name(biker):
Explanation
The function get_name(biker) is incorrectly defined with a parameter biker, which is not needed for this specific functionality. The function should only prompt the user to input their name and return it.
Correct selection
def get_name():
Explanation
The function get_name() is correctly defined with no parameters as it only needs to return the name input by the user. This function will prompt the user to input their name and return it to the main program.
def calc_calories(miles, burn_rate):
Explanation
The function calc_calories(miles, burn_rate) is correctly defined with two parameters: miles and burn_rate. This function will calculate the calories burned based on the miles biked and the burn rate provided.
def get_name(name):
Explanation
The function get_name(name) is incorrectly defined with a parameter name, which is not needed for this specific functionality. The function should only prompt the user to input their name and return it.
Correct selection
def calc_calories(miles, calories_per_mile):
Explanation
The function calc_calories(miles, calories_per_mile) is correctly defined with two parameters: miles and calories_per_mile. This function will calculate the calories burned based on the miles biked and the burn rate provided.
Overall explanation
Topics: def input() multiplication operator int()
Try it yourself:
-
def get_name():
-
# name = input('What is your name? ') -
name = 'Peter' -
return name -
def calc_calories(miles, calories_per_mile):
-
calories = miles * calories_per_mile -
return calories -
distance = int(input(‘How many miles did you bike this week? ‘))
-
distance = int(‘740’)
-
burn_rate = 50
-
biker = get_name()
-
calories_burned = calc_calories(distance, burn_rate)
-
print(biker + ‘, you burned about’, calories_burned, ‘calories.’)
-
Peter, you burned about 37000 calories.
Explanation:
biker = get_name() calls get_name() without any arguments
and therefore you can not have any parameters:
def get_name():
calories_burned = calc_calories(distance, burn_rate)
calls calc_calories() with two arguments
and therefore you need two parameters:
def calc_calories(miles, calories_per_mile):
Q346 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 41Skipped
Q307 – Control Flow
How many stars will the following snippet print to the monitor?
x = 16
while x > 0:
print('*')
x //= 2
The code will enter an infinite loop.
Explanation
The snippet initializes x to 16 and then enters a while loop that continues as long as x is greater than 0. Inside the loop, it prints a single asterisk ‘*’ and then divides x by 2 using the floor division operator ‘//’. Since x is divided by 2 in each iteration, it will eventually reach 0 after 5 iterations, causing the loop to terminate. The code will not enter an infinite loop.
three
Explanation
The snippet initializes x to 16 and then enters a while loop that continues as long as x is greater than 0. Inside the loop, it prints a single asterisk ‘*’ and then divides x by 2 using the floor division operator ‘//’. This process repeats until x becomes less than or equal to 0. The loop will run 5 times, printing 5 asterisks to the monitor, not 3.
Correct answer
five
Explanation
The snippet initializes x to 16 and then enters a while loop that continues as long as x is greater than 0. Inside the loop, it prints a single asterisk ‘*’ and then divides x by 2 using the floor division operator ‘//’. This process repeats until x becomes less than or equal to 0. The loop will run 5 times, printing 5 asterisks to the monitor.
one
Explanation
The snippet initializes x to 16 and then enters a while loop that continues as long as x is greater than 0. Inside the loop, it prints a single asterisk ‘*’ and then divides x by 2 using the floor division operator ‘//’. This process repeats until x becomes less than or equal to 0. The loop will run 5 times, printing 5 asterisks to the monitor, not just 1.
Overall explanation
Topics: while greater than operator print() with end parameter
floor-divide and assign operator
Try it yourself:
- x = 16
- while x > 0:
-
print('1. x:', x) # 16 -> 8 -> 4 -> 2 -> 1 -
print('*') # ***** -
x //= 2 # x = x // 2 -
print('2. x:', x) # 8 -> 4 -> 2 -> 1 -> 0
Explanation:
After each printing a floor division by 2 takes place.
And 1 // 2 is 0 and that’s where the while loop ends.
Q307 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 42Skipped
Q338 – Basics
By which variable of the sys module can we access command line arguments?
args
Explanation
The variable ‘args’ is not a valid variable in the sys module to access command line arguments. The correct variable is ‘argv’, which holds the command line arguments as a list.
arguments
Explanation
The variable ‘arguments’ is not a valid variable in the sys module to access command line arguments. The correct variable is ‘argv’, which is specifically designed to hold and access the command line arguments.
argsv
Explanation
The variable ‘argsv’ is not a valid variable in the sys module to access command line arguments. The correct variable is ‘argv’, which is used to access the command line arguments passed to the Python script.
Correct answer
argv
Explanation
The correct variable to access command line arguments in the sys module is argv. This variable is a list that contains all the command line arguments passed to the Python script when it is executed.
Overall explanation
Topic: sys.argv
Try it yourself:
-
import sys
-
print(sys.argv[0]) # The first index is the name of the file
-
Now execute the following to create the needed file:
-
code = ”’
-
import sys
-
for a in sys.argv[1:]:
-
print(a) -
”’
-
with open(‘argv.py’, ‘w’) as f:
-
f.write(code) -
In Terminal:
-
python argv.py Peter Paul Mary
-
"""
-
Peter
-
Paul
-
Mary
-
"""
Explanation:
sys.argv[1:] slices everything except the first index with holds the filename.
You have to open the folder where you created the argv.py file in a terminal
and run the file by python argv.py Peter Paul Mary
The "v" in argv stands for vector.
Q338 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics
Question 43Skipped
Q318 – Control Flow
What is the expected output of the following code?
- data = [(0, 1), (1, 2), (2, 3)]
- res = sum(i for j, i in data)
- print(res)
Correct answer
6
Explanation
The code iterates over each tuple in the ‘data’ list, unpacks the tuple as ‘j’ and ‘i’, and then sums the ‘i’ values. In this case, the sum of 1, 2, and 3 is 6, so the expected output is 6.
The code is erroneous.
Explanation
The code is correct and will produce an output. It sums the ‘i’ values in the tuples, so there is no error in the code. The expected output is 6.
9
Explanation
The sum of the ‘i’ values in the tuples (1, 2, and 3) is 6, not 9. Therefore, the expected output is 6, not 9.
3
Explanation
The code is not simply summing the ‘j’ values, but rather the ‘i’ values in each tuple. Therefore, the sum of 1, 2, and 3 is 6, not 3.
Overall explanation
Topics: sum() list tuple generator expression
Try it yourself:
-
data = [(0, 1), (1, 2), (2, 3)]
-
res = sum(i for j, i in data)
-
print(res) # 6
-
print(i for j, i in data) # <generator object
at …> -
print([i for j, i in data]) # [1, 2, 3]
Explanation:
The for loop inside the generator expression
takes the second index from every tuple.
1, 2, 3 add up to 6
Q318 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 44Skipped
Q320 – Data Aggregates
What is the expected output of the following code?
- data = (1,) * 3
- data[0] = 2
- print(data)
(1, 1, 1)
Explanation
This choice is incorrect because the code will raise a TypeError due to trying to modify an element in a tuple, which is not allowed in Python. Therefore, the output will not be (1, 1, 1).
(2, 1, 1)
Explanation
This choice is incorrect because the code will raise a TypeError due to trying to modify an element in a tuple, which is not allowed in Python. Therefore, the output will not be (2, 1, 1).
Correct answer
The code is erroneous.
Explanation
The code is erroneous because tuples are immutable in Python, meaning their elements cannot be changed once they are assigned. Therefore, trying to modify the value at index 0 of the tuple ‘data’ will result in a TypeError.
(2, 2, 2)
Explanation
This choice is incorrect because the code will raise a TypeError due to trying to modify an element in a tuple, which is not allowed in Python. Therefore, the output will not be (2, 2, 2).
Overall explanation
Topics: tuple multiply operator tuple concatenation tuple indexing
Try it yourself:
- data = (1,) * 3
- data[0] = 2 # TypeError: …
- print(data)
Explanation:
A tuple is immutable. You can not change it.
Therefore you can not assign something to one of its indexes.
Q320 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 45Skipped
Q312 – Functions
What is the expected output of the following code?
-
def test(x, y=23, z=10):
-
print('x is', x, 'and y is', y, 'and z is', z) -
test(3, 7)
-
test(42, z=24)
-
test(z=60, x=100)
The code is erroneous.
Explanation
The code is not erroneous; it defines a function test with default parameter values and makes multiple function calls with different argument assignments.
Correct answer
- x is 3 and y is 7 and z is 10
- x is 42 and y is 23 and z is 24
- x is 100 and y is 23 and z is 60
Explanation
The first function call test(3, 7) assigns 3 to x and 7 to y, leaving z as the default value of 10. The second function call test(42, z=24) assigns 42 to x and overrides the default value of z with 24, leaving y as the default value of 23. The third function call test(z=60, x=100) assigns 100 to x and overrides the default value of z with 60, leaving y as the default value of 23.
- x is 3 and y is 7 and z is 10
- x is 23 and y is 42 and z is 24
- x is 60 and y is 100 and z is 23
Explanation
This choice does not match the expected output based on the function calls and parameter assignments provided in the code snippet.
- x is 7 and y is 3 and z is 10
- x is 42 and y is 23 and z is 24
- x is 23 and y is 100 and z is 60
Explanation
This choice does not match the expected output based on the function calls and parameter assignments provided in the code snippet.
Overall explanation
Topics: def arguments/parameters
Try it yourself:
-
def test(x, y=23, z=10):
-
print('x is', x, 'and y is', y, 'and z is', z) -
test(3, 7) # x is 3 and y is 7 and z is 10
-
test(42, z=24) # x is 42 and y is 23 and z is 24
-
test(z=60, x=100) # x is 100 and y is 23 and z is 60
Explanation:
First test(3, 7) is executed:
x gets the first argument 3
y gets the second argument 7
z stays 10
Second test(42, z=24) is executed:
x gets the first argument 42
z gets the second argument 24
y stays 23
Third test(z=60, x=100) is executed:
z gets the first argument 60
x gets the second argument 100
y stays 23
Q312 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 46Skipped
Q352 – Data Aggregates
An alternative name for a data structure called a stack is:
Correct answer
LIFO
Explanation
LIFO stands for Last In, First Out, which is a characteristic of a stack data structure. In a stack, the last element added is the first one to be removed, making LIFO an alternative name for a stack.
FOLO
Explanation
FOLO is not a commonly used term in computer science or data structures to describe a stack. The correct alternative name for a stack is LIFO, which stands for Last In, First Out.
FIFO
Explanation
FIFO stands for First In, First Out, which is a characteristic of a queue data structure, not a stack. In a queue, the first element added is the first one to be removed, so FIFO is not an alternative name for a stack.
Overall explanation
Topic: LIFO
Try it yourself:
- x = []
- x.append(1)
- x.append(2)
- x.append(3)
- print(x.pop()) # 3
- print(x.pop()) # 2
- print(x.pop()) # 1
Explanation:
LIFO stands for Last-In-First-Out.
Here you find a great explanation:
http://bluegalaxy.info/codewalk/2018/08/12/python-how-to-implement-a-lifo-stack/
Q352 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 47Skipped
Q302 – Operators
What value will be assigned to the x variable?
- z = 2
- y = 1
- x = y < z or z > y and y > z or z < y
0
Explanation
The expression does not evaluate to 0. The result of the expression is a boolean value (True or False) based on the conditions provided, not an integer value like 0.
Correct answer
True
Explanation
The expression evaluates to True because the logical OR operator (or) returns True if at least one of the conditions is True. In this case, the condition "y < z" is True, so the overall result is True.
False
Explanation
The expression does not evaluate to False. The logical OR operator (or) returns True if at least one of the conditions is True, and in this case, the condition "y < z" is True, so the overall result is True.
1
Explanation
The expression does not evaluate to 1. The result of the expression is a boolean value (True or False) based on the conditions provided, not an integer value like 1.
Overall explanation
Topics: operators relational operators operator precedence
Try it yourself:
- z = 7
- y = 3
- x = y < z or z > y and y > z or z < y
- print(x) # True
- print(y < z or z > y and y > z or z < y) # True
- print(3 < 7 or 7 > 3 and 3 > 7 or 7 < 3) # True
- print(True or True and False or False) # True
- print(True or (True and False) or False) # True
- print(True or False or False) # True
- print((True or False) or False) # True
- print(True or False) # True
- print(True) # True
Explanation:
The operators here are from three different groups.
"Comparisons, Identity, Membership operators", "Logical AND", "Logical OR".
The two comparison operators,
greater than operator and less than operator have the highest precedence.
Then the logical and operator has a higher precedence
than the logical or operators
Q302 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 48Skipped
Q344 – Functions
What is the expected output of the following code?
-
def func(x):
-
global y -
y = x * x -
return y -
func(2)
-
print(y)
Correct answer
4
Explanation
The code defines a function ‘func’ that takes a parameter ‘x’, calculates the square of ‘x’, assigns it to the global variable ‘y’, and returns the result. When the function is called with ‘2’ as the argument, ‘y’ is assigned the value of ‘2 * 2’, which is 4. Therefore, the expected output when printing ‘y’ is 4.
The code is erroneous.
Explanation
The code is not erroneous. It defines a function ‘func’ that correctly calculates the square of the input parameter ‘x’ and assigns it to the global variable ‘y’. When the function is called with ‘2’ as the argument, ‘y’ is assigned the value of ‘2 * 2’, which is 4. Therefore, the code will output 4, not raise an error.
None
Explanation
The code defines a function ‘func’ that calculates the square of the input parameter ‘x’ and assigns it to the global variable ‘y’. When the function is called with ‘2’ as the argument, ‘y’ is assigned the value of ‘2 * 2’, which is 4. Therefore, the expected output when printing ‘y’ is not ‘None’.
2
Explanation
The code correctly calculates the square of the input parameter ‘x’ and assigns it to the global variable ‘y’. When the function is called with ‘2’ as the argument, ‘y’ is assigned the value of ‘2 * 2’, which is 4. Therefore, the expected output when printing ‘y’ is 4, not 2.
Overall explanation
Topics: def return global
Try it yourself:
-
def func(x):
-
global y -
y = x * x -
return y -
func(2)
-
print(y) # 4
Explanation:
The global keyword can be used to read
and write a global variable inside of a function.
Once you write global y then y also exists in the outer scope.
You would not need the return here.
It is of no use, because the return value of func(2)
does not get processed any further.
But still you can print y because y is global
Q344 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 49Skipped
Q345 – Basics
What is the expected output of the following code?
- num = 2 + 3 * 5
- print(Num)
17.0
Explanation
The code will not output 17.0 because the variable num is assigned the value of 2 + 3 * 5, which equals 17. However, the code is trying to print Num (with a capital ‘N’), not num, so the output will not be in floating-point format.
Correct answer
The code is erroneous.
Explanation
The code is erroneous because the variable num is assigned the value of 2 + 3 * 5, which equals 17. However, when trying to print the variable Num (with a capital ‘N’), it will result in an error because Python is case-sensitive and Num is not defined.
25
Explanation
The code will not output 25 because the variable num is assigned the value of 2 + 3 * 5, which equals 17. However, the code is trying to print Num (with a capital ‘N’), not num, so the output will not be 25.
17
Explanation
The code will not output 17 because the variable num is assigned the value of 2 + 3 * 5, which equals 17. However, the code is trying to print Num (with a capital ‘N’), not num, so the output will not be 17.
Overall explanation
Topics: naming variables NameError
Try it yourself:
- num = 2 + 3 * 5
- print(Num) # NameError: name ‘Num’ is not defined
-
print(num)
Explanation:
Python is case sensitive.
num is a different variable name than Num
Q345 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics
Question 50Skipped
Q351 – Error Handling
When an exception occurs, we say that it has been:
dropped
Explanation
The term "dropped" is not commonly used in the context of exception handling in Python. When an exception occurs, it is either "raised" or "caught" by an appropriate exception handler.
thrown
Explanation
While the term "thrown" is commonly used in other programming languages to describe the occurrence of an exception, in Python, we typically use the term "raised" to indicate that an exception has occurred.
Correct answer
raised
Explanation
In Python, when an exception occurs, we use the term "raised" to indicate that the exception has been detected and the corresponding error-handling mechanism is triggered.
Overall explanation
Topic: exceptions
Explanation:
"In Python, exceptions can be handled using a try statement.
The critical operation which can raise an exception
is placed inside the try clause.
The code that handles the exceptions is written in the except clause."
https://www.programiz.com/python-programming/exception-handling
Q351 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 51Skipped
Q322 – Data Aggregates
What is the expected output of the following code?
- data = (1, 2, 4, 8)
- data = data[1:-1]
- data = data[0]
- print(data)
(2,)
Explanation
The output format (2,) indicates a tuple with a single element. However, since the code explicitly accesses and prints the element at index 0, the output will be the integer 2 without parentheses.
The code is erroneous.
Explanation
The code is not erroneous as it correctly accesses and prints the element at index 0 of the sliced tuple ‘data’. The expected output is the integer 2.
(2)
Explanation
The parentheses around the number 2 indicate a tuple with a single element. However, since the code explicitly accesses and prints the element at index 0, the output will be the integer 2 without parentheses.
Correct answer
2
Explanation
The code first slices the tuple ‘data’ from index 1 to the second-to-last element, resulting in a new tuple (2, 4). Then, it further slices this tuple to extract the element at index 0, which is 2. Therefore, the expected output is 2.
Overall explanation
Topics: tuple slicing tuple indexing
Try it yourself:
- data = (1, 2, 4, 8)
- data = data[1:-1]
- print(data) # (2, 4)
- data = data[0]
- print(data) # 2
Explanation:
The start of the slicing is index 1 (inclusive)
and the end is the last index -1 (exclusive).
That would be the numbers 2, 4
The first one of those is the 2
Q322 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 52Skipped
Q342 – Error Handling
What is the expected output of the following code?
-
def func():
-
try: -
print('Monday') -
finally: -
print('Friday') -
func()
Friday
Explanation
This choice is incorrect because the code will print ‘Monday’ inside the try block, but it will always execute the finally block, printing ‘Friday’ afterwards. Therefore, the output will be ‘Monday’ followed by ‘Friday’.
Monday
Explanation
This choice is incorrect because the code will print ‘Monday’ inside the try block, but it will always execute the finally block, printing ‘Friday’ afterwards. Therefore, the output will be ‘Monday’ followed by ‘Friday’.
The code is erroneous.
Explanation
This choice is incorrect because the code is not erroneous. It will print ‘Monday’ inside the try block and ‘Friday’ in the finally block, as expected.
None of these.
Explanation
This choice is incorrect because the expected output of the code is ‘Monday’ followed by ‘Friday’.
Correct answer
Monday
Friday
Explanation
The code will first print ‘Monday’ inside the try block, and then it will always execute the finally block, printing ‘Friday’ afterwards. This is the expected output of the code.
Friday
Monday
Explanation
This choice is incorrect because the code will print ‘Monday’ inside the try block, but it will always execute the finally block, printing ‘Friday’ afterwards. Therefore, the output will be ‘Monday’ followed by ‘Friday’.
Overall explanation
Topic: try finally
Try it yourself:
-
def func():
-
try: -
print('Monday') # Monday -
finally: -
print('Friday') # Friday -
func()
Explanation:
The function will try to execute print('Monday') and succeed.
The finally block always gets execute.
(There are similar questions Q127 and Q235.)
Q342 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 53Skipped
Q323 – Operators
The ** operator …
does not exist.
Explanation
The ** operator does exist in Python and it is used for exponentiation. It is a fundamental operator in Python and is widely used for mathematical calculations involving exponentiation.
performs floating-point multiplication.
Explanation
The ** operator does not perform floating-point multiplication in Python. It is solely used for exponentiation operations and does not have a functionality for performing floating-point multiplication.
performs duplicated multiplication.
Explanation
The ** operator does not perform duplicated multiplication in Python. It is specifically designed for exponentiation operations and does not have a functionality for duplicated multiplication.
Correct answer
performs exponentiation.
Explanation
The ** operator in Python is used for exponentiation, which means raising a number to the power of another number. It is a valid and commonly used operator for performing exponentiation operations in Python.
Overall explanation
Topic: exponentiation operator
Try it yourself:
print(2 ** 8) # 256
Explanation:
That’s why the operator is called exponentiation operator
Q323 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 54Skipped
Q339 – Basics
The folder created by Python used to store pyc files is named:
__pyc__
Explanation
The folder named pyc is not the correct folder created by Python to store pyc files. The correct folder is pycache, which is specifically used for storing compiled bytecode files for modules.
__pycfiles__
Explanation
The folder named pycfiles is not the correct folder created by Python to store pyc files. The correct folder is pycache, which is specifically used for storing compiled bytecode files for modules.
__cache__
Explanation
The folder named cache is not the correct folder created by Python to store pyc files. The correct folder is pycache, which is specifically used for storing compiled bytecode files for modules.
Correct answer
__pycache__
Explanation
The folder named pycache is created by Python to store compiled bytecode files (.pyc) for modules. These files are used to improve the performance of Python programs by caching the compiled versions of modules for faster execution.
Overall explanation
Topic: __pycache__
Try it yourself:
-
You have to run this to create the needed files:
-
functions = ”’
-
def func():
-
print('Hello world') -
”’
-
with open(‘functions.py’, ‘w’) as f:
-
f.write(functions) -
index = ”’
-
import functions
-
functions.func()
-
”’
-
with open(‘index.py’, ‘w’) as f:
-
f.write(index)
Explanation:
First please check, if the files index.py
and functions.py are created as expected.
Now run the file index.py and the folder __pycache__ should be created.
In case your Editor/IDE does not show the folder, check in your file system.
Inside the folder should be a file like functions.cpython-39.pyc
You can always delete the folder __pycache__
It will be created again the next time you run index.py
Q339 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics
Question 55Skipped
Q330 – I/O
Which of the following statements are true regarding the opening modes of a file?
Choose three.
When you open a file for reading,
if the file does not exist, the program will open an empty file.
Explanation
When opening a file for reading, if the file does not exist, the program will not open an empty file. Instead, an error will occur as the program cannot read from a non-existent file.
Correct selection
When you open a file for writing,
if the file does not exist, a new file is created.
Explanation
When opening a file for writing, if the file does not exist, a new file will be created because the program needs a file to write the data into.
Correct selection
When you open a file for writing,
if the file exists, the existing file is overwritten with the new file.
Explanation
When opening a file for writing, if the file exists, the existing file will be overwritten with the new file because the program is set to write new data into the file.
When you open a file for writing,
if the file does not exist, an error occurs.
Explanation
When opening a file for writing, if the file does not exist, an error will not occur. Instead, a new file will be created to write the data into.
Correct selection
When you open a file for reading,
if the file does not exist, an error occurs.
Explanation
When opening a file for reading, if the file does not exist, an error will occur because the program cannot read from a non-existent file.
Overall explanation
Topic: open() write() read() close()
Try it yourself:
-
When you open a file for reading,
-
if the file does not exist, an error occurs:
-
open(‘anyfile.txt’, ‘r’) # FileNotFoundError: …
-
When you open a file for writing,
-
if the file does not exist, a new file is created:
-
file = open(‘peoples.txt’, ‘w’)
-
file.write(‘Peter, Paul, Mary’)
-
file.close()
-
file = open(‘peoples.txt’, ‘r’)
-
print(file.read()) # Peter, Paul, Mary
-
file.close()
-
When you open a file for writing, if the file exists,
-
the existing file is overwritten with the new file:
-
file = open(‘peoples.txt’, ‘w’)
-
file.close()
-
file = open(‘peoples.txt’, ‘r’)
-
print(file.read()) # no output, because the file is empty
-
file.close()
Explanation:
If you want to read from a file, the file needs to exist.
If you want to write to a file, the file does not have to exist.
It will be created, if it does not exist.
If the file already exists, it will be overwritten.
If you do not want to loose the old content of the file,
you can use the append mode: open('myfile.txt', 'a')
That will append the new content at the end of the file.
Q330 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 56Skipped
Q315 – Data Types
You want to print each name of the list on a new line.
data = ['Peter', 'Paul', 'Mary', 'Jane']
Which statement will you use?
print(data.join('\n'))
Explanation
The join method is used to concatenate elements of a list with a specified separator. However, in this choice, the syntax is incorrect as join should be called on the separator ('\n') rather than on the list data.
Correct answer
print('\n'.join(data))
Explanation
The correct choice uses the join method to concatenate the elements of the list data with a newline character \n in between each element. This will print each name on a new line as desired.
print(data.concatenate('\n'))
Explanation
There is no concatenate method in Python for lists. This choice is incorrect as it does not provide a valid method to concatenate the elements of the list with a newline character.
print(data.join('%s\n', names))
Explanation
The join method should be called on the separator ('\n') to join the elements of the list data. Additionally, the names variable is not defined in the given context, making this choice incorrect.
Overall explanation
Topics: join() list string
Try it yourself:
-
data = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]
-
print(‘\n’.join(data))
-
"""
-
Peter
-
Paul
-
Mary
-
Jane
-
"""
-
print(data.join(‘\n’)) # AttributeError: …
-
print(data.concatenate(‘\n’)) # AttributeError: …
-
print(data.join(‘%s\n’, names)) # AttributeError: …
Explanation:
join() is a string method.
The string is the separator
and the list (or any other iterable) is passed as argument.
The elements of the list will then be joined into a string
using the original string as separator.
Q315 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 57Skipped
Q348 – Basics
You develop a Python application for your company.
You want to add notes to your code so other team members will understand it.
What should you do?
Place the notes before the first line of code separated by a blank line.
Explanation
Placing notes before the first line of code separated by a blank line in Python code does not create comments. Comments in Python should be placed on the same line after the # sign or in a multiline comment block using triple quotes. Comments before the first line of code are not considered valid comments in Python.
Correct answer
Place the notes after the # sign on any line.
Explanation
Placing notes after the # sign on any line in Python code is the correct way to add comments. The # sign indicates a single-line comment, and anything after it on the same line is considered a comment and will not be executed as code.
Place the notes inside of parentheses on any line.
Explanation
Placing notes inside parentheses on any line in Python code does not create comments. Instead, it will be treated as part of the code and may cause syntax errors or unexpected behavior.
Place the notes after the last line of code separated by a blank line.
Explanation
Placing notes after the last line of code separated by a blank line in Python code does not create comments. Comments in Python should be placed on the same line after the # sign or in a multiline comment block using triple quotes.
Overall explanation
Topics: comments
Try it yourself:
-
Example of a whole line as a comment
- print(‘Hello’) # Example of the rest of a line as a comment
Explanation:
With the # sign you can comment out a whole line
or you can comment out the rest of a line.
Q348 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics