Python ITS-303 Test Exam VI (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
Q606 – Data Aggregates
What is the expected output of the following code?
-
data = {1: 0, 2: 1, 3: 2, 0: 1}
-
x = 0
-
for _ in range(len(data)):
-
x = data[x] -
print(x)
Correct answer
0
Explanation
The code starts with x=0 and then iterates through the ‘data’ dictionary using the values of ‘x’ as keys. Since the value of ‘x’ changes based on the key-value pairs in the ‘data’ dictionary, the final value of ‘x’ will be 0, which is the initial value.
2
Explanation
The code iterates through the ‘data’ dictionary using the values of ‘x’ as keys. However, the final value of ‘x’ is not 2, as the value of ‘x’ changes based on the key-value pairs in the ‘data’ dictionary.
1
Explanation
The code iterates through the ‘data’ dictionary using the values of ‘x’ as keys. However, the final value of ‘x’ is not 1, as the value of ‘x’ changes based on the key-value pairs in the ‘data’ dictionary.
The code is erroneous.
Explanation
The code is not erroneous as it runs without any syntax errors. It iterates through the ‘data’ dictionary using the values of ‘x’ as keys and assigns the final value of ‘x’ based on the key-value pairs in the ‘data’ dictionary.
Overall explanation
Topics: dictionary for range() len()
Try it yourself:
-
data = {1: 0, 2: 1, 3: 2, 0: 1}
-
x = 0
-
for _ in range(len(data)):
-
print(x) # 0 - 1 - 0 - 1 -
x = data[x] -
print(x) # 0
Explanation:
The dictionary has four elements
and therefore the for loop has four iterations.
The value of x gets changed four times: 0 -> 1 -> 0 -> 1 -> 0
And in the end the value again is 0
Q606 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 2Skipped
Q629 – Control Flow
Consider the following code.
- x = 42
- y = 7
- data = "I’m gonna make him an offer he can’t refuse."
Which of the following expressions will evaluate to 19?
19 if None else x / y
Explanation
The expression 19 if None else x / y will not evaluate to 19 because the condition None is considered as False in Python, so the expression will result in the division of x by y, which is not equal to 19.
data.rfind('an') if data else None
Explanation
The expression data.rfind('an') if data else None will not evaluate to 19 because the rfind() method returns the highest index of the substring ‘an’ in the given string. In this case, ‘an’ is found at index 19, but the rfind() method returns the highest index, which is not 19.
7 if len(data) > 19 else 6
Explanation
The expression 7 if len(data) > 19 else 6 will not evaluate to 19 because it checks if the length of the string data is greater than 19. If the condition is False, it will return 6, not 19.
Correct answer
data.find('an') if data else None
Explanation
The expression data.find('an') if data else None will evaluate to 19 because the find() method returns the index of the first occurrence of the specified value in the string. In this case, ‘an’ is found in the string "I’m gonna make him an offer he can’t refuse." at index 19.
Overall explanation
Topics: conditional expression (if else) find() rfind() len()
None division operator
Try it yourself:
-
x = 42
-
y = 7
-
data = "I’m gonna make him an offer he can’t refuse."
-
print(data.find(‘an’) if data else None) # 19
-
print(19 if None else x / y) # 6.0
-
print(data.rfind(‘an’) if data else None) # 32
-
print(7 if len(data) > 19 else 6) # 7
Explanation:
The find() method is looking for the first occurrence of a string in a string
and returns the index, where this string is starting.
In this case 'an' starts in data at index 19
rfind() looks from the right and will find the last occurrence.
In this case the 'an' in "can't" at index 32
None evaluates to False and therefore the else clause executes.
And yes, the string is longer than 19 but anyway 7 and 6 are both not 19
Q629 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 3Skipped
Q605 – Data Aggregates
What is the expected output of the following code?
-
data = {}
-
data[‘2’] = [1, 2]
-
data[‘1’] = [3, 4]
-
for i in data.keys():
-
print(data[i][1], end=' ')
Correct answer
2 4
Explanation
The code creates a dictionary ‘data’ with keys ‘2’ and ‘1’, each associated with a list of integers. The loop iterates over the keys of the dictionary and prints the second element of each list. Therefore, the expected output is ‘2 4’.
3 1
Explanation
This choice is incorrect because it does not match the expected output of the code. The code prints the second element of each list associated with the keys ‘2’ and ‘1’, which are 2 and 4 respectively, not 3 and 1.
4 2
Explanation
This choice is incorrect because it does not match the expected output of the code. The code prints the second element of each list associated with the keys ‘2’ and ‘1’, which are 2 and 4 respectively, not 4 and 2.
1 3
Explanation
This choice is incorrect because it does not match the expected output of the code. The code prints the second element of each list associated with the keys ‘2’ and ‘1’, which are 2 and 4 respectively, not 1 and 3.
Overall explanation
Topics: dictionary for keys() print() with end parameter
Try it yourself:
-
data = {}
-
data[‘2’] = [1, 2]
-
data[‘1’] = [3, 4]
-
for i in data.keys():
-
print(data[i][1], end=' ') # 2 4 -
print()
-
print(data) # {‘2’: [1, 2], ‘1’: [3, 4]}
Explanation:
The dictionary does not automatically get sorted.
The index 2 was put in first.
The index 2 will be read first.
The keys() method reads out the keys.
In the first iteration off the for loop i is going to be 2
and in the second iteration i is going to be 1
Q605 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 4Skipped
Q626 – Data Aggregates
What snippet would you insert in the line indicated below to print
The highest number is 10 and the lowest number is 1. to the monitor?
-
data = [10, 2, 1, 7, 5, 6, 4, 3, 9, 8]
-
insert your code here
-
print(
-
('The highest number is {} ' + -
'and the lowest number is {}.').format(high, low) -
)
-
def find_high_low(nums):
-
nums.sort() -
return nums[len(nums)], nums[0] -
high, low = find_high_low(data)
Explanation
This choice incorrectly tries to access the highest number in the sorted list by using the length of the list as an index, which results in an index out of range error. It does correctly access the lowest number, but the incorrect method for accessing the highest number makes this choice invalid for achieving the desired output.
None of the above.
Explanation
This choice is incorrect as it states that none of the above choices are valid, but choice A is indeed the correct choice for achieving the desired output of printing the highest and lowest numbers from the given list.
-
def find_high_low(nums):
-
nums.sort() -
return nums[0], nums[-1] -
high, low = find_high_low(data)
Explanation
This choice correctly defines a function named find_high_low that sorts the input list of numbers and returns the lowest and highest numbers. By calling this function with the data list, the variables high and low are assigned the highest and lowest numbers, respectively, which can then be used to format and print the desired output.
Correct answer
-
def find_high_low(nums):
-
nums.sort() -
return nums[-1], nums[0] -
high, low = find_high_low(data)
Explanation
This choice correctly defines a function named find_high_low that sorts the input list of numbers and returns the highest and lowest numbers. By calling this function with the data list, the variables high and low are assigned the highest and lowest numbers, respectively, which can then be used to format and print the desired output.
Overall explanation
Topics: def sort() list format()
return a tuple tuple assignment
Try it yourself:
-
data = [10, 2, 1, 7, 5, 6, 4, 3, 9, 8]
-
def find_high_low(nums):
-
nums.sort() -
print(nums) -
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] -
return nums[-1], nums[0] -
# return nums[len(nums)], nums[0] -
# IndexError: list index out of range -
# return nums[0], nums[-1] -
# high and low are interchanged -
high, low = find_high_low(data)
-
print(
-
('The highest number is {} ' + -
'and the lowest number is {}.').format(high, low) -
)
-
The highest number is 10 and the lowest number is 1.
Explanation:
The built-in function sort() will sort the list of integers in-place.
Then index -1 will take the last and the index 0 the first element,
which are the highest and the lowest.
Q626 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 5Skipped
Q619 – Functions
What is the expected output of the following code?
-
def func(n):
-
s = '*' -
for i in range(n): -
s += s -
yield s -
for x in func(2):
-
print(x, end='')
**
Explanation
The output ** is incorrect because the loop iterates twice and concatenates the string '*' with itself in each iteration. Therefore, the final output will be longer than two asterisks.
Correct answer
****
Explanation
The code defines a function func(n) that initializes a string s with a single asterisk '*'. It then iterates over the range of n (which is 2 in this case) and concatenates s with itself in each iteration. Finally, it yields the resulting string. In this case, the output will be **** as the string '*' is concatenated with itself twice.
*
Explanation
The output * is incorrect because the loop iterates twice and concatenates the string '*' with itself in each iteration. Therefore, the final output will be longer than a single asterisk.
***
Explanation
The output *** is incorrect because the loop iterates twice and concatenates the string '*' with itself in each iteration. Therefore, the final output will be longer than three asterisks.
Overall explanation
Topics: def yield for range() print with end parameter
Try it yourself:
-
def func(n):
-
s = '*' -
for i in range(n): -
s += s -
yield s -
# return s -
for x in func(2):
-
print(x, end='') # **** -
print()
-
print(func(2)) # <generator object func at …>
-
print(list(func(2))) # [‘****’]
-
s = ‘*’
-
s += s # s = s + s -> s = ‘‘ + ‘‘ -> ‘**’
-
s += s # s = s + s -> s = ‘‘ + ‘‘ -> ‘****’
-
print(s) # ****
Explanation:
The generator function will produce a generator object with one element: '****'
The for loop will iterate through that string and print every single character.
The snippet would have the same output if yield gets interchanged with return
If you only have one yield keyword, it belongs in a loop.
Q619 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 6Skipped
Q645 – Control Flow
Consider the following code.
- for i in range(5, 0, ???):
-
print(i, i, i, i, i)
What would you insert instead of ??? so that the program
prints the following pattern to the monitor?
- 5 5 5 5 5
- 4 4 4 4 4
- 3 3 3 3 3
- 2 2 2 2 2
- 1 1 1 1 1
0
Explanation
By inserting 0 in place of ???, the code will not iterate as the range function requires a non-zero step size. This will not produce the desired pattern as the loop will not execute.
1
Explanation
By inserting 1 in place of ???, the code will iterate over the range from 5 to 0 (exclusive) with a step size of 1. This will result in the loop not executing as the starting value is greater than the ending value when using a positive step size.
None
Explanation
By inserting None in place of ???, the code will raise a TypeError as the range function requires an integer value for the step size parameter. This will result in an error and the desired pattern will not be printed.
Correct answer
-1
Explanation
By inserting -1 in place of ???, the code will iterate over the range from 5 to 0 (exclusive) with a step size of -1. This will result in the desired pattern being printed to the monitor as the loop decrements from 5 to 1.
Overall explanation
Topics: range() for
Try it yourself:
-
for i in range(5, 0, -1):
-
print(i, i, i, i, i) -
print(‘—–‘)
-
for i in range(5, 0, None): # TypeError: …
-
print(i, i, i, i, i)
-
print(‘—–‘)
-
for i in range(5, 0, 0): # ValueError: …
-
print(i, i, i, i, i)
-
print(‘—–‘)
-
for i in range(5, 0, 1):
-
print(i, i, i, i, i) -
print(list(range(5, 0, 1))) # []
Explanation:
The third argument of the range() function can neither be None nor 0
And if the third argument if a positive number,
the start argument (here 5) has to be lower than the end argument (here 0).
Otherwise range() will return an empty list
Q645 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 7Skipped
Q604 – Data Aggregates
What is the expected output of the following code?
-
list = [‘Peter’, ‘Paul’, ‘Mary’]
-
def list(data):
-
del data[1] -
data[1] = 'Jane' -
return data -
print(list(list))
['Peter'**,** 'Jane'**,** 'Mary']
Explanation
The code deletes the element at index 1 (‘Paul’) from the list, replaces it with ‘Jane’, and then returns the modified list. The output would be [‘Peter’, ‘Jane’, ‘Mary’].
['Peter'**,** 'Jane']
Explanation
The code attempts to delete the element at index 1 (‘Paul’) from the list and replace it with ‘Jane’. However, since the list is modified in place, the output would be [‘Peter’, ‘Jane’].
Correct answer
The code is erroneous.
Explanation
The code is erroneous because it redefines the built-in list function with a variable name ‘list’. This can lead to unexpected behavior and errors in the code.
['Paul'**,** 'Mary'**,** 'Jane']
Explanation
The code deletes the element at index 1 (‘Paul’) from the list, replaces it with ‘Jane’, and then returns the modified list. The output would not include ‘Paul’ and would be [‘Peter’, ‘Jane’, ‘Mary’].
Overall explanation
Topics: list def del
Try it yourself:
-
list = [‘Peter’, ‘Paul’, ‘Mary’]
-
def func(data):
-
def list(data):
-
del data[1] -
data[1] = 'Jane' -
return data -
print(func(list)) # [‘Peter’, ‘Jane’]
-
print(list(list)) # TypeError: …
Explanation:
The list and the function can not have the same name.
The function gets passed the itself and then naturally the del does not work.
Q604 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 8Skipped
Q617 – Functions
What is the expected output of the following code?
-
def func(x, y, z):
-
return x + 4 * y + 5 * z -
print(func(1, z=2, y=3))
The code is erroneous.
Explanation
The code is not erroneous. The function func is defined correctly, and when calling func(1, z=2, y=3), it will return a valid output. The code will not produce an error, and the expected output is 23.
Correct answer
23
Explanation
The function func takes three parameters x, y, and z, and returns the result of x + 4 * y + 5 * z. When calling the function func(1, z=2, y=3), the values of x, y, and z are 1, 3, and 2 respectively. Substituting these values into the function, the output will be 1 + 4 * 3 + 5 * 2 = 1 + 12 + 10 = 23.
80
Explanation
The function func computes the result of x + 4 * y + 5 * z. However, when calling func(1, z=2, y=3), the values of x, y, and z are 1, 3, and 2 respectively. Substituting these values into the function, the output will be 1 + 4 * 3 + 5 * 2 = 1 + 12 + 10 = 23. Therefore, the expected output is 23, not 80.
24
Explanation
The function func calculates the result of x + 4 * y + 5 * z. In this case, when calling func(1, z=2, y=3), the values of x, y, and z are 1, 3, and 2 respectively. Substituting these values into the function, the output will be 1 + 4 * 3 + 5 * 2 = 1 + 12 + 10 = 23. Therefore, the expected output is 23.
Overall explanation
Topics: def keyword argument addition operator
multiplication operator operator precedence
Try it yourself:
-
def func(x, y, z):
-
return x + 4 * y + 5 * z -
print(func(1, z=2, y=3)) # 23
-
print(1 + 4 * 3 + 5 * 2) # 23
-
print(1 + (4 * 3) + (5 * 2)) # 23
-
print(1 + 12 + 10) # 23
-
print(23) # 23
Explanation:
Here you have to watch, that z is before y in the function call.
The rest is operator precedence
multiplication before addition.
Q617 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 9Skipped
Q648 – Control Flow
You are designing a decision structure
to convert a student’s numeric grade to a letter grade.
The program must assign a letter grade as specified as followed:
- 90 through 100 -> A
- 80 through 89 -> B
- 70 through 79 -> C
- 65 through 69 -> D
- 0 through 64 -> F
For example, if the user enters a 90
the output should be Your letter grade is A
Likewise, if a user enters an 89
the output should be Your letter grade is B
-
Letter Grade Converter
- grade = int(input(‘Enter a numeric grade:’))
-
Line-3
-
letter_grade = 'A' -
Line-5
-
letter_grade = 'B' -
Line-7
-
letter_grade = 'C' -
Line-9
-
letter_grade = 'D' - else:
-
letter_grade = 'F' - print(‘Your letter grade is:’, letter_grade)
Which of the following should you insert on
Line-3, Line-5, Line-7 and Line-9?
- if grade < 90: # Line-3
- elif grade < 80: # Line-5
- elif grade < 70: # Line-7
- elif grade < 65: # Line-9
Explanation
Using if statements with less than comparisons instead of less than or equal to will exclude the grades that are exactly 90, 80, 70, or 65 from being assigned the correct letter grades. This approach will lead to incorrect conversions of numeric grades to letter grades for those specific grades.
- if grade > 90: # Line-3
- elif grade > 80: # Line-5
- elif grade > 70: # Line-7
- elif grade > 65: # Line-9
Explanation
Using if statements with greater than comparisons instead of greater than or equal to will not cover the edge cases where the grade is exactly 90, 80, 70, or 65. This approach may lead to incorrect letter grade assignments for those specific grades.
- if grade <= 90: # Line-3
- elif grade <= 80: # Line-5
- elif grade <= 70: # Line-7
- elif grade <= 65: # Line-9
Explanation
Using if statements with less than or equal to comparisons will not correctly assign the letter grades according to the specified ranges. This approach will result in inaccurate conversions of numeric grades to letter grades, as it does not consider the upper bounds of each grade range.
Correct answer
- if grade >= 90: # Line-3
- elif grade >= 80: # Line-5
- elif grade >= 70: # Line-7
- elif grade >= 65: # Line-9
Explanation
Using if statements with greater than or equal to comparisons ensures that the correct letter grade is assigned based on the specified grade ranges. This approach covers all possible numeric grade scenarios and accurately converts them to the corresponding letter grades.
Overall explanation
Topics: if elif else input() int()
Try it yourself:
-
grade = int(input(‘Enter a numeric grade:’))
-
grade = 90 # A
-
grade = 89 # B
-
if grade >= 90: # Line-3
-
letter_grade = 'A' -
elif grade >= 80: # Line-5
-
letter_grade = 'B' -
elif grade >= 70: # Line-7
-
letter_grade = 'C' -
elif grade >= 65: # Line-9
-
letter_grade = 'D' -
else:
-
letter_grade = 'F' -
print(‘Your letter grade is:’, letter_grade)
Explanation:
It is 90 through 100 and therefore: grade >= 90
It is 80 through 89 and therefore: grade >= 80
It is 70 through 79 and therefore: grade >= 70
It is 65 through 69 and therefore: grade >= 65
And if the grade is 64 or below the else clause is executed.
Q648 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 10Skipped
Q616 – Control Flow
How many stars will the following code print to the monitor?
- data = [[x for x in range(3)] for y in range(3)]
- for i in range(3):
-
for j in range(3): -
if data[i][j] % 2 != 0: -
print('*')
six
Explanation
The code only prints ‘‘ when the number in the matrix is odd. There are three odd numbers in the matrix (1, 1, and 1), so the code will print ‘‘ six times.
nine
Explanation
The code only prints ‘‘ when the number in the matrix is odd. Since there are three odd numbers in the matrix (1, 1, and 1), the code will print ‘‘ three times, not nine.
zero
Explanation
The code only prints ‘‘ when the number in the matrix is odd. Since all the numbers in the matrix are even (0, 1, 2), the code will not print any ‘‘ to the monitor.
Correct answer
three
Explanation
The code creates a 3×3 matrix filled with numbers from 0 to 2. It then iterates over each element in the matrix and checks if the number is odd. Since there are three odd numbers in the matrix (1, 1, and 1), the code will print ‘*’ three times.
Overall explanation
Topics: list comprehension for if list indexing
modulus operator not equal to operator
Try it yourself:
- data = [[x for x in range(3)] for y in range(3)]
- print(data) # [[0, 1, 2], [0, 1, 2], [0, 1, 2]]
- for i in range(3):
-
for j in range(3): -
if data[i][j] % 2 != 0: -
print('*') # * * *
Explanation:
The list comprehension produces a two-dimensional list
The three elements of the outer list also each have three elements:
the numbers 0, 1, 2
x % 2 != 0 tests, if x is odd.
The two for loops make it happen, that every of the nine elements is tested.
There is three times the number 1
Those are the odd ones.
Therefore three stars get printed.
Q616 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 11Skipped
Q615 – Operators
Which of the following statements are correct?
Choose two.
Correct selection
True + 1 evaluates to 2
Explanation
The statement "True + 1" evaluates to 2 because in Python, the boolean value True is equivalent to the integer value 1 when used in arithmetic operations.
7 + False evaluates to False
Explanation
The statement "7 + False" does not evaluate to False. In Python, False is equivalent to the integer value 0, so the expression would evaluate to 7.
Correct selection
True or False evaluates to True
Explanation
The statement "True or False" evaluates to True because the "or" operator returns True if at least one of the operands is True.
True and False evaluates to True
Explanation
The statement "True and False" evaluates to False because the "and" operator returns True only if both operands are True. Since False is one of the operands, the result is False.
type('') returns <class 'bool'>
Explanation
The statement "type(”)" does not return . The type() function in Python returns the type of the object passed as an argument, and an empty string (”) is of type str, not bool.
Overall explanation
Topics: and boolean identity operator type()
Try it yourself:
-
print(True or False == True) # True
-
print(True + 1 == 2) # True
-
print(7 + False == False) # False
-
print(7 + False) # 7
-
print(type(”)) # <class ‘str’> -> False
-
print(type(”)) # <class ‘str’>
-
print(True and False == True) # False
-
print(True and False) # False
Explanation:
An empty string is still a string
If you calculate with a boolean, True becomes 1 and False becomes 0
Q615 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 12Skipped
Q625 – Data Types
Consider the following code.
- data = eval(input(‘Input: ‘))
- print(‘Output:’, data)
Which of the inputs below would produce the specified output?
Both are correct.
Explanation
Both inputs are not correct. Only input A will produce the specified output of [1, 4, 9]. Input B will produce the output ‘Hello Python’.
Correct answer
- Input: [x**2 for x in range(1, 4)]
- Output: [1, 4, 9]
Explanation
The input [x**2 for x in range(1, 4)] is a list comprehension that generates a list of squared values for x ranging from 1 to 3. When evaluated, this input will produce the output [1, 4, 9] as the squared values of 1, 2, and 3.
None of the above.
Explanation
None of the above inputs will produce the specified output. Input A will produce [1, 4, 9], and input B will produce ‘Hello Python’.
- Input: Hello Python
- Output: Hello Python
Explanation
The input ‘Hello Python’ is a string literal. When evaluated, this input will produce the output ‘Hello Python’ as it is a simple string that will be printed as is.
Overall explanation
Topics: input() eval() list comprehension
Try it yourself:
-
data = eval(input(‘Input: ‘))
-
data = eval(‘[x**2 for x in range(1, 4)]’)
-
print(‘Input: [x**2 for x in range(1, 4)]’)
-
print(‘Output:’, data) # Output: [1, 4, 9]
-
print(‘———-‘)
-
If there is a string in the input,
-
it would need quotation marks:
-
data = eval(input(‘Input: ‘))
-
data = eval(‘Hello Python’) # SyntaxError: …
-
data = eval(input(‘Input: ‘))
-
data = eval(‘"Hello Python"’)
-
print(‘Input: "Hello Python"’)
-
print(‘Output:’, data) # Hello Python
Explanation:
This question is about the eval() function.
It will evaluate the given code inside of the passed string
Remember input() always returns a string
That works with a number and even the list comprehension.
But to make it work with a string you need to put extra quotation marks around it.
Q625 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 13Skipped
Q653 – I/O
You want to access the test.txt file and retrieve each line in it.
- file = open(‘test.txt’)
-
insert code here
- file.close()
Which option will you use?
(Select all that apply.)
Correct selection
- for f in file:
-
print(f)
Explanation
Using a for loop with for f in file: will iterate over each line in the file and print them one by one. This is a valid way to access and retrieve each line in the ‘test.txt’ file.
Correct selection
print(file.readlines())
Explanation
The readlines() method reads all the lines in the file and returns them as a list. Using print(file.readlines()) will print all the lines in the ‘test.txt’ file.
print(file.lines())
Explanation
There is no method lines() available for file objects in Python. This choice is incorrect as it does not represent a valid method to access and retrieve each line in the ‘test.txt’ file.
print(readlines(file))
Explanation
There is no built-in function readlines() in Python that takes a file object as an argument. This choice is incorrect as it does not represent a valid method to access and retrieve each line in the ‘test.txt’ file.
Correct selection
print(file.read())
Explanation
The read() method reads the entire content of the file as a string. Using print(file.read()) will print the entire content of the ‘test.txt’ file.
print(file.readlines(:)
Explanation
The syntax file.readlines(:) is incorrect as the colon : is not used in the correct way. This choice is incorrect as it does not represent a valid method to access and retrieve each line in the ‘test.txt’ file.
print(read.file(test.txt))
Explanation
The syntax read.file(test.txt) is incorrect and does not represent a valid method to access and retrieve each line in the ‘test.txt’ file. This choice is incorrect.
Overall explanation
Topic: open() for readlines() read() close()
Try it yourself:
-
First you have to run this to create the file:
-
with open(‘test.txt’, ‘w’) as f:
-
f.write('Hello world') -
file = open(‘test.txt’)
-
print(file.readlines()) # [‘Hello world’]
-
file.close()
-
file = open(‘test.txt’)
-
print(file.read()) # Hello world
-
file.close()
-
file = open(‘test.txt’)
-
for f in file:
-
print(f) # Hello world -
file.close()
Explanation:
These are your three options.
The read() function reads the whole file
and returns a string.
The readlines() function also reads the whole file
and returns a list of the single lines.
And you can also iterate through the file object.
In each iteration you will get one line.
Q653 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 14Skipped
Q633 – Modules
You are creating a function that manipulates a number.
The function has the following requirements:
A float is passed into the function.
The function must take the absolute value of the float.
Any decimal points after the integer must be removed.
Which math functions should you use?
Each correct answer is part of the solution.
Choose two.
math.ceil(x)
Explanation
The math.ceil(x) function returns the smallest integer greater than or equal to x, which is not suitable for removing the decimal points after the integer in a float. This function is not necessary for the requirements of the function.
math.fmod(x)
Explanation
The math.fmod(x) function returns the remainder of x divided by y. This function is not relevant to the requirements of the function, which involve taking the absolute value of the float and removing decimal points.
math.frexp(x)
Explanation
The math.frexp(x) function returns the mantissa and exponent of x as a pair. This function is not relevant to the requirements of the function, which only involve taking the absolute value of the float and removing decimal points.
Correct selection
math.floor(x)
Explanation
The math.floor(x) function returns the largest integer less than or equal to x, effectively removing any decimal points after the integer. This is useful for removing the decimal part of a float.
Correct selection
math.fabs(x)
Explanation
The math.fabs(x) function returns the absolute value of x, which ensures that the number is positive regardless of its original sign. This is necessary for taking the absolute value of the float passed into the function.
Overall explanation
Topics: math.floor() math.fabs() math.frexp()
math.fmod() math.ceil()
Try it yourself:
-
def get_absolute_integer(num):
-
import math -
return math.floor(math.fabs(num)) -
print(get_absolute_integer(-23.42)) # 23
-
import math
-
print(math.floor(4.9)) # 4
-
print(math.fabs(-4)) # 4.0
-
print(math.frexp(4)) # (0.5, 3)
-
print(math.fmod(7, 2)) # 1.0
-
print(math.ceil(3.1)) # 4
Explanation:
It is said "Each correct answer is part of the solution. Choose two."
This means that you need two of the functions in the answers to solve the problem.
In this case, you need floor() & fabs().
Neither of them is the complete solution.
They are both just part of the solution.
fabs() returns the float value of the absolute value.
floor() rounds a number down to the nearest integer
Those are the two you need here.
The others are of no use here:
fmod() returns the float value of the remainder.
ceil() rounds a number up to the nearest integer
frexp() returns the mantissa and the exponent.
Q633 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 15Skipped
Q649 – Control Flow
The ABC company needs a way to find the count of particular letters
in their publications to ensure that there is a good balance.
It seems that there have been complaints about overuse of the letter e
You need to create a function to meet the requirements.
-
Function accepts a list of words from a file,
-
and a letter to search for.
-
Returns count of the words containing that letter.
-
def count_letter(letter, word_list):
-
count = 0 -
for ???: -
if ???: -
count += 1 -
return count -
word_list = []
-
word_list is populated from a file. Code not shown.
-
letter = input(‘Which letter would you like to count?’)
-
letter_count = count_letter(letter, word_list)
-
print(‘There are’, letter_count, ‘words with the letter’, letter)
What would you insert instead of ??? and ???
- word is word_list
- letter in word
Explanation
This choice is incorrect because it suggests checking if the word is in the word_list and if the letter is in the word, which is not the correct way to iterate over the word_list and search for the specified letter.
- word_list in word
- word in letter
Explanation
This choice is incorrect because it suggests checking if the word_list is in the word, which is not the correct way to iterate over the word_list and search for the specified letter.
Correct answer
- word in word_list
- letter in word
Explanation
The correct choice is to iterate over each word in the word_list and check if the letter is in that word. This approach ensures that each word is evaluated for the presence of the specified letter.
- word in word_list
- word in letter
Explanation
This choice is incorrect because it suggests checking if the word is in the letter, which is not the correct way to iterate over the word_list and search for the specified letter.
- word in word_list
- letter is word
Explanation
This choice is incorrect because it suggests checking if the word is in the word_list and if the letter is the word, which is not the correct way to iterate over the word_list and search for the specified letter.
- word_list in word
- letter in word
Explanation
This choice is incorrect because it suggests checking if the word_list is in the word, which is not the correct way to iterate over the word_list and search for the specified letter.
Overall explanation
Topics: for if def list input()
Try it yourself:
-
Function accepts a list of words from a file,
-
and a letter to search for.
-
Returns count of the words containing that letter.
-
def count_letter(letter, word_list):
-
count = 0 -
for word in word_list: -
if letter in word: -
count += 1 -
return count -
word_list = []
-
word_list is populated from a file. Code not shown.
-
word_list = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’, ‘Steve’]
-
letter = input(‘Which letter would you like to count?’)
-
letter = ‘e’
-
letter_count = count_letter(letter, word_list)
-
print(‘There are’, letter_count, ‘words with the letter’, letter)
-
There are 3 words with the letter e
Explanation:
for word in word_list:
In every iteration of the for loop,
one element of word_list will be assigned to word
if letter in word:
if the passed letter is in the word
the counter is increased by one.
Q649 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 16Skipped
Q638 – Error Handling
What is the expected output of the following code?
- try:
-
raise Exception - except:
-
print('c') - except BaseException:
-
print('a') - except Exception:
-
print('b')
c
Explanation
This choice is incorrect because the except block for the generic Exception is not the first one to be executed due to the incorrect order of except blocks. As a result, ‘c’ will not be printed.
Correct answer
The code is erroneous.
Explanation
The code is erroneous because the order of the except blocks is incorrect. The more specific exceptions should come before the more general ones. In this case, the except block for BaseException should come before the except block for Exception.
b
Explanation
This choice is incorrect because the except block for Exception is not the first one to be executed due to the incorrect order of except blocks. As a result, ‘b’ will not be printed.
a
Explanation
This choice is incorrect because the except block for BaseException is not the first one to be executed due to the incorrect order of except blocks. As a result, ‘a’ will not be printed.
Overall explanation
Topics: try except Exception BaseException
Try it yourself:
- try:
-
raise Exception - except: # SyntaxError: default ‘except:’ must be last
-
print('c') - except BaseException:
-
print('a') - except Exception:
-
print('b')
Explanation:
The unnamed except block has to be the last except block.
Q638 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 17Skipped
Q632 – Modules
You are writing an application that uses the sqrt function.
The program must reference the function using the name squareRoot
You need to import the function.
Which code segment should you use?
import sqrt from math as squareRoot
Explanation
This code segment incorrectly uses the import statement with the function name before the module name, which is not the correct syntax for importing functions in Python. The ‘from’ keyword is also used incorrectly in this choice.
from math.sqrt as squareRoot
Explanation
This code segment incorrectly uses dot notation to import the sqrt function from the math module, which is not the correct syntax for importing functions in Python. The ‘as’ keyword is also used incorrectly in this choice.
import math.sqrt as squareRoot
Explanation
This code segment attempts to import the sqrt function from the math module using dot notation, which is not the correct syntax for importing functions from modules in Python. The ‘as’ keyword is also used incorrectly in this choice.
Correct answer
from math import sqrt as squareRoot
Explanation
This code segment correctly imports the sqrt function from the math module and assigns it the name squareRoot using the ‘as’ keyword. This allows the program to reference the function as squareRoot throughout the application.
Overall explanation
Topics: from import math.sqrt
Try it yourself:
-
from math import sqrt as squareRoot
-
print(squareRoot(16)) # 4.0
-
import math.sqrt as squareRoot # ModuleNotFoundError: …
-
import sqrt from math as squareRoot # SyntaxError: …
-
from math.sqrt as squareRoot # SyntaxError: …
Explanation:
The order is from big to small:
from module import entity as alias
Q632 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 18Skipped
Q644 – Data Types
What is the expected output of the following code?
print('x'**,** 'y'**,** 'z'**,** sep='sep')
xyz
Explanation
This choice does not match the expected output because the ‘sep’ parameter is set to ‘sep’, which will be used as the separator between the values ‘x’, ‘y’, and ‘z’.
x y z
Explanation
This choice does not match the expected output because the ‘sep’ parameter is set to ‘sep’, which will be used as the separator between the values ‘x’, ‘y’, and ‘z’.
xsepysepzsep
Explanation
This choice does not match the expected output because the ‘sep’ parameter is set to ‘sep’, which will be used as the separator between the values ‘x’, ‘y’, and ‘z’. Additionally, there is an extra ‘sep’ at the end of the output, which is not included in the original code.
Correct answer
xsepysepz
Explanation
The ‘sep’ parameter in the print function specifies the separator between the values to be printed. In this case, ‘sep’ is set to ‘sep’, so the output will be ‘x’ + ‘sep’ + ‘y’ + ‘sep’ + ‘z’, which results in ‘xsepysepz’.
Overall explanation
Topic: print() with sep parameter
Try it yourself:
- print(‘x’, ‘y’, ‘z’, sep=’sep’) # xsepysepz
- print(‘x’, ‘y’, ‘z’) # x y z
- print(‘x’, ‘y’, ‘z’, sep=”) # xyz
Explanation:
The print() function has the sep parameter
for the separation BETWEEN the arguments.
Its default value is one space.
Q644 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 19Skipped
Q640 – Data Types
The following code reads two numbers.
Which of the following is the correct input for the code?
- x, y = eval(input(‘Enter two numbers: ‘))
- print(x)
- print(y)
None of the above.
Explanation
None of the above choices are correct except for Choice A, which provides the correct input format of two numbers separated by a comma for the code to read and assign to x and y variables.
Correct answer
3, 4
Explanation
The input format "3, 4" is correct for the code as it provides two numbers separated by a comma, which can be evaluated by the eval() function to assign them to x and y variables.
3 4
Explanation
This input format "3 4" does not contain a comma to separate the two numbers, so the eval() function will not be able to correctly assign them to x and y variables as expected in the code.
<pre>3 4</pre>
Explanation
The input format "
3 4
" is not valid for the code as it contains HTML tags that are not part of the expected input format. The eval() function will not be able to evaluate this input correctly.
Overall explanation
Topics: eval() input() multiple assignment
Try it yourself:
-
x, y = eval(input(‘Enter two numbers: ‘))
- x, y = eval(‘3, 4’) # works
-
x, y = eval(‘3 4’) # SyntaxError: …
-
x, y = eval(‘
3 4
‘) # SyntaxError: …
- print(x) # 3
- print(y) # 4
Explanation:
eval() runs the Python code which is passed as an argument.
For multiple assignment you need a comma separated list.
Therefore '3, 4' is the only possible input.
Q640 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 20Skipped
Q643 – I/O
What does the readline() method return, when the end of the file is reached?
Correct answer
An empty string.
Explanation
The readline() method returns an empty string when the end of the file is reached. This indicates that there are no more lines to read from the file.
‑1
Explanation
The value of -1 is not returned by the readline() method when the end of the file is reached. Instead, it returns an empty string to signify the end of the file.
EOF
Explanation
The term "EOF" is not directly returned by the readline() method when the end of the file is reached. Instead, an empty string is returned to indicate the end of the file.
An exception
Explanation
The readline() method does not raise an exception when the end of the file is reached. Instead, it returns an empty string to signify that there are no more lines to read.
Overall explanation
Topic: readline()
Try it yourself:
-
First execute the following to create the needed file:
-
data = ”’Peter
-
Paul
-
Mary
-
”’
-
with open(‘data.txt’, ‘w’) as f:
-
f.write(data) -
file = open(‘data.txt’, ‘r’)
-
print(file.readline()) # Peter
-
print(file.readline()) # Paul
-
print(file.readline()) # Mary
-
print(type(file.readline())) # <class ‘str’>
-
print(bool(file.readline())) # False
Explanation:
When the readline() method reaches the end of the file,
it returns an empty string
Q643 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 21Skipped
Q601 – Functions
What is the expected output of the following code?
-
def func(x=2, y=3):
-
return x * y -
print(func(y=2, 3))
4
Explanation
The code will not output ‘4’ because the function call func(y=2, 3) is incorrect. The positional argument ‘3’ should not be placed after a keyword argument ‘y=2’. This will result in a syntax error.
6
Explanation
The code will not output ‘6’ because the function call func(y=2, 3) is incorrect. The positional argument ‘3’ should not be placed after a keyword argument ‘y=2’. This will result in a syntax error.
Correct answer
The code is erroneous.
Explanation
The code is erroneous because there is a syntax error in the print statement. The arguments passed to the print function should be separated by commas, but in this case, there is a comma after ‘y=2’ and then ‘3’ directly after it, which is not valid syntax.
2
Explanation
The code will not output ‘2’ because the function call func(y=2, 3) is incorrect. The positional argument ‘3’ should not be placed after a keyword argument ‘y=2’. This will result in a syntax error.
Overall explanation
Topics: def return positional/keyword argument
Try it yourself:
-
def func(x=2, y=3):
-
return x * y -
print(func(y=2, 3))
-
SyntaxError: positional argument follows keyword argument
-
print(func(3, y=2)) # 6
Explanation:
The keyword arguments always have to be at the end of the list of arguments.
In other words: You can not have a keyword argument before a positional argument.
Q601 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 22Skipped
Q656 – Error Handling
Which of the following is an example of a Python built-in concrete exception?
Correct answer
IndexError
Explanation
IndexError is a built-in concrete exception in Python that occurs when trying to access an index that is out of range in a sequence like a list or a tuple. It is specific and directly related to index-related errors.
ArithmeticError
Explanation
ArithmeticError is a built-in base class for arithmetic errors in Python, such as ZeroDivisionError or OverflowError. It is a generic exception for arithmetic-related errors and not a concrete exception like IndexError.
BaseException
Explanation
BaseException is the base class for all built-in exceptions in Python. It is not a concrete exception that can be directly raised, unlike IndexError, which is a specific concrete exception for index-related errors.
ImportError
Explanation
ImportError is a built-in exception in Python that occurs when an import statement fails to find the module or package being imported. It is a generic exception for import-related errors and not a concrete exception like IndexError.
Overall explanation
Topics: IndexError ImportError ArithmeticError BaseException
Try it yourself:
-
IndexError:
-
e1 = [1, 2][23] # IndexError …
-
print(IndexError.subclasses()) # []
-
ImportError:
-
import mat # ModuleNotFoundError …
-
print(issubclass(ModuleNotFoundError, ImportError)) # True
-
print(ImportError.subclasses())
-
[<class ‘ModuleNotFoundError’>, <class ‘zipimport.ZipImportError’>]
-
ArithmeticError:
-
e2 = 10 / 0 # ZeroDivisionError …
-
print(issubclass(ZeroDivisionError, ArithmeticError)) # True
-
print(ArithmeticError.subclasses())
-
[<class ‘FloatingPointError’>, <class ‘OverflowError’>,
-
<class ‘ZeroDivisionError’>]
Explanation:
IndexError is the only built-in concrete exception here.
In the meaning that you can get an error message saying: IndexError ...
Since Python 3.6 the ImportError has the subclass ModuleNotFoundError
and ImportError is not a Python built-in concrete exception anymore.
ArithmeticError is also not a built-in concrete exception.
For example, you would get a ZeroDivisionError
BaseException is the base class for all built-in exceptions
what makes it the opposite of a built-in concrete exception.
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
Q656 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 23Skipped
Q621 – Functions
What is the expected output of the following code?
-
def func():
-
print(x + 1, end=' ') -
x = 1
-
func()
-
print(x)
Correct answer
2 1
Explanation
The code defines a function func() that prints the value of x + 1 with a space at the end. The value of x is set to 1 before calling the function func(). Therefore, the output will be 2 1 as x + 1 will be 1 + 1.
1 1
Explanation
This choice is incorrect because the function func() adds 1 to the value of x and prints it. Since the value of x is 1 when the function is called, the output will be 2 1, not 1 1.
2 2
Explanation
This choice is incorrect because the function func() adds 1 to the value of x and prints it. Since the value of x is 1 when the function is called, the output will be 2 1, not 2 2.
1 2
Explanation
This choice is incorrect because the function func() adds 1 to the value of x and prints it. Since the value of x is 1 when the function is called, the output will be 2 1, not 1 2.
Overall explanation
Topics: def scope print() with end parameter
Try it yourself:
-
def func():
-
print(x + 1, end=' ') # 2 -
x = 1
-
func()
-
print(x) # 1
Explanation:
There is no variable x inside of the function.
Python then will look for a variable x in the outer scope and read from that.
But that will definitely not change the value of the variable x in the outer scope.
Q621 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 24Skipped
Q652 – Data Types
The following code:
print(float("1, 3"))
prints 1,3
Explanation
This choice is incorrect because the code does not print 1,3. The presence of a comma in the string "1, 3" makes it an invalid input for conversion to a float, so the code will not print 1,3.
prints 1.3
Explanation
This choice is incorrect because the code does not print 1.3. The presence of a comma in the string "1, 3" makes it an invalid input for conversion to a float, so the code will not print 1.3.
prints 13
Explanation
This choice is incorrect because the code does not print 13. The float() function in Python does not interpret the comma in "1, 3" as a valid part of a floating-point number, so the code will not print 13.
Correct answer
raises a ValueError exception.
Explanation
The code raises a ValueError exception because the float() function in Python expects a string that represents a valid floating-point number. The use of a comma in "1, 3" makes it an invalid input for conversion to a float, resulting in a ValueError.
Overall explanation
Topics: float()
Try it yourself:
-
print(float("1, 3")) # ValueError …
-
print(float("1. 3")) # ValueError …
-
print(float("1,3")) # ValueError …
- print(float("1.3")) # 1.3
Explanation:
There are two problems.
There is a comma instead of a point and there is a space.
Q652 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 25Skipped
Q631 – Data Types
Consider the following Python code:
- distance = 1876.23
- amount = +42E7
- country = ‘Italy’
What are the types of the variables distance, amount and country?
double, str, float
Explanation
There is no data type "double" in Python. The variable "distance" is assigned a floating-point number, so its type is float. The variable "amount" is assigned a number in scientific notation, which is a floating-point number, not a string, so its type is float. The variable "country" is assigned a string, so its type is str.
Correct answer
float, float, str
Explanation
The variable "distance" is assigned a floating-point number, so its type is float. The variable "amount" is assigned a number in scientific notation, which is also a floating-point number, so its type is float. The variable "country" is assigned a string, so its type is str.
float, int, str
Explanation
The variable "distance" is assigned a floating-point number, so its type is float. The variable "amount" is assigned a number in scientific notation, which is also a floating-point number, not an integer, so its type is float. The variable "country" is assigned a string, so its type is str.
float, str, str
Explanation
The variable "distance" is assigned a floating-point number, so its type is float. The variable "amount" is assigned a number in scientific notation, which is a floating-point number, not a string, so its type is float. The variable "country" is assigned a string, so its type is str.
Overall explanation
Topics: integer float string scientific notation
Try it yourself:
-
print(type(1876.23)) # <class ‘float’>
-
print(type(+42E7)) # <class ‘float’>
-
print(type(‘Italy’)) # <class ‘str’>
-
print(10e6) # 10000000.0
Explanation:
There is no double in Python.
The scientific notation always returns a float
The letter E is called exponent and it does not matter whether you use e or E
Q631 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 26Skipped
Q646 – Data Types
Consider the following code.
- start = input(‘How old were you at the time of joining?’)
- now = input(‘How old are you today?’)
Which of the following codes will print the right output?
Correct answer
- print(
-
'Congratulations on ' -
+ str(int(now) - int(start)) -
+ ' Years of Service!' - )
Explanation
This choice correctly converts the input values to integers using the int() function before subtracting them to calculate the years of service. It then converts the result back to a string to concatenate it with the rest of the message for printing.
- print(
-
'Congrats on ' -
+ int(now - start) -
+ ' years of service!' - )
Explanation
This choice tries to subtract the input values directly without converting them to integers first. Additionally, it tries to concatenate an integer value with a string, which will result in a TypeError in Python.
- print(
-
'Congrats on ' -
+ (int(now) - int(start)) -
+ ' years of service!' - )
Explanation
This choice correctly converts the input values to integers using the int() function before subtracting them to calculate the years of service. However, it incorrectly tries to concatenate the integer result with a string without converting it back to a string, which will result in a TypeError.
- print(
-
'Congrats on ' -
+ str(now - start) -
+ ' years of service!' - )
Explanation
This choice attempts to subtract the input values directly without converting them to integers first. This will result in a TypeError because the input values are strings, and you cannot subtract strings in Python.
Overall explanation
Topics: input() string concantenation str() int()
subtraction operator
Try it yourself:
-
start = input(‘How old were you at the time of joining?’)
-
now = input(‘How old are you today?’)
-
start, now = ’20’, ’65’ # Just for convenience
-
You cannot subtract one string from another:
-
print(‘Congrats on ‘ + str(now – start) + ‘ Years of Service!’)
-
TypeError
-
print(‘Congrats on ‘ + int(now – start) + ‘ Years of Service!’)
-
TypeError
-
"""
-
You cannot concatenate a string and an integer
-
print(
-
'Congrats on ' -
+ (int(now) - int(start)) -
+ ' Years of Service!' -
) # TypeError
-
"""
-
This is the right way to do it:
-
print(
-
'Congrats on ' -
+ str(int(now) - int(start)) -
+ ' Years of Service!' -
)
-
Congrats on 45 years of service!
Explanation:
Each input() function will return a string
First you have to cast each of them to an integer to be able to calculate with them.
Then you have to cast the result to a string
to be able to concatenate it to the surrounding strings.
Q646 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 27Skipped
Q651 – Modules
What happens if you run the following code?
-
import time
-
time.sleep(30)
-
print("Wake up!")
The string Wake up! will be displayed thirty times on the screen for 30 seconds.
Explanation
This choice is incorrect because the code only prints the string "Wake up!" once after the 30-second sleep period. It does not involve displaying the string multiple times or repeatedly on the screen.
Correct answer
The string Wake up! will be displayed on the screen after 30 seconds.
Explanation
The code imports the time module and then calls the sleep function with a parameter of 30, which means the program will pause execution for 30 seconds. After the sleep period, the program will print the string "Wake up!" to the screen.
The string Wake up! will be displayed on the screen for 30 seconds.
Explanation
This choice is incorrect because the code does not involve displaying the string "Wake up!" for 30 seconds. The sleep function only pauses the program for the specified time period before executing the next line of code, which is to print the string.
Overall explanation
Topics: import time sleep()
Try it yourself:
- import time
- time.sleep(3)
- print("Wake up!") # Wake up!
Explanation:
Try it with a smaller number
then you don’t have to wait too long.
https://www.programiz.com/python-programming/time/sleep
Q651 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 28Skipped
Q602 – Data Aggregates
What is the expected output of the following code?
- data1 = (1, 2)
- data2 = (3, 4)
- [print(sum(x)) for x in [data1 + data2]]
The code is erroneous.
Explanation
This choice is incorrect because the code is syntactically correct and will run without errors. It concatenates the tuples data1 and data2, calculates the sum of all elements in the resulting tuple, and prints the sum. The code is not erroneous.
Nothing gets printed.
Explanation
This choice is incorrect because the code uses a list comprehension to iterate over a single element list containing the concatenated tuple. The sum of the concatenated tuple is printed within the list comprehension, so the output will not be empty. The expected output is 10.
Correct answer
10
Explanation
The code concatenates the tuples data1 and data2, resulting in (1, 2, 3, 4). Then, it calculates the sum of all elements in the concatenated tuple, which is 10. The print statement outputs the result, so the expected output is 10.
4
Explanation
This choice is incorrect because the code does not calculate the sum of individual elements in the tuples data1 and data2 separately. Instead, it concatenates the tuples and calculates the sum of all elements in the resulting tuple, which is 10, not 4.
Overall explanation
Topics: tuple sum() list comprehension
plus operator tuple concatenation
Try it yourself:
-
data1 = (1, 2)
-
data2 = (3, 4)
-
[print(sum(x)) for x in [data1 + data2]] # 10
-
[print(sum(x)) for x in [(1, 2, 3, 4)]] # 10
-
[print(sum(x)) for x in [(1, 2), (3, 4), (5, 6)]] # 3 – 7 – 11
Explanation:
data1 and data2 will get concatenated to one tuple
That leaves a list comprehension with a list of just one element,
the tuple (1, 2, 3, 4)
The sum() function adds the elements of a tuple and returns the sum.
sum((1, 2, 3, 4)) will be 10 which will be printed.
Q602 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 29Skipped
Q630 – Control Flow
What is the expected output of the following code?
-
x = (1, 4, 7, 9, 10, 11)
-
y = {2: ‘A’, 4: ‘B’, 6: ‘C’, 8: ‘D’, 10: ‘E’, 12: ‘F’}
-
res = 1
-
for z in x:
-
if z in y: -
continue -
else: -
res += z -
print(res)
30
Explanation
The code incorrectly calculates the sum of elements in x that are not keys in the dictionary y. The correct sum should be 29, not 30.
31
Explanation
The code incorrectly calculates the sum of elements in x that are not keys in the dictionary y. The correct sum should be 29, not 31.
Correct answer
29
Explanation
The code initializes the variable res to 1 and iterates over the elements in the tuple x. For each element z in x, it checks if z is a key in the dictionary y. If z is not in y, it adds the value of z to the res variable. The elements in x that are not keys in y are 1, 7, and 9. Therefore, the final value of res is 1 (initial value) + 7 + 9 + 1 + 11 = 29.
28
Explanation
The code incorrectly calculates the sum of elements in x that are not keys in the dictionary y. The correct sum should be 29, not 28.
Overall explanation
Topics: tuple dictionary for if else continue
Try it yourself:
-
x = (1, 4, 7, 9, 10, 11)
-
y = {2: ‘A’, 4: ‘B’, 6: ‘C’, 8: ‘D’, 10: ‘E’, 12: ‘F’}
-
res = 1
-
for z in x:
-
if z in y: -
continue -
else: -
print('z:', z) # 1 -> 7 -> 9 -> 11 -
res += z -
print(res) # 29
Explanation:
Which values in the tuple are NOT also indexes in the dictionary?
1 + 7 + 9 + 11 -> 28
The result starts at 1
Makes 29 in total.
Q630 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 30Skipped
Q609 – Operators
What is the expected output of the following code?
print('Mike' > 'Mikey')
0
Explanation
The comparison between ‘Mike’ and ‘Mikey’ does not result in a numerical value like 0. Instead, it results in a boolean value (True or False) based on the comparison of the strings character by character.
1
Explanation
The comparison between ‘Mike’ and ‘Mikey’ does not result in a numerical value like 1. Instead, it results in a boolean value (True or False) based on the comparison of the strings character by character.
Correct answer
False
Explanation
In Python, when comparing strings, the comparison is done character by character based on the ASCII value of the characters. In this case, ‘Mike’ is not greater than ‘Mikey’ because ‘Mikey’ has an extra ‘y’ character at the end. Therefore, the expected output is False.
True
Explanation
The comparison between ‘Mike’ and ‘Mikey’ is based on the ASCII values of the characters in the strings. Since ‘Mikey’ has an extra ‘y’ character at the end compared to ‘Mike’, the comparison results in False, not True.
Overall explanation
Topics: string comparison greater than operator
Try it yourself:
- print(‘Mike’ > ‘Mikey’) # False
- print(‘y’ > ”) # True
- print(‘B’ > ‘A’) # True
Explanation:
Every letter is greater than no character at all.
First the letters M, i, k, e are compared with each other.
Than the empty string is smaller than y
Therefore Mike is smaller than Mickey and it is False that Mike is greater.
Q609 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 31Skipped
Q610 – Operators
Which of the following is the correct order of operator precedence?
Parentheses
Exponents
Unary positive, negative, not
Addition and Subtraction
Multiplication and Division
And
Explanation
This order starts with Parentheses, followed by Exponents, Unary positive, negative, not, Addition and Subtraction, Multiplication and Division, and And. This order is incorrect as it does not follow the standard operator precedence in Python.
Correct answer
Parentheses
Exponents
Unary positive, negative, not
Multiplication and Division
Addition and Subtraction
And
Explanation
The correct order of operator precedence in Python is Parentheses, Exponents, Unary positive, negative, not, Multiplication and Division, Addition and Subtraction, and finally And. Parentheses have the highest precedence, followed by Exponents, then Unary operators, Multiplication and Division, Addition and Subtraction, and And operators.
Exponents
Unary positive, negative, not
Multiplication and Division
Addition and Subtraction
And
Parentheses
Explanation
This order starts with Exponents, followed by Unary positive, negative, not, Multiplication and Division, Addition and Subtraction, And, and finally Parentheses. This order is incorrect as it does not follow the standard operator precedence in Python.
Exponents
Unary positive, negative, not
Parentheses
Multiplication and Division
Addition and Subtraction
And
Explanation
This order starts with Exponents, followed by Unary positive, negative, not, Parentheses, Multiplication and Division, Addition and Subtraction, and And. This order is incorrect as it does not follow the standard operator precedence in Python.
Overall explanation
Topic: operator precedence
Explanation:
The operator precedence is very important.
You have to remember the it.
Q610 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 32Skipped
Q612 – Operators
Consider the following code.
- languages = [‘English’, ‘Spanish’, ‘German’]
- more_languages = [‘English’, ‘Spanish’, ‘German’]
- extra_languages = more_languages
Which statement will print True to the monitor?
Choose two.
print(languages is extra_languages)
Explanation
This statement will print False because ‘languages’ and ‘extra_languages’ are two separate list objects, even though ‘extra_languages’ was assigned the value of ‘more_languages’. The ‘is’ operator checks if two variables reference the same object in memory, which is not the case here.
Correct selection
print(languages == more_languages)
Explanation
This statement will print True because the ‘==’ operator checks if the contents of the two lists are the same, regardless of whether they reference the same object in memory. In this case, both ‘languages’ and ‘more_languages’ have the same elements, so the statement will evaluate to True.
print(languages is more_languages)
Explanation
This statement will print False because the ‘is’ operator checks if two variables reference the same object in memory. In this case, ‘languages’ and ‘more_languages’ are two separate list objects, even though they have the same elements.
Correct selection
print(more_languages is extra_languages)
Explanation
This statement will print True because both ‘more_languages’ and ‘extra_languages’ variables refer to the same list object in memory. The ‘is’ operator checks if two variables reference the same object, which is the case here.
Overall explanation
Topics: list equal to operator identity operator
Try it yourself:
-
languages = [‘English’, ‘Spanish’, ‘German’]
-
more_languages = [‘English’, ‘Spanish’, ‘German’]
-
extra_languages = more_languages
-
print(more_languages is extra_languages) # True
-
print(languages == more_languages) # True
-
print(languages is more_languages) # False
-
print(languages is extra_languages) # False
-
print(id(languages)) # e.g. 140539383900864
-
print(id(more_languages))
-
e.g. 140539383947452 (same number than extra_languages)
-
print(id(extra_languages))
-
e.g. 140539383947452 (same number than more_languages)
Explanation:
All the lists will have the same values.
more_languages is assigned to extra_languages
A list is a mutable data type.
Assigning a list creates a reference.
Therefore more_languages and extra_languages will have the same identity.
Q612 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 33Skipped
Q657 – Data Types
If you want to build a string that reads:
Peter's sister's name's "Anna"
Which of the following literals would you use?
Choose two.
'Peter's sister's name's "Anna"'
Explanation
This choice uses single quotes to enclose the entire string but does not escape the inner single quotes or double quotes. This would result in a syntax error as the interpreter would interpret the string as ending at the first occurrence of the unescaped single quote.
"Peter's sister's name's "Anna""
Explanation
This choice uses double quotes to enclose the beginning and end of the string but does not escape the inner double quotes. This would result in a syntax error as the interpreter would interpret the string as ending at the first occurrence of the unescaped double quote.
Correct selection
"Peter's sister's name's \"Anna\""
Explanation
The correct choice uses double quotes to enclose the entire string and escapes the inner double quotes with a backslash to include them in the string without terminating it. This is the correct way to represent the desired string in Python.
Correct selection
'Peter\'s sister\'s name\'s \"Anna\"'
Explanation
This choice uses single quotes to enclose the entire string and escapes the inner single quotes and double quotes with backslashes to include them in the string without terminating it. This is another correct way to represent the desired string in Python.
Overall explanation
Topics: quotation marks escaping
Try it yourself:
- print("Peter’s sister’s name’s "Anna"")
-
Peter’s sister’s name’s "Anna"
- print(‘Peter’s sister’s name’s "Anna"’)
-
Peter’s sister’s name’s "Anna"
-
print("Peter’s sister’s name’s "Anna"")
-
SyntaxError: invalid syntax
-
print(‘Peter’s sister’s name’s "Anna"’)
-
SyntaxError: invalid syntax
Explanation:
When you use the same kind of quotes inside of a string
and outside to delimiter the string
you have to escape the ones inside of the string
Q657 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 34Skipped
Q611 – Operators
What is the expected output of the following code?
-
list1 = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]
-
list2 = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]
-
print(list1 is list2)
-
print(list1 == list2)
-
list1 = list2
-
print(list1 is list2)
-
print(list1 == list2)
-
False
-
True
-
True
-
False
Explanation
The ‘is’ operator checks for object identity, not value equality. Since list1 and list2 are two separate list objects, ‘list1 is list2’ will return False. The values of list1 and list2 are the same, so ‘list1 == list2’ will return True. After assigning list2 to list1, both variables point to the same list object, so ‘list1 is list2’ will be True. However, the values of list1 and list2 are still the same, so ‘list1 == list2’ will remain True, not False.
- False
- True
- False
- True
Explanation
The ‘is’ operator checks for object identity, not value equality. Since list1 and list2 are two separate list objects, ‘list1 is list2’ will return False. The values of list1 and list2 are the same, so ‘list1 == list2’ will return True. After assigning list2 to list1, both variables point to the same list object, so ‘list1 is list2’ will be True. Since the values of list1 and list2 are still the same, ‘list1 == list2’ will remain True, not False.
- False
- False
- True
- True
Explanation
The ‘is’ operator checks for object identity, not value equality. Since list1 and list2 are two separate list objects, ‘list1 is list2’ will return False. The values of list1 and list2 are the same, so ‘list1 == list2’ will return True. After assigning list2 to list1, both variables point to the same list object, so ‘list1 is list2’ will be True, not False. The values of list1 and list2 are still the same, so ‘list1 == list2’ will remain True.
Correct answer
- False
- True
- True
- True
Explanation
The ‘is’ operator in Python checks if two variables refer to the same object in memory. Since list1 and list2 are two separate lists with the same values, they are not the same object in memory, so the output of ‘list1 is list2’ is False. The ‘==’ operator in Python checks if the values of two variables are equal. Since list1 and list2 have the same values, the output of ‘list1 == list2’ is True. After assigning list2 to list1 with ‘list1 = list2’, both variables point to the same list object in memory, so the output of ‘list1 is list2’ becomes True. The values of list1 and list2 are still the same, so the output of ‘list1 == list2’ remains True.
Overall explanation
Topics: list equal to operator identity operator
Try it yourself:
-
list1 = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]
-
list2 = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]
-
print(list1 is list2) # False
-
print(list1 == list2) # True
-
print(id(list1)) # e.g. 140539383900864
-
print(id(list2)) # e.g. 140539383947452 (a different number)
-
list1 = list2
-
print(list1 is list2) # True
-
print(list1 == list2) # True
-
print(id(list1)) # e.g. 140539652049216
-
print(id(list2)) # e.g. 140539652049216 (the same number)
Explanation:
A list is a mutable data type.
The second list will be a different object, although the values are the same.
When list2 gets assigned to list1 Python creates a reference.
From now on the two lists have the same identity and the same values.
Q611 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 35Skipped
Q635 – Modules
You want to develop a programm to calculate the area of a circle.
Here is the formula:
A = pi * r ** 2
Which of the following code snippets do you need?
- import math
- def get_area(r):
-
return math.pi * math.fmod(r, 2)
Explanation
This code snippet is incorrect because it uses the math.fmod() function, which calculates the remainder of dividing r by 2, not the square of r. This function is not suitable for calculating the area of a circle.
Correct answer
- import math
- def get_area(r):
-
return math.pi * math.pow(r, 2)
Explanation
This code snippet is correct because it imports the math module, which provides access to the mathematical constant pi and the pow() function to calculate the area of a circle using the formula A = pi * r ** 2.
- import math
- def get_area(r):
-
return math.pi * math.fabs(r, 2)
Explanation
This code snippet is incorrect because it uses the math.fabs() function, which returns the absolute value of r, not the square of r. This function is not suitable for calculating the area of a circle.
None of the above.
Explanation
This code snippet is incorrect because it states that none of the above code snippets are needed, but Choice A is the correct code snippet that imports the math module and provides the necessary calculation for the area of a circle.
Overall explanation
Topics: import math.pi math.pow() math.fmod() math.fabs()
Try it yourself:
-
import math
-
def get_area(r):
-
return math.pi * math.pow(r, 2) -
print(get_area(2)) # 12.566370614359172
-
print(math.pi * 2 ** 2) # 12.566370614359172
-
print(‘———-‘)
-
def get_area(r):
-
return math.pi * math.fmod(r, 2) -
print(get_area(2)) # 0.0
-
print(math.fmod(7, 2)) # 1.0
-
print(7 % 2) # 1
-
print(float(7 % 2)) # 1.0
-
print(‘———-‘)
-
"""
-
def get_area(r):
-
return math.pi * math.fabs(r, 2) # TypeError: ... -
print(get_area(2))
-
"""
-
print(math.fabs(-7.3)) # 7.3
-
print(math.fabs(-7)) # 7.0
-
print(abs(-7.3)) # 7.3
-
print(abs(-7)) # 7
-
print(float(abs(7))) # 7.0
Explanation:
The pow() method is the right choice here.
We could also write it like: math.pi * r ** 2
fmod() returns the float value of the remainder.
fabs() returns the float value of the absolute value.
Q635 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 36Skipped
Q654 – Modules
Look at the code below:
-
import random
-
Insert lines of code here.
-
print(a, b, c)
Which lines of code would you insert so that it is possible for the program
to output the following result:
6 82 0
- a = random.choice((0, 100, 3))
- b = random.randrange(10, 100, 3)
- c = random.randint(0, 100)
Explanation
This choice is incorrect because it assigns a random choice from the tuple (0, 100, 3) to variable ‘a’, a random integer between 10 and 100 with a step of 3 to variable ‘b’, and a random integer between 0 and 100 to variable ‘c’. This combination does not match the desired output of 6, 82, 0.
- a = random.randrange(10, 100, 3)
- b = random.randint(0, 100)
- c = random.choice((0, 100, 3))
Explanation
This choice is incorrect because it assigns a random integer between 10 and 100 with a step of 3 to variable ‘a’, a random integer between 0 and 100 to variable ‘b’, and a random choice from the tuple (0, 100, 3) to variable ‘c’. This combination does not match the desired output of 6, 82, 0.
- a = random.randint(0, 100)
- b = random.choice((0, 100, 3))
- c = random.randrange(10, 100, 3)
Explanation
This choice is incorrect because it assigns a random integer between 0 and 100 to variable ‘a’, a random choice from the tuple (0, 100, 3) to variable ‘b’, and a random integer between 10 and 100 with a step of 3 to variable ‘c’. This combination does not match the desired output of 6, 82, 0.
Correct answer
- a = random.randint(0, 100)
- b = random.randrange(10, 100, 3)
- c = random.choice((0, 100, 3))
Explanation
This choice is correct because it uses the random.randint() function to generate a random integer between 0 and 100 for variable ‘a’, the random.randrange() function to generate a random integer between 10 and 100 with a step of 3 for variable ‘b’, and the random.choice() function to select a random element from the tuple (0, 100, 3) for variable ‘c’. This combination of functions ensures that ‘a’ will be a random integer, ‘b’ will be a random integer between 10 and 100 with a step of 3, and ‘c’ will be a random element from the tuple.
Overall explanation
Topics: import random randint() randrange() choice()
Try it yourself:
-
import random
-
a = random.randint(0, 100)
-
b = random.randrange(10, 100, 3)
-
c = random.choice((0, 100, 3))
-
print(a, b, c) # e.g. 6 82 0
-
print(random.randint(0, 100)) # e.g. 0, 1, 2, … 98, 99, 100
-
print(random.randrange(10, 100, 3)) # e.g. 10, 13, 16, … 91, 94, 97
-
print(random.choice((0, 100, 3))) # e.g. 0, 100, 3
Explanation:
randint(0, 100) will return a number
between 0 (inclusive) and 100 (inclusive).
randrange(10, 100, 3) will return a number between
0 (inclusive) and 100 (EXCLUSIVE)
with a step of three: 10, 13, 16, ... , 79, 82, 85, ...
choice((0, 100, 3)) will return one element of the tuple (0, 100, 3)
Q654 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 37Skipped
Q613 – Operators
What is the expected output of the following code?
- res = str(bool(1) + float(12) / float(2))
- print(res)
6
Explanation
The code performs the same operations as explained in Explanation A, but the result is not converted to a string. Therefore, the output will be 6 (an integer).
Correct answer
7.0
Explanation
The code first evaluates the boolean value of 1 (which is True) and then adds it to the result of dividing 12.0 by 2.0 (which is 6.0). The result is then converted to a string, resulting in ‘7.0’.
6.0
Explanation
The code performs the same operations as explained in Explanation A, but the result is not converted to a string. Therefore, the output will be 6.0 (a float).
The code is erroneous.
Explanation
The code is not erroneous and will produce a valid output. It performs a series of operations involving boolean, integer, and float values, resulting in a final output that is a string representation of a float value.
7
Explanation
The code performs the same operations as explained in Explanation A, but the result is not converted to a string. Therefore, the output will be 7 (an integer).
Overall explanation
Topics: bool() float() addition operator division operator
Try it yourself:
- res = str(bool(1) + float(12) / float(2))
- print(res) # 7.0
- print(str(bool(1) + float(12) / float(2))) # 7.0
- print(str(True + 12.0 / 2.0)) # 7.0
- print(str(True + (12.0 / 2.0))) # 7.0
- print(str(True + 6.0)) # 7.0
- print(str(1 + 6.0)) # 7.0
- print(str(7.0)) # 7.0
- print(‘7.0’) # 7.0
Explanation:
First the functions inside of the parenthesis are executed.
The value 1 becomes True
Then division comes before addition.
If you calculate with a boolean True becomes 1
In the end the str() method will make it the string '7.0'
Q613 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 38Skipped
Q650 – Error Handling
What is the output of the following code?
-
import math
-
try:
-
print(math.pow(2)) -
except TypeError:
-
print('A') -
else:
-
print('B')
Correct answer
A
Explanation
The code will raise a TypeError because the math.pow() function requires two arguments (base and exponent). Since only one argument is provided, a TypeError will occur, and the code will print ‘A’ as the output inside the except block.
B
Explanation
The else block will not be executed in this code because an exception (TypeError) is raised in the try block. As a result, the code will not reach the else block, and ‘B’ will not be printed as the output.
The program will cause a ValueError exception.
Explanation
The program will not cause a ValueError exception. Instead, it will raise a TypeError due to providing an incorrect number of arguments to the math.pow() function. The except block will handle this TypeError, and ‘A’ will be printed as the output.
Overall explanation
Topics: import math math.pow() try except else TypeError
Try it yourself:
-
import math
-
try:
-
print(math.pow(2)) -
except TypeError:
-
print('A') -
else:
-
print('B') -
math.pow(2)
-
TypeError: pow expected 2 arguments, got 1
-
print(math.pow(2, 8)) # 256.0
Explanation:
The math.pow() function like any pow() function needs two arguments.
And that will raise a TypeError
Q650 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 39Skipped
Q636 – Basics
The compiled Python bytecode is stored in files having names ending with:
Correct answer
pyc
Explanation
The compiled Python bytecode is stored in files with names ending in "pyc." These files contain the bytecode version of the Python source code and are created by the Python interpreter to improve the execution speed of the program.
pyb
Explanation
Files ending with "pyb" are not used to store compiled Python bytecode. The standard convention for storing compiled Python bytecode is to use the ".pyc" extension, which is recognized by the Python interpreter for optimized execution.
pc
Explanation
Files ending with "pc" are not used to store compiled Python bytecode. The correct extension for storing Python bytecode is "pyc," which stands for Python compiled.
py
Explanation
Files ending with "py" are regular Python source code files, not compiled bytecode files. The Python interpreter reads and executes the code directly from ".py" files, while ".pyc" files store the compiled bytecode for faster execution.
Overall explanation
Topic: pyc
Try it yourself:
-
First execute the following to create the needed file:
-
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
This file contains compiled Python bytecode.
Next time you run index.py Python will use
the compiled bytecode for faster execution.
Q636 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics
Question 40Skipped
Q624 – Control Flow
Which of the following code snippets will print all prime numbers
between 2 and 100 to the monitor?
Correct answer
- num = 2
- while num <= 100:
-
is_prime = True -
for i in range(2, num): -
if num % i == 0: -
is_prime = False -
break -
if is_prime == True: -
print(num) -
num += 1
Explanation
This code snippet correctly implements a loop that iterates through numbers from 2 to 100 and checks if each number is prime by dividing it by numbers from 2 to the number itself. If the number is only divisible by 1 and itself, it is considered prime and printed to the monitor.
- num = 2
- while num <= 100:
-
is_prime = True -
for i in range(2, num): -
if num % i == 0: -
is_prime = False -
break -
if is_prime == False: -
print(num) -
num += 1
Explanation
This code snippet incorrectly checks for non-prime numbers by changing the condition to print when ‘is_prime’ is False. This will result in printing non-prime numbers instead of prime numbers between 2 and 100.
- num = 2
- is_prime = True
- while num <= 100:
-
for i in range(2, num): -
if num % i == 0: -
is_prime = False -
break -
if is_prime == True: -
print(num) -
num += 1
Explanation
This code snippet has a logical error in that the variable ‘is_prime’ is initialized outside the loop, causing it to retain its value across iterations. This will result in incorrect prime number identification and printing.
- num = 2
- while num <= 100:
-
is_prime = True -
for i in range(2, num): -
if num % i == 0: -
is_prime = False -
break -
if is_prime == True: -
print(num)
Explanation
This code snippet correctly implements the prime number checking logic, similar to choice A, but it lacks the correct condition to print prime numbers. The condition should be to print when ‘is_prime’ is True, not when it is False.
Overall explanation
Topics: while break boolean for range()
modulus operator equal to operator if
Try it yourself:
-
num = 2
-
while num <= 100:
-
is_prime = True -
for i in range(2, num): -
if num % i == 0: -
is_prime = False -
break -
if is_prime == True: -
print(num) # 2 -> 3 -> 5 -> ... -> 89 -> 97 -
num += 1 -
print(‘———-‘)
-
num = 2
-
is_prime = True
-
while num <= 100:
-
for i in range(2, num): -
if num % i == 0: -
is_prime = False -
break -
if is_prime == True: -
print(num) # 2 -> 3 -
num += 1 -
print(‘———-‘)
-
num = 2
-
while num <= 100:
-
is_prime = True -
for i in range(2, num): -
if num % i == 0: -
is_prime = False -
break -
if is_prime == False: -
print(num) # 4 -> 6 -> 8 -> ... -> 99 -> 100 -
num += 1 -
print(‘———-‘)
-
stop = 0 # Just added to prevent the infinite loop
-
num = 2
-
while num <= 100:
-
is_prime = True -
for i in range(2, num): -
if num % i == 0: -
is_prime = False -
break -
if is_prime == True: -
print(num) # 2 -> 2 -> 2 -> ... -> 2 -> 2 -
stop += 1 -
# Just added to prevent the infinite loop -
if stop > 100: -
break -
# Just added to prevent the infinite loop
Explanation:
One answer does not increment the number.
One answer has the is_prime flag outside of the outer loop.
One answer checks, if it is False the the number is a prime number.
And one answer does it all the right way.
Q624 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 41Skipped
Q655 – Error Handling
What is the expected result of the following code?
- try:
-
raise Exception - except:
-
print("c") - except BaseException:
-
print("a") - except Exception:
-
print("b")
a
Explanation
This choice is incorrect because the code will not print "a". The exception raised is of type Exception, which is more specific than BaseException. Since the except block for Exception comes before the one for BaseException, "b" will be printed instead of "a".
1
Explanation
This choice is incorrect because the code will not output "1". The code does not have any print statement for the integer 1, so it will not be part of the output. The code will either result in a syntax error or print "b".
Correct answer
The code will cause a syntax error.
Explanation
The code will cause a syntax error because the order of the except blocks is incorrect. In Python, the except blocks should be ordered from the most specific exception to the most general one. In this case, the order is reversed, which will result in a syntax error.
b
Explanation
This choice is incorrect because the code will not print "b". The exception raised is of type Exception, so the except block for Exception will be executed, resulting in "b" being printed.
Overall explanation
Topics: try except Exception BaseException SyntaxError
Try it yourself:
-
"""
-
try:
-
raise Exception -
except:
-
print("c") -
except BaseException:
-
print("a") -
except Exception:
-
print("b") -
"""
-
SyntaxError: default ‘except:’ must be last
-
This still does not make much sense,
-
but there would be no syntax error.
-
try:
-
raise Exception -
except BaseException:
-
print("a") # a -
except Exception:
-
print("b") -
except:
-
print("c")
Explanation:
As the error message claims:
default ‘except:’ must be last
Q655 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 42Skipped
Q647 – Control Flow
You work for a company that distributes media for all ages.
You are writing a function that assigns a rating based on a user’s age.
The function must meet the following requirements:
Anyone 18 years old or older receives a rating of A
Anyone 13 or older, but younger than 18 receives a rating of T
Anyone 12 years old or younger receives a rating of C
If the age is unknown, the rating is set to C
- def get_rating(age):
-
rating = '' -
if # Line-3 -
elif # Line-4 -
elif # Line-5 -
else # Line-6 -
return rating
Which of the following should you insert on Line-3 to Line-6?
- : rating = ‘A’ # Line-3
- age < 18: rating = ‘T’ # Line-4
- age < 13: rating = ‘C’ # Line-5
- age == None: rating = ‘C’ # Line-6
Explanation
This choice correctly assigns the rating ‘A’ as the default option if none of the other conditions are met. It then correctly checks if the age is less than 18 and assigns the rating ‘T’, followed by checking if the age is less than 13 and assigning the rating ‘C’. Lastly, it handles the case where the age is unknown (None) and assigns the rating ‘C’.
- age < 18: rating = ‘T’ # Line-3
- age < 13: rating = ‘C’ # Line-4
- age == None: rating = ‘C’ # Line-5
- : rating = ‘A’ # Line-6
Explanation
This choice incorrectly checks if the age is less than 18 before checking if the age is less than 13. This order would result in incorrect ratings for ages between 13 and 18. It then correctly handles the case where the age is unknown (None) and assigns the rating ‘C’. Finally, if none of the previous conditions are met, it assigns the rating ‘A’.
Correct answer
- age == None: rating = ‘C’ # Line-3
- age < 13: rating = ‘C’ # Line-4
- age < 18: rating = ‘T’ # Line-5
- : rating = ‘A’ # Line-6
Explanation
This choice correctly handles the case where the age is unknown (None) and assigns the rating ‘C’ accordingly. It then checks if the age is less than 13 and assigns the rating ‘C’, followed by checking if the age is less than 18 and assigning the rating ‘T’. Finally, if none of the previous conditions are met, it assigns the rating ‘A’.
- age < 13: rating = ‘C’ # Line-3
- age == None: rating = ‘C’ # Line-4
- age < 18: rating = ‘T’ # Line-5
- : rating = ‘A’ # Line-6
Explanation
This choice incorrectly checks if the age is less than 13 before handling the case where the age is unknown (None). This order would result in incorrect ratings for unknown ages. It then correctly checks if the age is less than 18 and assigns the rating ‘T’. Finally, if none of the previous conditions are met, it assigns the rating ‘A’.
- : rating = ‘A’ # Line-3
- age < 13: rating = ‘C’ # Line-4
- age < 18: rating = ‘T’ # Line-5
- age == None: rating = ‘C’ # Line-6
Explanation
This choice incorrectly assigns the rating ‘A’ as the default option without considering the other age conditions. It then correctly checks if the age is less than 13 and assigns the rating ‘C’, followed by checking if the age is less than 18 and assigning the rating ‘T’. Lastly, it handles the case where the age is unknown (None) and assigns the rating ‘C’.
- age == None: rating = ‘C’ # Line-3
- age < 18: rating = ‘T’ # Line-4
- age < 13: rating = ‘C’ # Line-5
- : rating = ‘A’ # Line-6
Explanation
This choice incorrectly checks if the age is less than 18 before checking if the age is less than 13. This order would result in incorrect ratings for ages between 13 and 18. Additionally, it correctly handles the case where the age is unknown (None) and assigns the rating ‘C’.
Overall explanation
Topics: if elif else def None
equal to operator less than operator
Try it yourself:
-
def get_rating(age):
-
rating = '' -
if age == None: rating = 'C' -
elif age < 13: rating = 'C' -
elif age < 18: rating = 'T' -
else: rating = 'A' -
return rating -
print(get_rating(19)) # A
-
print(get_rating(18)) # A
-
print(get_rating(17)) # T
-
print(get_rating(13)) # T
-
print(get_rating(12)) # C
-
print(get_rating(11)) # C
-
print(get_rating(None)) # C
Explanation:
The None condition needs to be first,
because None does not support the less than operator
And if you start with rating C you can best continue with it.
That would be: age < 13
The next bigger rating is T: age < 18
Then anyone who is at least 18 remains.
They all get the rating A in the else clause.
Q647 (Please refer to this number, if you want to write me about this question.)
Domain
05 – Control Flow
Question 43Skipped
Q618 – Functions
What is the expected output of the following code?
-
def func(a, b):
-
return a ** a -
print(func(2))
2
Explanation
The code will not output 2 because the function func is defined to return the value of a raised to the power of a. In this case, a is 2, so the expected output should be 2 ** 2, which is 4.
4
Explanation
The code will not output 4 because the function func is defined to return the value of a raised to the power of a. In this case, a is 2, so the expected output should be 2 ** 2, which is 4.
Correct answer
The code is erroneous.
Explanation
The code is erroneous because the function func is defined with two parameters a and b, but only one argument 2 is passed to the function when it is called. This will result in a TypeError as the function expects two arguments.
None
Explanation
The code will not output None because the function func is defined to return a value, specifically a raised to the power of a. Since the function is called with an argument of 2, the function will return 2 ** 2, which is 4, not None.
Overall explanation
Topics: def argument exponentiation operator
Try it yourself:
-
def func(a, b):
-
return a ** a -
print(func(2))
-
TypeError: func() missing 1 required positional argument: ‘b’
Explanation:
There are two parameters in the function definition.
That means you need two arguments in the function call.
Only one is given.
Q618 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 44Skipped
Q622 – Functions
Consider the following code.
- def function(x=0):
-
return x
With sentence describes the function the best?
A function defined like function() …
must be called without arguments.
Explanation
This function has a default argument, so it can be called without any arguments. If called without any arguments, it will return the default value specified in the function definition.
must be called with exactly one argument.
Explanation
This function has a default argument, but it is not mandatory to provide an argument when calling the function. It can be called without any arguments or with just one argument, but it is not required to be called with exactly one argument.
Correct answer
may be called without any argument, or with just one.
Explanation
This function is defined with a default argument of 0, which means it can be called without any arguments, in which case it will return the default value of 0. It can also be called with just one argument, which will override the default value.
may be called with any number of arguments (including zero).
Explanation
This function can be called with any number of arguments, including zero. If no arguments are provided, the default value of 0 will be returned. The function is flexible in terms of the number of arguments it can accept.
Overall explanation
Topics: def arguments
Try it yourself:
-
def function(x=0):
-
return x -
print(function()) # 0
-
print(function(7)) # 7
-
print(function(4, 7)) # TypeError: …
Explanation:
The parameter x has the default value 0
You call the function without any argument.
Then x becomes its default 0
Or you can call the function with exactly one argument.
x will get the value of that argument.
Q622 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 45Skipped
Q614 – Operators
Which expression evaluates to 7?
Correct answer
9 % 3 + 7
Explanation
This expression first calculates the remainder of 9 divided by 3, which is 0, and then adds 7 to it, resulting in 7. This is why this expression evaluates to 7.
9 - 3 * 7
Explanation
This expression first multiplies 3 by 7, resulting in 21, and then subtracts 9 from it, resulting in 12. Therefore, this expression does not evaluate to 7.
9 / 3 * 7
Explanation
This expression first divides 9 by 3, resulting in 3, and then multiplies it by 7, resulting in 21. Therefore, this expression does not evaluate to 7.
9 // 3 - 7
Explanation
This expression first performs integer division of 9 by 3, resulting in 3, and then subtracts 7 from it, resulting in -4. Therefore, this expression does not evaluate to 7.
Overall explanation
Topics: arithmetic operators operator precedence
Try it yourself:
-
print(9 % 3 + 7) # 7
-
print((9 % 3) + 7) # 7
-
print(0 + 7) # 7
-
print(9 / 3 * 7) # 21.0
-
print((9 / 3) * 7) # 21.0
-
print(3.0 * 7) # 21.0
-
print(9 // 3 – 7) # -4
-
print((9 // 3) – 7) # -4
-
print(3 – 7) # -4
-
print(9 – 3 * 7) # -12
-
print(9 – (3 * 7)) # -12
-
print(9 – 21) # -12
Explanation:
The operators here are from two different groups:
The group "Multiplication, Division, Floor division, Modulus"
has a higher precedence than the group
"Addition, Subtraction".
Once there are only operators from the group
"Multiplication, Division, Floor division, Modulus".
The group has a left-to-right associativity,
meaning the left one gets evaluated first.
Q614 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 46Skipped
Q637 – Basics
You execute the following command in the terminal.
python index.py Hello
You want the command to print out Hello
What has to be inside of index.py?
- from sys import args
- print(args[1])
Explanation
This choice is incorrect because there is no ‘args’ module in the sys library. The correct module to import for accessing command-line arguments is ‘argv’.
Correct answer
- from sys import argv
- print(argv[1])
Explanation
This choice is correct because it imports the argv module from the sys library, which allows access to command-line arguments. The command print(argv[1]) prints out the second argument passed to the script, which in this case is ‘Hello’.
- from sys import args
- print(args[0])
Explanation
This choice is incorrect because there is no ‘args’ module in the sys library. The correct module to import for accessing command-line arguments is ‘argv’. Additionally, printing args[0] would not print the desired argument ‘Hello’.
- from sys import argv
- print(argv[0])
Explanation
This choice is incorrect because printing argv[0] would print the name of the script itself, not the argument ‘Hello’ that we want to print out.
Overall explanation
Topic: sys.argv
Try it yourself:
-
First execute the following to create the needed file:
-
code = ”’
-
from sys import argv
-
print(argv[1])
-
”’
-
with open(‘index.py’, ‘w’) as f:
-
f.write(code) -
In Terminal:
-
python index.py Hello
Explanation:
You need to know two things here.
First the name of the variable is argv (argument vector).
And second the index 0 always holds the filename.
Index 1 holds the first argument from the command line.
To test it you have to open the folder
where you created the index.py file in a terminal
and run the file by executing python index.py Hello
Q637 (Please refer to this number, if you want to write me about this question.)
Domain
01 – Basics
Question 47Skipped
Q623 – Data Types
The ABC company is building a basketball court
for its employees to improve company morale.
You are creating a Python program that employees
can use to keep track of their average score.
The program must allow users to enter their name and current scores.
The program will output the user name and the user’s average score.
The output must meet the following requirements:
The user name must be left-aligned
If the user name has fewer than 20 characters,
additional space must be added to the right
The average score must have three places to the left of the decimal point
and one place to the right of the decimal (xxx.x)
What would you insert instead of ??? and ???
-
name = input(‘What is your name?’)
-
sum = 0
-
score = 0
-
count = 0
-
while score != -1:
-
score = int(input('Enter your scores: (-1 to end)')) -
if score == -1: -
break -
sum += score -
count += 1 -
average = sum / count
-
print(‘???, your average score is: ???’ % (name, average))
-
%-20f
-
%4.1s
Explanation
The format specifier %-20f is not appropriate for formatting a string (user’s name) and does not align with the left-align requirement. The format specifier %4.1s does not correctly format the average score with the required decimal places.
- %-20d
- %4.1f
Explanation
The format specifier %-20d is not suitable for formatting a string (user’s name) and does not align with the left-align requirement. The format specifier %4.1f is used to display the average score with the correct number of decimal places.
- %-20s
- %1.4f
Explanation
The format specifier %-20s correctly left-aligns the user’s name with additional spaces to the right if needed. However, the format specifier %1.4f does not align with the requirement of having three places to the left of the decimal point and one place to the right for the average score.
- %-20i
- %4.1
Explanation
The format specifier %-20i is not suitable for formatting a string (user’s name) and does not align with the left-align requirement. The format specifier %4.1 does not correctly format the average score with three places to the left of the decimal point and one place to the right.
Correct answer
- %-20s
- %4.1f
Explanation
The format specifier %-20s is used to left-align the user’s name with additional spaces to the right if the name has fewer than 20 characters. The format specifier %4.1f is used to display the average score with three places to the left of the decimal point and one place to the right, meeting the specified requirements.
- %-20f
- %1.4s
Explanation
The format specifier %-20f is not appropriate for formatting a string (user’s name) and does not align with the left-align requirement. Additionally, the format specifier %1.4s does not match the requirement of displaying the average score with specific decimal places.
Overall explanation
Topics: int() if input() while break
not equal to operator add and assign operator
division operator string formatting
Try it yourself:
-
name = input(‘What is your name?’)
-
name = ‘Peter’ # Just for convenience
-
sum = 0
-
score = 0
-
count = 0
-
"""
-
while score != -1:
-
score = int(input('Enter your scores: (-1 to end)')) -
if score == -1: -
break -
sum += score -
count += 1 -
"""
-
sum = 120 + 180 + 165 + 224 # Just for convenience
-
count = 4 # Just for convenience
-
average = sum / count
-
print(‘%-20s, your average score is: %4.1f’ % (name, average))
-
Peter , your average score is: 172.2
-
print(‘%-20i, … %4.1f’ % (name, average)) # TypeError: …
-
print(‘%-20d, … %4.1f’ % (name, average)) # TypeError: …
-
print(‘%-20f, … %4.1f’ % (name, average)) # TypeError: …
-
print(‘%-20s, … %1.4s’ % (name, average)) # … 172.
-
print(‘%-20s, … %1.4f’ % (name, average)) # … 172.2500
-
print(‘%-20s, … %4.1s’ % (name, average)) # … 1
-
Other possibilities to format a string in Python:
-
name, age = ‘Peter’, 30
-
print(f’My name is {name} and I am {age} years old.’)
-
My name is Peter and I am 30 years old.
-
s = ‘My name is {name} and I am {age} years old.’
-
print(s.format(name=’Peter’, age=30))
-
My name is Peter and I am 30 years old.
Explanation:
This question is about string formatting by % in the so called printf-style.
%-20s
The minus sign is for the left-alignment.
The 20 stands for 20 characters.
The s stands for string
%4.1f
The 4 stands for a minimum of 4 characters.
The .1 stands for 1 decimal place.
The f stands for float format.
Check the official documentation for more information about the topic:
https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
Q623 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 48Skipped
Q642 – I/O
You want to write more text into an already existing file.
Which of the modes below do you have to use to only open the file for writing?
at+
Explanation
The ‘at+’ mode is used to open a file for both reading and writing, with the ability to append new text to the end of the file. However, since the question specifies that you only want to open the file for writing, the ‘at+’ mode is not necessary.
Correct answer
at
Explanation
The ‘at’ mode is used to open a file for writing only, without truncating the existing content. It allows you to append new text to the end of the file without overwriting the existing data, which is the requirement in this scenario.
ab
Explanation
The ‘ab’ mode is used to open a file for writing in binary format. It is not specifically designed for appending text to an existing file in a text format, so it is not the correct choice for this scenario.
ab+
Explanation
The ‘ab+’ mode is used to open a file for both reading and writing in binary format. Similar to the ‘ab’ mode, it is not the most suitable choice for appending text to an existing file in a text format without truncating the existing content.
Overall explanation
Topic: open() and its modes
Try it yourself:
-
First execute the following to create the needed file:
-
data = ”’Peter
-
Paul
-
Mary
-
”’
-
with open(‘data.txt’, ‘w’) as f:
-
f.write(data) -
file = open(‘data.txt’, ‘at’)
-
file.write(‘Jane’)
-
file.close()
-
with open(‘data.txt’, ‘r’) as f:
-
print(f.read()) -
"""
-
Peter
-
Paul
-
Mary
-
Jane
-
"""
-
print(‘———-‘)
-
This would open for writing and reading
-
file = open(‘data.txt’, ‘at+’)
-
file.seek(0)
-
print(file.read())
-
file.close()
-
"""
-
Peter
-
Paul
-
Mary
-
Jane
-
"""
-
file = open(‘data.txt’, ‘ab’)
-
file.write(‘Jane’) # TypeError: …
-
file.close()
-
file = open(‘data.txt’, ‘ab+’)
-
file.write(‘Jane’) # TypeError: …
-
file.close()
Explanation:
All answers have with a the right mode to append.
The t stands for text.
It is the default and could also be left out.
The b stands for binary and is wrong here,
because we want to write text into the file.
The + would allow us to read and write.
Therefore that is wrong here too,
because we want to open the file for writing only.
Q642 (Please refer to this number, if you want to write me about this question.)
Domain
07 – I/O
Question 49Skipped
Q634 – Modules
You are writing code that generates a random integer
with a minimum value of 5 and a maximum value of 11
Which functions should you use?
Each correct answer presents a complete solution.
Choose two.
Correct selection
random.randrange(5, 12, 1)
Explanation
The random.randrange(5, 12, 1) function generates a random integer within the specified range of 5 (inclusive) to 12 (exclusive) with a step of 1. This choice correctly fulfills the requirement of generating a random integer with a minimum value of 5 and a maximum value of 11.
Correct selection
random.randint(5, 11)
Explanation
The random.randint(5, 11) function generates a random integer between the specified range of 5 and 11, inclusive. This choice correctly meets the requirement of generating a random integer with a minimum value of 5 and a maximum value of 11.
random.randrange(5, 11, 1)
Explanation
The random.randrange(5, 11, 1) function generates a random integer within the specified range of 5 (inclusive) to 11 (exclusive) with a step of 1. This choice does not meet the requirement of generating a random integer with a maximum value of 11, as it excludes 11 from the range.
random.randint(5, 12)
Explanation
The random.randint(5, 12) function generates a random integer between the specified range of 5 and 12, inclusive. This choice does not meet the requirement of generating a random integer with a maximum value of 11, as it includes 12 in the range.
Overall explanation
Topics: random.randint() random.randrange()
Try it yourself:
- import random
- print(random.randint(5, 11)) # 5 to 11
- print(random.randrange(5, 12, 1)) # 5 to 11
- print(random.randrange(5, 11, 1)) # 5 to 10
- print(random.randint(5, 12)) # 5 to 12
Explanation:
random.randint(start, stop)
With randint() both start and stop are inclusive.
random.randrange(start, stop, step)
With randrange() start is inclusive and stop is exclusive.
(just like with range())
Q634 (Please refer to this number, if you want to write me about this question.)
Domain
09 – Modules
Question 50Skipped
Q607 – Data Aggregates
What is the expected output of the following code?
- data = [‘Peter’, ‘Paul’, ‘Mary’]
- print(data[int(-1 / 2)])
Paul
Explanation
The code calculates -1 divided by 2, which results in -0.5. When converted to an integer, it becomes 0. Therefore, the code will print the element at index 0 of the ‘data’ list, which is ‘Peter’, not ‘Paul’.
Mary
Explanation
The code calculates -1 divided by 2, which results in -0.5. When converted to an integer, it becomes 0. Therefore, the code will print the element at index 0 of the ‘data’ list, which is ‘Peter’, not ‘Mary’.
Correct answer
Peter
Explanation
The code calculates -1 divided by 2, which results in -0.5. When converted to an integer, it becomes 0. Therefore, the code will print the element at index 0 of the ‘data’ list, which is ‘Peter’.
The code is erroneous.
Explanation
The code is not erroneous. It calculates the index to access in the ‘data’ list correctly and will output ‘Peter’.
None of the above.
Explanation
The code will output ‘Peter’ as the result. Therefore, the correct choice is not "None of the above."
Overall explanation
Topics: list int() division operator
Try it yourself:
-
data = [‘Peter’, ‘Paul’, ‘Mary’]
-
print(data[int(-1 / 2)]) # Peter
-
print(-1 / 2) # -0.5
-
print(int(-0.5)) # 0
Explanation:
First the division takes place and -0.5 is the result.
The integer value of -0.5 is 0
And index 0 is ‘Peter'
Q607 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 51Skipped
Q641 – Data Types
What is the expected output of the following code if the user enters 4 and 7?
- x = input()
- y = int(input())
- print(x * y)
7777
Explanation
This choice is incorrect because the code does not involve adding or repeating the second input ‘7’. It multiplies the string ‘4’ by the integer 7, resulting in the repeated string ‘4444444’, not the repeated ‘7’.
28
Explanation
This choice is incorrect because the code does not perform addition or concatenation of the inputs. It multiplies the string ‘4’ by the integer 7, resulting in the repeated string ‘4444444’, not the sum of the inputs.
47
Explanation
This choice is incorrect because the code does not concatenate the inputs. It multiplies the string ‘4’ by the integer 7, resulting in the repeated string ‘4444444’, not a combination of the inputs.
Correct answer
4444444
Explanation
The code takes two inputs from the user, one as a string and the other as an integer. When the user enters 4 and 7, the first input ‘4’ is stored as a string in variable x, and the second input ‘7’ is converted to an integer and stored in variable y. When the print statement is executed, it multiplies the string ‘4’ by the integer 7, resulting in the string ‘4444444’.
Overall explanation
Topics: input() int() multiply operator string concatenation
Try it yourself:
-
x = input() # Input: 4
-
y = int(input()) # Input: 7
- x, y = ‘4’, int(‘7’) # Just for convenience
- print(x * y) # 4444444
- print(‘4’ * int(‘7’)) # 4444444
- print(‘4’ * 7) # 4444444
Explanation:
Like always input() returns a string
The second one will be cast to an integer
Then the string '4' will be multiplied seven times
and the result is the string '4444444'
Q641 (Please refer to this number, if you want to write me about this question.)
Domain
02 – Data Types
Question 52Skipped
Q628 – Error Handling
The top-most Python exception is named:
TopException
Explanation
There is no built-in exception class named TopException in Python. The top-most exception class is BaseException, which is the parent class for all other built-in exception classes in Python.
PythonException
Explanation
There is no built-in exception class named PythonException in Python. The top-most exception class is BaseException, which is the correct choice for the top-most Python exception.
Exception
Explanation
Exception is a built-in class in Python that serves as the base class for all user-defined exceptions. While it is a common exception class used in Python, it is not the top-most exception class. BaseException is the correct choice for the top-most Python exception.
Correct answer
BaseException
Explanation
BaseException is the top-most built-in exception class in Python. It serves as the base class for all built-in exceptions and is the parent class for all other exception classes in Python. Therefore, it is the correct choice for the top-most Python exception.
Overall explanation
Topic: BaseException Exception hierarchy
Explanation:
Nothing much to explain here.
You just have to remember that.
Check the official documentation about the exception hierarchy:
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
Q628 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 53Skipped
Q603 – Data Aggregates
What is the expected output of the following code?
- data = (1, 2, 3, 4)
- data = data[-2:-1]
- data = data[-1]
- print(data)
4
Explanation
The code slices the tuple ‘data’ from the second to last element to the first element (-2:-1), resulting in a new tuple with the value (3,). It then accesses the last element of this new tuple, which is 3, and prints it as the output. Therefore, this choice is incorrect.
2
Explanation
The code slices the tuple ‘data’ from the second to last element to the first element (-2:-1), resulting in a new tuple with the value (3,). However, it then accesses the second element of this new tuple, which is not present, resulting in an error. Therefore, this choice is incorrect.
1
Explanation
The code actually slices the tuple ‘data’ from the second to last element to the first element (-2:-1), resulting in a new tuple with the value (3,). Then, it accesses the first element of this new tuple, which is 3, and prints it as the output.
Correct answer
3
Explanation
The code first assigns a tuple (1, 2, 3, 4) to the variable ‘data’. Then, it slices the tuple from the second to last element to the first element (-2:-1), resulting in a new tuple with the value (3,). Finally, it accesses the last element of this new tuple, which is 3, and prints it as the output.
Overall explanation
Topics: tuple slicing tuple indexing
Try it yourself:
- data = (1, 2, 3, 4)
- data = data[-2:-1]
- print(data) # (3,)
- data = data[-1]
- print(data) # 3
Explanation:
Slicing with negative indexes.
A start of -2 takes the second last element.
That would be the value 3
The index -1 is the last element.
The end is always exclusive.
That leaves (3,)
The index -1 is again the last element of that,
which is the value 3
Q603 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates
Question 54Skipped
Q620 – Functions
What is the expected output of the following code?
-
def func(x):
-
if x % 2 == 0: -
return 1 -
else: -
return 2 -
print(func(func(2)))
The code is erroneous.
Explanation
The code is not erroneous as it follows a clear logic flow. The function func correctly returns 1 for even numbers and 2 for odd numbers, leading to a predictable output.
0
Explanation
The code does not involve any operations that would result in the output being 0. The logic within the functions ensures that the output will be either 1 or 2 based on the input provided.
Correct answer
2
Explanation
The input to the outer function func is 2, which is an even number. Therefore, the inner function call func(2) will return 1. As a result, the outer function call func(1) will return 2, leading to the output of 2.
1
Explanation
The code does not involve any operations that would result in the output being 1. The logic within the functions ensures that the output will be either 1 or 2 based on the input provided.
Overall explanation
Topics: def if else modulus operator
Try it yourself:
-
def func(x):
-
if x % 2 == 0: -
print("if", end=" -> ") -
return 1 -
else: -
print("else", end=" -> ") -
return 2 -
print(func(func(2))) # if -> else -> 2
Explanation:
The condition x % 2 == 0 tests for even numbers.
The first function call func(2) passes an even number
and the return value will be 1
The second function call func(1) passes an odd number
and the return value will be 2
Q620 (Please refer to this number, if you want to write me about this question.)
Domain
06 – Functions
Question 55Skipped
Q627 – Operators
What is the expected output of the following code?
x = 28
y = 8
print(x / y)
print(x // y)
print(x % y)
- 3.0
- 3
- 2
Explanation
The code incorrectly calculates the result of x divided by y using the "/" operator, which results in a floating-point division, so the output should be 3.5. Then, it calculates the result of x divided by y using the "//" operator, which performs integer division and returns the whole number part of the division, so the output should be 3. The remainder of x divided by y using the "%" operator should be 2.
- 3.5
- 3.5
- 2
Explanation
The code correctly calculates the result of x divided by y using the "/" operator, which results in a floating-point division, so the output is 3.5. However, it incorrectly calculates the result of x divided by y using the "//" operator, which should return 3 instead of 3.5. The remainder of x divided by y using the "%" operator should be 2.
- 3
- 3.5
- 4
Explanation
The code incorrectly calculates the result of x divided by y using the "/" operator, which results in a floating-point division, so the output should be 3.5. Then, it calculates the result of x divided by y using the "//" operator, which performs integer division and returns the whole number part of the division, so the output should be 3. The remainder of x divided by y using the "%" operator should be 4.
Correct answer
- 3.5
- 3
- 4
Explanation
The code first calculates the result of x divided by y using the "/" operator, which results in a floating-point division, so the output is 3.5. Then, it calculates the result of x divided by y using the "//" operator, which performs integer division and returns the whole number part of the division, so the output is 3. Finally, it calculates the remainder of x divided by y using the "%" operator, which returns the remainder after integer division, so the output is 4.
Overall explanation
Topic: arithmetic operators
Try it yourself:
- a = 28
- b = 8
- print(a / b) # 3.5
- print(a // b) # 3
- print(a % b) # 4
Explanation:
Everything normal here.
The division operator the floor division operator
and the modulus operator all do their normal job.
Q627 (Please refer to this number, if you want to write me about this question.)
Domain
03 – Operators
Question 56Skipped
Q639 – Error Handling
The following statement …
assert x != 0
Correct answer
will stop the program if x is equal to 0
Explanation
This choice is correct because the assert statement in Python is used to check if a condition is true. If the condition is false, the program will stop and raise an AssertionError. In this case, if x is equal to 0, the condition will be false, and the program will stop.
will stop the program if x is not equal to 0
Explanation
This choice is incorrect. The assert statement in Python will only stop the program if the condition provided is false. In this case, the program will not stop if x is not equal to 0, as the condition is checking for x not being equal to 0.
has no effect.
Explanation
This choice is incorrect. The assert statement in Python has an effect by checking the condition provided. In this case, the statement will check if x is not equal to 0 and raise an AssertionError if the condition is false.
is erroneous.
Explanation
This choice is incorrect. The assert statement in Python is a valid way to check conditions and raise an AssertionError if the condition is false. In this case, the statement is checking if x is not equal to 0, which is a valid use of the assert statement.
Overall explanation
Topic: assert
Try it yourself:
-
x = 7
-
assert x != 0
-
print(‘Hello’) # Hello
-
x = 0
-
assert x != 0 # AssertionError
-
print(‘Hello’)
Explanation:
If the assertion (here x != 0) is true,
the program will continue.
Otherwise an AssertionError occurs.
Q639 (Please refer to this number, if you want to write me about this question.)
Domain
08 – Error Handling
Question 57Skipped
Q608 – Data Aggregates
What is the expected output of the following code?
- data = [‘abc’, ‘def’, ‘abcde’, ‘efg’]
- print(max(data))
abc
Explanation
‘abc’ is not the maximum value in the list ‘data’, so it is not the expected output of the code.
None of the above.
Explanation
The expected output of the code is ‘efg’, which is one of the choices provided. Therefore, this choice is incorrect.
The code is erroneous.
Explanation
The code is not erroneous; it is simply finding the maximum value in the list ‘data’. The expected output is ‘efg’, so this choice is incorrect.
def
Explanation
‘def’ is not the maximum value in the list ‘data’, so it is not the expected output of the code.
abcde
Explanation
‘abcde’ is not the maximum value in the list ‘data’, so it is not the expected output of the code.
Correct answer
efg
Explanation
The max() function in Python returns the maximum value from a list. In this case, the maximum value in the list ‘data’ is ‘efg’, so the expected output is ‘efg’.
Overall explanation
Topics: list max()
Try it yourself:
-
data = [‘abc’, ‘def’, ‘abcde’, ‘efg’]
-
print(max(data)) # efg
-
print(ord(‘a’)) # 97
-
print(ord(‘d’)) # 100
-
print(ord(‘e’)) # 101
Explanation:
Python’s built-in function max() is given a list with strings.
max() will look for the character with the highest Unicode character number,
which in this case is e
Q608 (Please refer to this number, if you want to write me about this question.)
Domain
04 – Data Aggregates