Python ITS-303 Test Exam II (with questions from all areas) – Results

Python ITS-303 Test Exam II (with questions from all areas) – Results

Back to result overview

Attempt 2

All domains

  • 57 all
  • 0 correct
  • 0 incorrect
  • 57 skipped
  • 0 marked

Collapse all questions

Question 1Skipped

Q247 – Data Aggregates

What is the expected output of the following code?

  1. data = [[0, 1, 2, 3] for i in range(2)]
  2. print(data[2][0])

Correct answer

The code is erroneous.

Explanation

The code is erroneous because it tries to access an index that is out of bounds for the ‘data’ list. The ‘data’ list has only two elements, so trying to access index 2 will result in an IndexError.

2

Explanation

The code will not output 2 because the ‘data’ list is a list of lists, and the index [2][0] is trying to access the first element of the third inner list. However, there are only two inner lists in the ‘data’ list, so index 2 is out of bounds.

0

Explanation

The code will not output 0 because the ‘data’ list is a list of lists, and the index [2][0] is trying to access the first element of the third inner list. However, there are only two inner lists in the ‘data’ list, so index 2 is out of bounds.

1

Explanation

The code will not output 1 because the ‘data’ list is a list of lists, and the index [2][0] is trying to access the first element of the third inner list. However, there are only two inner lists in the ‘data’ list, so index 2 is out of bounds.

Overall explanation

Topics: list comprehension list indexing IndexError

Try it yourself:

  1. data = [[0, 1, 2, 3] for i in range(2)]

  2. print(data[2][0]) # IndexError: list index out of range

  3. print(data) # [[0, 1, 2, 3], [0, 1, 2, 3]]

  4. print(data[0]) # [0, 1, 2, 3]

  5. print(data[1]) # [0, 1, 2, 3]

Explanation:

range(2) has two elements: 0 and 1

Therefore the outer list will have two elements.

And data[2] does not exist.

Q247 (Please refer to this number, if you want to write me about this question.)

Domain

04 – Data Aggregates

Question 2Skipped

Q228 – I/O

What is the expected output of the following code?

  1. colors = [‘red\n’, ‘yellow\n’, ‘blue\n’]

  2. file = open(‘wellert.txt’, ‘w+’)

  3. file.writelines(colors)

  4. file.close()

  5. file.seek(0)

  6. for line in file:

  7. print(line)
    
  8. red

  9. yellow

  10. blue

Explanation

‘red\n’, ‘yellow\n’, ‘blue\n’ is not the expected output because the lines are written to the file but not read and printed correctly due to the incorrect file pointer position. Additionally, the newline characters are not removed when printing the lines.

['red\n', 'yellow\n', 'blue\n']

Explanation

[‘red\n’, ‘yellow\n’, ‘blue\n’] is not the expected output because the lines are written to the file but not read and printed correctly due to the incorrect file pointer position.

Correct answer

The code is erroneous.

Explanation

The code is erroneous because after writing the lines to the file, the file pointer is not reset to the beginning of the file before reading the lines. This results in the file being read from the end, and no lines are printed.

redyellowblue

Explanation

‘redyellowblue’ is not the expected output because the lines are written to the file but not read and printed correctly due to the incorrect file pointer position. Additionally, the newline characters are not removed when printing the lines.

Overall explanation

Topics: open() writelines() seek() close() for

Try it yourself:

  1. colors = [‘red\n’, ‘yellow\n’, ‘blue\n’]
  2. file = open(‘wellert.txt’, ‘w+’)
  3. file.writelines(colors)
  4. file.close()
  5. file.seek(0) # ValueError: I/O operation on closed file.
  6. for line in file:
  7. print(line)
    
  8. file.close()

Explanation:

The file gets closed too early.

All operations on the file need the be finished before you can close it.

Q228 (Please refer to this number, if you want to write me about this question.)

Domain

07 – I/O

Question 3Skipped

Q234 – Modules

Which of the following functions immediately terminates a program?

sys.terminate()

Explanation

The sys.terminate() function does not exist in the sys module in Python. Therefore, it cannot be used to immediately terminate a program.

sys.stop()

Explanation

The sys.stop() function does not exist in the sys module in Python. Therefore, it cannot be used to immediately terminate a program.

sys.halt()

Explanation

The sys.halt() function does not exist in the sys module in Python. Therefore, it cannot be used to immediately terminate a program.

Correct answer

sys.exit()

Explanation

The sys.exit() function is used to immediately terminate a program in Python. It raises the SystemExit exception, which can be caught and handled if necessary, but by default, it will exit the program without any further execution.

None

Explanation

The "None" choice does not represent a function in the sys module that can be used to immediately terminate a program. It is not a valid option for terminating a program in Python.

Overall explanation

Topic: sys.exit()

Try it yourself:

  1. import sys
  2. print(‘Before the exit!’) # Before the exit!
  3. sys.exit()
  4. sys.halt() # AttributeError: …

  5. sys.stop() # AttributeError: …

  6. sys.terminat() # AttributeError: …

  7. print(‘After the exit!’)

Explanation:

The method in Python to immediately terminate a program is sys.exit()

The others methods do not exist.

Q234 (Please refer to this number, if you want to write me about this question.)

Domain

09 – Modules

Question 4Skipped

Q230 – Data Types

What is the expected output of the following code if the user enters 11 and 4 ?

  1. x = int(input())
  2. y = int(input())
  3. x = x % y
  4. x = x % y
  5. y = y % x
  6. print(y)

Correct answer

1

Explanation

The code takes two integer inputs from the user, calculates the remainder of x divided by y twice, and then calculates the remainder of y divided by the result of the previous operation. For the inputs 11 and 4, the first remainder operation results in x = 3, and the second remainder operation results in x = 3 % 4 = 3. Finally, y = 4 % 3 = 1, so the expected output is 1.

3

Explanation

The code involves multiple modulo operations on the input values x and y, but the calculations are incorrect. For the inputs 11 and 4, the first remainder operation results in x = 3, and the second operation should result in x = 3 % 4 = 3. However, the final operation y = 4 % 3 = 1 is incorrect. Therefore, the expected output is not 3.

4

Explanation

The code performs multiple modulo operations on the input values x and y, but the calculations are incorrect. For the inputs 11 and 4, the first remainder operation results in x = 3, and the second operation should result in x = 3 % 4 = 3. However, the final operation y = 4 % 3 = 1 is incorrect. Therefore, the expected output is not 4.

2

Explanation

The code performs two modulo operations on the input values x and y, but the calculations are incorrect. For the inputs 11 and 4, the first remainder operation results in x = 3, and the second operation should result in x = 3 % 4 = 3. However, the final operation y = 4 % 3 = 1 is incorrect. Therefore, the expected output is not 2.

Overall explanation

Topics: input() modulus operator

Try it yourself:

  1. x = int(input()) # Input: 11

  2. y = int(input()) # Input: 4

  3. x, y = 11, 4 # Just for convenience
  4. x = x % y
  5. print(11 % 4) # 3
  6. x = x % y
  7. print(3 % 4) # 3
  8. y = y % x
  9. print(4 % 3) # 1
  10. print(y) # 1

Explanation:

input() returns strings, but the int() function casts them to integers.

Then you have to concentrate with all the modulus operators.

Q230 (Please refer to this number, if you want to write me about this question.)

Domain

02 – Data Types

Question 5Skipped

Q255 – Modules

What is the expected output of the following code?

  1. import os

  2. os.mkdir(‘thumbnails’)

  3. os.chdir(‘thumbnails’)

  4. sizes = [‘small’, ‘medium’, ‘large’]

  5. for size in sizes:

  6. os.mkdir(size)
    
  7. print(os.listdir())

Correct answer

['large', 'medium', 'small']

Explanation

The code first creates a directory called ‘thumbnails’ and then changes the current working directory to ‘thumbnails’. It then creates three directories inside ‘thumbnails’ with the names ‘small’, ‘medium’, and ‘large’. Finally, it prints the list of files and directories in the current working directory, which will be [‘large’, ‘medium’, ‘small’].

[]

Explanation

This choice is incorrect because the code creates directories inside the ‘thumbnails’ directory and then lists the contents of the current working directory. Since the current working directory is ‘thumbnails’, the output will not be an empty list.

['.', 'large', 'medium', 'small']

Explanation

This choice is incorrect because the code only creates directories inside the ‘thumbnails’ directory and then lists the contents of the current working directory. The output will not include the current directory ‘.’ in the list.

['.', '..', 'large', 'medium', 'small']

Explanation

This choice is incorrect because the code only creates directories inside the ‘thumbnails’ directory and then lists the contents of the current working directory. The output will not include the parent directory ‘..’ in the list.

Overall explanation

Topics: import os mkdir() chdir() list for listdir()

Try it yourself:

  1. import os

  2. To be able to run the file more often

  3. you have to remove the ‘thumbnails’ directory:

  4. import shutil

  5. shutil.rmtree(‘thumbnails’)

  6. os.mkdir(‘thumbnails’)

  7. os.chdir(‘thumbnails’)

  8. sizes = [‘small’, ‘medium’, ‘large’]

  9. for size in sizes:

  10. os.mkdir(size)
    
  11. print(os.listdir()) # [‘large’, ‘medium’, ‘small’]

Explanation:

This is pretty straight forward.

You make the directory thumbnails

you change into it,

you make the three directories small medium large

and then you list them.

But you need the knowledge, that listdir() never includes

the special entries . and ..

https://www.tutorialspoint.com/python/os_listdir.htm

Q255 (Please refer to this number, if you want to write me about this question.)

Domain

09 – Modules

Question 6Skipped

Q239 – Control Flow

How many stars will the following code send to the monitor?

  1. x = 0
  2. while x < 6:
  3. x += 1
    
  4. if x % 2 == 0:
    
  5.     continue
    
  6. print('*')
    

two

Explanation

The code prints a star only when x is an odd number. As the loop starts with x = 0, which is an even number, the first odd number encountered is 1, and the second odd number is 3. Therefore, the code will send two stars to the monitor.

zero

Explanation

Since the code only prints a star when x is an odd number, and the loop starts with x = 0, which is an even number, no stars will be printed. Therefore, the code will not send any stars to the monitor, resulting in zero stars.

one

Explanation

The code prints a star only when x is an odd number. As the loop starts with x = 0, which is an even number, the first odd number encountered is 1. Therefore, the code will send one star to the monitor.

Correct answer

three

Explanation

The code initializes x to 0 and enters a while loop that increments x by 1 in each iteration. If x is even (x % 2 == 0), the loop continues without printing anything. Therefore, the code will print a star for odd values of x, which are 1, 3, and 5, resulting in three stars being sent to the monitor.

Overall explanation

Topics: while if continue

Try it yourself:

  1. x = 0
  2. while x < 6:
  3. print('1. x:', x)         # 0 -> 1 -> 2 -> 3 -> 4 -> 5
    
  4. x += 1
    
  5. print('2. x:', x)         # 1 -> 2 -> 3 -> 4 -> 5 -> 6
    
  6. if x % 2 == 0:
    
  7.     print('x in if:', x)  # 2 -> 4 -> 6
    
  8.     continue
    
  9. print('x behind if:', x)  # 1 -> 3 -> 5
    
  10. print('*')
    
  11. """
  12. """

Explanation:

When x is 24 and 6 the if condition is True

and the continue gets triggered.

The iteration ends directly and the print() function doesn’t get executed.

When x is 13 and 5 the if condition is False

the continue does not get triggered

and those three times the print() function gets executed.

Therefore there will be three stars printed.

Q239 (Please refer to this number, if you want to write me about this question.)

Domain

05 – Control Flow

Question 7Skipped

Q249 – Error Handling

Which of the following is false?

try statement can have a finally clause without an except clause.

Explanation

A try statement can have a finally clause without an except clause to ensure certain code is always executed, even if an exception is not raised. This statement is true and valid in Python error handling.

try statement can have one or more except clauses.

Explanation

A try statement can have one or more except clauses to handle specific exceptions that may occur within the try block. This statement is true and valid in Python error handling.

try statement can have a finally clause and an except clause.

Explanation

A try statement can have both a finally clause and an except clause to handle exceptions and execute cleanup code. This statement is true and valid in Python error handling.

Correct answer

try statement can have one or more finally clauses.

Explanation

A try statement can have one or more finally clauses to execute cleanup code regardless of whether an exception is raised or not. This statement is true and valid in Python error handling.

Overall explanation

Topics: try except finally

Try it yourself:

  1. A try statement can have a finally clause and an except clause.

  2. try:

  3. print('try')      # try
    
  4. except:

  5. print('except')
    
  6. finally:

  7. print('finally')  # finally
    
  8. A try statement can have a finally clause without an except clause.

  9. try:

  10. print('try')      # try
    
  11. finally:

  12. print('finally')  # finally
    
  13. A try statement can have one or more except clauses.

  14. try:

  15. # value = input('Please enter a number!')
    
  16. value = 'one'
    
  17. # value = '0'
    
  18. number = 100 / int(value)
    
  19. except ValueError:

  20. print('Please enter an integer!')
    
  21. except ZeroDivisionError:

  22. print('Please do not enter zero!')
    
  23. else:

  24. print('Result:', number)
    
  25. """

  26. A try statement can have one or more finally clauses.

  27. try:

  28. print('try')
    
  29. finally:

  30. print('finally 1')
    
  31. finally: # SyntaxError: invalid syntax

  32. print('finally 2')
    
  33. """

Explanation:

Yes, a try statement can have one or more except clauses.

Yes, a try statement can have a finally clause and an except clause.

Yes, a try statement can have a finally clause without an except clause.

But NO, a try statement can NOT have more finally clauses.

Q249 (Please refer to this number, if you want to write me about this question.)

Domain

08 – Error Handling

Question 8Skipped

Q248 – Control Flow

The ABC Video company needs a way to determine the cost

that a customer will pay for renting a DVD.

The cost is dependent on the time of day the DVD is returned.

However, there are also special rates on Thursdays and Sundays.

The fee structure is shown in the following list:

The cost is $1.59 per night.

If the DVD is returned after 8 PM, the customer will be charged an extra day.

If the video is rented on a Sunday,

the customer gets 30% off for as long as they keep the video.

If the video is rented on a Thursday,

the customer gets 50% off for as long as they keep the video.

You need to write code to meet the requirements.

  1. ABC Video, DVD Rental Calculator

  2. ontime = input(‘Was the video returned before 8 pm? y or n’).lower()

  3. days_rented = int(input(‘How many days was the video rented?’))

  4. day_rented = input(‘What day was the video rented?’).capitalize()

  5. cost_per_day = 1.59

  6. if ontime XXX

  7. days_rented += 1
    
  8. if day_rented YYY

  9. total = (days_rented * cost_per_day) * .7
    
  10. elif day_rented ZZZ

  11. total = (days_rented * cost_per_day) * .5
    
  12. else:

  13. total = (days_rented * cost_per_day)
    
  14. print(‘Cost of the DVD rental is: $’, total)

What should you insert instead of XXXYYY and ZZZ?

  1. XXX -> == ‘y’:
  2. YYY -> == ‘Sunday’:
  3. ZZZ -> == ‘Thursday’:

Explanation

For XXX, the condition should check if the video was returned after 8 PM, so it should be ‘== ‘n’:’ to add an extra day if the video was returned after 8 PM. For YYY, the condition should check if the day rented is Sunday, so it should be ‘== ‘Sunday’:’ to apply the 30% discount. For ZZZ, the condition should check if the day rented is Thursday, so it should be ‘== ‘Thursday’:’ to apply the 50% discount.

  1. XXX -> == ‘n’:
  2. YYY -> is ‘Sunday’:
  3. ZZZ -> is ‘Thursday’:

Explanation

For XXX, the condition should check if the video was returned after 8 PM, so it should be ‘== ‘n’:’ to add an extra day if the video was returned after 8 PM. For YYY, the condition should check if the day rented is Sunday, so it should be ‘== ‘Sunday’:’ to apply the 30% discount. For ZZZ, the condition should check if the day rented is Thursday, so it should be ‘== ‘Thursday’:’ to apply the 50% discount.

  1. XXX -> == ‘y’:
  2. YYY -> >= ‘Sunday’:
  3. ZZZ -> >= ‘Thursday’:

Explanation

For XXX, the condition should check if the video was returned after 8 PM, so it should be ‘== ‘n’:’ to add an extra day if the video was returned after 8 PM. For YYY, the condition should check if the day rented is Sunday, so it should be ‘>= ‘Sunday’:’ which is not a valid comparison. For ZZZ, the condition should check if the day rented is Thursday, so it should be ‘>= ‘Thursday’:’ which is not a valid comparison.

Correct answer

  1. XXX -> == ‘n’:
  2. YYY -> == ‘Sunday’:
  3. ZZZ -> == ‘Thursday’:

Explanation

For XXX, the condition should check if the video was returned after 8 PM, so it should be ‘== ‘n’:’ to add an extra day if the video was returned after 8 PM. For YYY, the condition should check if the day rented is Sunday, so it should be ‘== ‘Sunday’:’ to apply the 30% discount. For ZZZ, the condition should check if the day rented is Thursday, so it should be ‘== ‘Thursday’:’ to apply the 50% discount.

  1. XXX -> != ‘n’:
  2. YYY -> is ‘Sunday’:
  3. ZZZ -> is ‘Thursday’:

Explanation

For XXX, the condition should check if the video was returned after 8 PM, so it should be ‘!= ‘n’:’ to add an extra day if the video was returned after 8 PM. For YYY, the condition should check if the day rented is Sunday, so it should be ‘== ‘Sunday’:’ to apply the 30% discount. For ZZZ, the condition should check if the day rented is Thursday, so it should be ‘== ‘Thursday’:’ to apply the 50% discount.

Overall explanation

Topics: input() int() if elif else

Try it yourself:

  1. ABC Video, DVD Rental Calculator

  2. ontime = input(‘Was the video returned before 8pm? y or n’).lower()

  3. ontime = ‘y’

  4. ontime = ‘n’

  5. days_rented = int(input(‘How many days was the video rented?’))

  6. days_rented = int(‘4’)

  7. day_rented = input(‘What day was the video rented?’).capitalize()

  8. day_rented = ‘sunday’.capitalize()

  9. day_rented = ‘thursday’.capitalize()

  10. day_rented = ‘monday’.capitalize()

  11. cost_per_day = 1.59

  12. if ontime == ‘n’:

  13. days_rented += 1
    
  14. if day_rented == ‘Sunday’:

  15. total = (days_rented * cost_per_day) * .7
    
  16. elif day_rented == ‘Thursday’:

  17. total = (days_rented * cost_per_day) * .5
    
  18. else:

  19. total = (days_rented * cost_per_day)
    
  20. print(‘Cost of the DVD rental is: $’, total)

  21. n, 4, monday -> 7.95

  22. y, 4, monday -> 6.36

  23. y, 4, thursday -> 3.18

  24. y, 4, sunday -> 4.452

Explanation:

At this company to return a video on time means to return it before 8 PM.

Otherwise one day is added to the amount of rented days.

If you return your video on a Sunday you get 30% off.

Meaning you only pay 70%.

And if you return your video on a Thursday, you pay only half (50%).

Q248 (Please refer to this number, if you want to write me about this question.)

Domain

05 – Control Flow

Question 9Skipped

Q226 – Data Types

What is the expected output of the following code?

print(float('1.3'))

13

Explanation

The output of the code will not be ’13’ because the float() function in Python does not interpret the input string as a concatenated number. It will only consider the characters before and after the decimal point, so ‘1.3’ will be converted to 1.3, not 13.

1,3

Explanation

The output of the code will not be ‘1,3’ because the float() function in Python expects a period (.) as the decimal separator, not a comma. Therefore, ‘1,3’ is not a valid float representation.

The code is erroneous.

Explanation

The code is not erroneous as it follows the correct syntax and uses a valid function. The float() function will successfully convert the string ‘1.3’ to a floating-point number.

Correct answer

1.3

Explanation

The float() function in Python converts a string representation of a number to a floating-point number. In this case, ‘1.3’ is a valid string representation of a float, so the output of the code will be 1.3.

Overall explanation

Topic: float()

Try it yourself:

print(float('1.3'))  # 1.3

Explanation:

The function float() does its normal job here

and converts the string to a float.

Q226 (Please refer to this number, if you want to write me about this question.)

Domain

02 – Data Types

Question 10Skipped

Q238 – Operators

What is the expected output of the following code?

x = 1 + 1 // 2 + 1 / 2 + 2

print(x)

Correct answer

3.5

Explanation

The code performs the following operations in order: integer division (1 // 2 = 0), division (1 / 2 = 0.5), and addition (0 + 0.5 + 2 = 2.5). Therefore, the expected output is 2.5 + 2 = 3.5.

3

Explanation

The code includes both integer and float division, which results in a float value. The final calculation is 2.5 + 2 = 3.5, so the expected output is 3.5.

4

Explanation

The code does not result in a final value of 4 after performing the specified operations. The correct calculation leads to 3.5 as the output, not 4.

4.0

Explanation

The code involves operations that result in a float value. The final calculation is 2.5 + 2 = 3.5, so the expected output is 3.5, not 4.0.

Overall explanation

Topics: arithmetic operators operator precedence

Try it yourself:

  1. x = 1 + 1 // 2 + 1 / 2 + 2

  2. print(x) # 3.5

  3. print(1 + 1 // 2 + 1 / 2 + 2) # 3.5

  4. print(1 + (1 // 2) + 1 / 2 + 2) # 3.5

  5. print(1 + 0 + 1 / 2 + 2) # 3.5

  6. print(1 + 0 + (1 / 2) + 2) # 3.5

  7. print(1 + 0 + 0.5 + 2) # 3.5

  8. print((1 + 0) + 0.5 + 2) # 3.5

  9. print(1 + 0.5 + 2) # 3.5

  10. print((1 + 0.5) + 2) # 3.5

  11. print(1.5 + 2) # 3.5

  12. print(3.5) # 3.5

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".

Therefore the order of operations here is: // -> / -> + -> + -> +

Q238 (Please refer to this number, if you want to write me about this question.)

Domain

03 – Operators

Question 11Skipped

Q208 – Operators

What is the expected output of the following code?

  1. x = True
  2. y = False
  3. x = x or y
  4. y = x and y
  5. x = x or y
  6. print(x, y)

False True

Explanation

The code first assigns the value of x to True and y to False. Then, it updates the value of x to the result of the logical OR operation between x and y, which is True. Next, it updates the value of y to the result of the logical AND operation between x and y, which is False. Therefore, the expected output is not False True.

False False

Explanation

The code first assigns the value of x to True and y to False. Then, it updates the value of x to the result of the logical OR operation between x and y, which is True. Next, it updates the value of y to the result of the logical AND operation between x and y, which is False. Therefore, the expected output is not False False.

True True

Explanation

The code first assigns the value of x to True and y to False. Then, it updates the value of x to the result of the logical OR operation between x and y, which is True. Next, it updates the value of y to the result of the logical AND operation between x and y, which is False. Finally, it updates the value of x to the result of the logical OR operation between x and y, which is True. Therefore, the expected output is not True True.

Correct answer

True False

Explanation

The code first assigns the value of x to True and y to False. Then, it updates the value of x to the result of the logical OR operation between x and y, which is True. Next, it updates the value of y to the result of the logical AND operation between x and y, which is False. Finally, it updates the value of x to the result of the logical OR operation between x and y, which is True. Therefore, the expected output is True False.

Overall explanation

Topics: logical operators boolean

Try it yourself:

  1. x = True
  2. y = False
  3. x = x or y # True or False -> True
  4. y = x and y # True and False -> False
  5. x = x or y # True or False -> True
  6. print(x, y) # True False

Explanation:

Nothing changes here.

The variables always get assigned the value they had before.

Q208 (Please refer to this number, if you want to write me about this question.)

Domain

03 – Operators

Question 12Skipped

Q203 – Data Aggregates

What is the expected output of the following code?

  1. a = [1, 2, 3, 4, 5]
  2. print(a[3:0:-1])

The code is erroneous.

Explanation

The code is not erroneous. It correctly slices the list ‘a’ and outputs a valid result.

[4, 3, 2, 1]

Explanation

The code slices the list ‘a’ starting from index 3 (value 4) and moving backwards towards index 0 (value 1) with a step size of -1. This would not include the value at index 0 (value 1) in the output, resulting in [4, 3, 2].

[4, 3]

Explanation

The code slices the list ‘a’ starting from index 3 (value 4) and moving backwards towards index 0 (value 1) with a step size of -1. This results in the output [4, 3].

Correct answer

[4, 3, 2]

Explanation

The code slices the list ‘a’ starting from index 3 (value 4) and moving backwards towards index 0 (value 1) with a step size of -1. This results in the output [4, 3, 2].

Overall explanation

Topic: list slicing

Try it yourself:

  1. a = [1, 2, 3, 4, 5]
  2. print(a[3:0:-1]) # [4, 3, 2]

Explanation:

List slicing: [start(inclusive):end(exclusive):step]

The step is negative here.

That makes the slice be build from right to left (start interchanges with end).

The start is the index 3 (inclusive) and the end is index 0 (exclusive).

Therefore we will get index 3 index 2 and index 1

which are the numbers 432

Q203 (Please refer to this number, if you want to write me about this question.)

Domain

04 – Data Aggregates

Question 13Skipped

Q212 – Functions

Which of the following items are present in the function header?

parameter list

Explanation

The parameter list is a crucial component of the function header as it defines the input values that the function can accept and operate on. Without the parameter list, the function header would be incomplete and the function would not be able to receive and process input values.

function name

Explanation

The function name alone is not sufficient in the function header. While the function name is necessary to define the function, it must be accompanied by the parameter list to specify the input values that the function expects.

Correct answer

function name and parameter list

Explanation

The function header includes the function name, which is used to identify and call the function, and the parameter list, which defines the input values that the function can accept and operate on. These two elements are essential in defining the function and its behavior.

return value

Explanation

The return value is not typically included in the function header. While the return value specifies the output of the function, it is not part of the function header, which primarily consists of the function name and parameter list.

Overall explanation

Topics: def parameter function header

Try it yourself:

  1. def func(para1, para2): # This line is the function header
  2.  para1 + para2
    

Explanation:

In the function header is the keyword def

the function name

and the parameter list.

Q212 (Please refer to this number, if you want to write me about this question.)

Domain

06 – Functions

Question 14Skipped

Q250 – Data Aggregates

You develop a Python application for your company.

list named employees contains 200 employee names,

the last five being company management.

You need to slice the list to display all employees excluding management.

Which code segments can you use?

Choose two.

employees[1:-4]

Explanation

The code segment employees[1:-4] will start slicing the list from the second element, excluding the first employee, and will go up to the last four elements. This will exclude the first employee and the management employees, which is not the desired outcome in this scenario.

Correct selection

employees[:-5]

Explanation

Using the slice notation [:-5] will return all elements of the list up to the last five, excluding the management employees at the end of the list. This code segment correctly slices the list to display all employees except for the management.

employees[1:-5]

Explanation

The code segment employees[1:-5] will start slicing the list from the second element, excluding the first employee, and will go up to the last five elements. This will exclude the first employee and the management employees, which is not the desired outcome in this scenario.

employees[0:-4]

Explanation

Using employees[0:-4] will exclude the last four elements of the list, which includes the management employees. This code segment does not correctly slice the list to display all employees excluding management.

Correct selection

employees[0:-5]

Explanation

The code segment employees[0:-5] is equivalent to employees[:-5] and will also return all elements of the list up to the last five, excluding the management employees at the end. This is a valid way to slice the list and display all employees except for the management.

Overall explanation

Topic: list slicing

Try it yourself:

  1. employees = []

  2. for i in range(1, 196):

  3. for i in range(1, 6): # Just for convenience

  4. employees.append('Employee' + str(i))
    
  5. for i in range(1, 6):

  6. employees.append('Manager' + str(i))
    
  7. print(employees)

  8. print(employees[:-5])

  9. print(employees[0:-5])

  10. print(employees[1:-4])

  11. One manager present and one employee is missing

  12. print(employees[1:-5]) # One employee is missing

  13. print(employees[0:-4]) # One manager present

Explanation:

List slicing: [start(inclusive):end(exclusive)]

The default value for the start is 0

Meaning you can write it or leave it out.

The negative index counts from the end.

The end is exclusive.

-1 cuts out one element.

-5 cuts out five elements.

And that is what you need here for the five managers.

Q250 (Please refer to this number, if you want to write me about this question.)

Domain

04 – Data Aggregates

Question 15Skipped

Q240 – Functions

What is the expected output of the following code?

  1. num = 1

  2. def func():

  3. num = 3
    
  4. print(num, end=' ')
    
  5. func()

  6. print(num)

Correct answer

3 1

Explanation

The expected output is "3 1" because within the function func(), a local variable num is assigned the value of 3. This local variable num is separate from the global variable num with a value of 1. When the function is called, it prints the local num (which is 3) and then outside the function, it prints the global num (which is 1).

The code is erroneous.

Explanation

The code is not erroneous as it will run without any errors. The output will be "3 1" as explained in the correct choice A.

3 3

Explanation

The expected output is not "3 3" because within the function func(), a local variable num is assigned the value of 3, not 1. The global variable num remains unchanged at 1. Therefore, the output will be "3 1".

1 1

Explanation

The expected output is not "1 1" because within the function func(), a local variable num is assigned the value of 3, not 1. The global variable num remains unchanged at 1. Therefore, the output will be "3 1".

1 3

Explanation

The expected output is not "1 3" because within the function func(), a local variable num is assigned the value of 3, not 1. The global variable num remains unchanged at 1. Therefore, the output will be "3 1".

Overall explanation

Topics: scope def print() with end parameter

Try it yourself:

  1. num = 1

  2. def func():

  3. num = 3              # Shadows name 'num' from outer scope
    
  4. print(num, end=' ')  # 3
    
  5. func()

  6. print(num) # 1

Explanation:

The num variable inside the function scope will be a different variable.

It will shadow the name of the num variable from the outer scope,

but it will be a different entity.

Q240 (Please refer to this number, if you want to write me about this question.)

Domain

06 – Functions

Question 16Skipped

Q237 – Operators

What value will be assigned to the x variable?

  1. z = 3
  2. y = 7
  3. x = y == z and y > z or z > y and z != y

1

Explanation

The expression does not result in a numerical value like 1. It evaluates to a boolean value (True or False) based on the comparison operations used in the expression.

0

Explanation

The expression does not result in a numerical value like 0. It evaluates to a boolean value (True or False) based on the comparison operations used in the expression.

Correct answer

False

Explanation

The expression evaluates as follows: (y == z) is False, (y > z) is True, (z > y) is False, and (z != y) is True. Therefore, the final result is False, which will be assigned to the x variable.

True

Explanation

The expression evaluates as False for the first part (y == z) and True for the second part (y > z). Since the ‘and’ operator requires both parts to be True for the whole expression to be True, the final result is False, not True.

Overall explanation

Topics: logical operators relational operators operator precedence

Try it yourself:

  1. z = 3
  2. y = 7
  3. x = y == z and y > z or z > y and z != y # False
  4. print(x) # False
  5. print(7 == 3 and 7 > 3 or 3 > 7 and 3 != 7) # False
  6. print(False and True or False and True) # False
  7. print((False and True) or (False and True)) # False
  8. print(False or False) # False
  9. print(False) # False

Explanation:

The operators here are from three different groups.

"Comparisons, Identity, Membership operators", "Logical AND", "Logical OR".

The three different comparison operators greater than operator

equal to operator not equal to operator have the highest precedence.

Then the logical and operator has a higher precedence

than the logical or operator

Q237 (Please refer to this number, if you want to write me about this question.)

Domain

03 – Operators

Question 17Skipped

Q242 – Data Types

Which of the following statements is false?

The None value can not be used as an argument of arithmetic operators.

Explanation

The None value can be used as an argument of arithmetic operators in Python. While it may not have a numerical value, it can still be used in expressions and calculations involving arithmetic operators without causing errors.

The None value can be compared with variables.

Explanation

The None value can be compared with variables in Python. It is often used in conditional statements to check if a variable has been assigned a value or if a function has returned a valid result.

The None value can be assigned to variables.

Explanation

The None value can indeed be assigned to variables in Python. It is commonly used to initialize a variable without assigning it a specific value, or to indicate that a function does not return any value.

Correct answer

The None value may not be used outside functions.

Explanation

The None value can be used both inside and outside functions in Python. It is a special constant that represents the absence of a value or a null value, and it can be assigned to variables, returned from functions, and used in various contexts throughout a Python program.

Overall explanation

Topic: None

Try it yourself:

  1. The None value can be assigned to variables.

  2. x = None

  3. print(x) # None

  4. The None value can be compared with variables.

  5. y = 3

  6. print(y is None) # False

  7. The None value cannot be used

  8. as an argument of arithmetic operators:

  9. print(None + 7) # TypeError: unsupported operand …

Explanation:

It is true that the None value can not be used

as an argument of arithmetic operators.

But the None value can be assigned and compared to variables.

And that can absolutely happen outside of a function.

Q242 (Please refer to this number, if you want to write me about this question.)

Domain

02 – Data Types

Question 18Skipped

Q219 – Functions

What is the expected output of the following code?

  1. data = ‘abcdefg’

  2. def func(text):

  3. del text[2]
    
  4. return text
    
  5. print(func(data))

acdef

Explanation

This output is not possible because the code will raise an error before reaching the print statement due to trying to delete an element from a string, which is not allowed.

abdef

Explanation

This output is not possible because the code will raise an error before reaching the print statement due to trying to delete an element from a string, which is not allowed.

Correct answer

The code is erroneous.

Explanation

The code is erroneous because strings in Python are immutable, meaning they cannot be modified in place. Therefore, trying to delete an element from a string using del text[2] will result in a TypeError.

abcef

Explanation

This output is not possible because the code will raise an error before reaching the print statement due to trying to delete an element from a string, which is not allowed.

Overall explanation

Topics: def del string (immutable) string indexing

Try it yourself:

  1. data = ‘abcdefg’

  2. def func(text):

  3. # del text[2]  # TypeError: ...
    
  4. return text
    
  5. print(func(data))

  6. Strings are immutable

  7. The indexes are readable but not writeable:

  8. s = ‘Hello’

  9. print(s[0]) # H

  10. s[0] = ‘h’ # TypeError: …

Explanation:

A string is immutable. You can not change it.

You can read something by indexing,

BUT you can not write something by indexing.

Q219 (Please refer to this number, if you want to write me about this question.)

Domain

06 – Functions

Question 19Skipped

Q244 – Data Aggregates

What is the expected output of the following code?

  1. data = {‘1’: ‘0’, ‘0’: ‘1’}

  2. for d in data.vals():

  3. print(d, end=' ')
    

Correct answer

The code is erroneous.

Explanation

The code contains a typo in the loop statement. The correct method to access the values of a dictionary in Python is data.values(), not data.vals(). Therefore, the code will result in an error due to the incorrect method call.

1 0

Explanation

This choice is incorrect because the code will not execute successfully. The loop statement contains a typo in the method call to access dictionary values, resulting in an error. Therefore, the output "1 0" will not be produced.

0 0

Explanation

This choice is incorrect because the code will not execute successfully. The loop statement contains a typo in the method call to access dictionary values, resulting in an error. Therefore, the output "0 0" will not be produced.

0 1

Explanation

This choice is incorrect because the code will not execute successfully. The loop statement contains a typo in the method call to access dictionary values, resulting in an error. Therefore, the output "0 1" will not be produced.

Overall explanation

Topics: dictionary values() for

Try it yourself:

  1. data = {‘1’: ‘0’, ‘0’: ‘1’}

  2. for d in data.values():

  3. for d in data.vals(): # AttributeError: …

  4. print(d, end=' ')    # 0 1
    

Explanation:

This question is a little tricky.

Everything seems to be fine,

BUT the right name of the dictionary method is values()

Q244 (Please refer to this number, if you want to write me about this question.)

Domain

04 – Data Aggregates

Question 20Skipped

Q202 – Data Types

What is the expected output of the following code?

  1. data = ‘abbabadaadbbaccabc’
  2. print(data.count(‘ab’, 1))

4

Explanation

The expected output of the code is not 4. The count() method is used to count the occurrences of a specified value in a string. In this case, it is counting the occurrences of the substring ‘ab’ starting from index 1. There are only 2 occurrences of ‘ab’ in the specified range, not 4.

Correct answer

2

Explanation

The count() method in Python returns the number of occurrences of a specified value in a string. In this case, the code is counting the occurrences of the substring ‘ab’ in the string ‘abbabadaadbbaccabc’ starting from index 1. The expected output is 2, as there are two occurrences of ‘ab’ starting from index 1.

5

Explanation

The expected output of the code is not 5. The count() method in Python returns the number of occurrences of a specified value in a string. In this case, it is counting the occurrences of the substring ‘ab’ starting from index 1. There are only 2 occurrences of ‘ab’ in the specified range, not 5.

3

Explanation

The expected output of the code is not 3. The count() method counts the occurrences of a specified value in a string, and in this case, it is counting the occurrences of the substring ‘ab’ starting from index 1. There are only 2 occurrences of ‘ab’ in the specified range, not 3.

Overall explanation

Topics: string count()

Try it yourself:

  1. data = ‘abbabadaadbbaccabc’
  2. print(data.count(‘ab’, 1)) # 2
  3. print(data.count(‘ab’, 0)) # 3

Explanation:

Remember to bring your best reading glasses to the exam.

The second parameter will determine where the count() method

will start its counting.

The first parameter (in this case ab) is what count() will look for.

count() will start at index 1

and therefore it will not find the ab right at the beginning of the string.

That leaves two more ab to find.

Q202 (Please refer to this number, if you want to write me about this question.)

Domain

02 – Data Types

Question 21Skipped

Q224 – Basics

What is the expected output of the following code?

  1. x = """
  2. """
  3. print(len(x))

The code is erroneous.

Explanation

The code is not erroneous; it defines a string x with an empty string containing a single newline character. The length of the string is 1, not 0.

2

Explanation

The code defines a string x with three double quotes, but the only character in the string is the newline character. Therefore, the length of the string is 1, not 2.

0

Explanation

Although the code may seem to define an empty string due to the presence of three double quotes, the newline character between the quotes counts as a single character. Therefore, the length of the string is 1, not 0.

Correct answer

1

Explanation

The code defines a string x with three double quotes, which represents an empty string. The length of an empty string is 1, as it contains a single character (the newline character).

Overall explanation

Topics: multiline string len()

Try it yourself:

  1. x = """

  2. """

  3. print(len(x)) # 1

  4. ord() returns an integer representing the Unicode character.

  5. print(ord(x[0])) # 10 (LF: line feed, new line)

  6. Same result with single quotes:

  7. y = ”’

  8. ”’

  9. print(len(y)) # 1

  10. Every line feed is a character:

  11. z = """

  12. """

  13. print(len(z)) # 2

Explanation:

In a multiline string the line feed gets saved like any other character.

Q224 (Please refer to this number, if you want to write me about this question.)

Domain

01 – Basics

Question 22Skipped

Q241 – Functions

Which of the following function headers is correct?

def func(a=1, b=1, c=2, d):

Explanation

This function header is incorrect because when specifying default parameter values, all parameters to the right of a parameter with a default value must also have default values. In this case, parameter ‘d’ does not have a default value, making the function header invalid.

Correct answer

def func(a=1, b=1, c=2):

Explanation

This function header is correct because it defines a function named ‘func’ with three parameters ‘a’, ‘b’, and ‘c’. The default values for ‘a’ and ‘b’ are specified as 1 and 1, respectively, while ‘c’ does not have a default value.

def func(a=1, b, c=2):

Explanation

This function header is incorrect because when specifying default parameter values, all parameters to the right of a parameter with a default value must also have default values. In this case, parameter ‘b’ does not have a default value, making the function header invalid.

def func(a=1, b):

Explanation

This function header is incorrect because when specifying default parameter values, all parameters to the right of a parameter with a default value must also have default values. In this case, parameter ‘b’ does not have a default value, making the function header invalid.

Overall explanation

Topics: def default arguments

Try it yourself:

  1. def func(a=1, b=1, c=2): pass

  2. def func(a=1, b): pass # SyntaxError: …

  3. def func(a=1, b, c=2): pass # SyntaxError: …

  4. def func(a=1, b=1, c=2, d): pass # SyntaxError: …

  5. This would also work:

  6. def func(a, b=1, c=2): pass

  7. """

  8. def func(a=1, b): pass

  9. func(7)

  10. The 7 would go into a and there is nothing left for b.

  11. """

Explanation:

The default argument(s) have to be at the end.

Q241 (Please refer to this number, if you want to write me about this question.)

Domain

06 – Functions

Question 23Skipped

Q205 – Operators

Which of the following statements is false?

Correct answer

The result of the / operator is always an integer value.

Explanation

The result of the / operator in Python is not always an integer value. It depends on the operands. If both operands are integers, the result will be a truncated integer value. However, if at least one of the operands is a float, the result will be a float value.

The ** operator has right-to-left associativity.

Explanation

The ** operator in Python has left-to-right associativity, not right-to-left. This means that when there are multiple ** operators in an expression, they are evaluated from left to right.

The right argument of the % operator can not be zero.

Explanation

In Python, the right argument of the % operator can be zero. However, if the right operand is zero, a ZeroDivisionError will be raised because division by zero is not allowed in Python.

Multiplication precedes addition.

Explanation

In Python, multiplication has a higher precedence than addition. This means that when both operations are present in an expression, multiplication will be performed first before addition.

Overall explanation

Topic: division operator integer float

Try it yourself:

  1. "The result of the / operator is always an integer value."

  2. is false:

  3. print(9 / 3) # 3.0

  4. The result of the division operator is always a float value!

  5. "Multiplication precedes addition." is true:

  6. print(3 + 4 * 5) # 23

  7. print(3 + (4 * 5)) # 23

  8. print(3 + 20) # 23

  9. print(23) # 23

  10. "The ** operator has right-to-left associativity." is true:

  11. print(2 ** 3 ** 2) # 512

  12. print(2 ** (3 ** 2)) # 512

  13. print(2 ** 9) # 512

  14. print(512) # 512

  15. "The right argument of the % operator cannot be zero."

  16. is true:

  17. print(7 % 0) # ZeroDivisionError: …

Explanation:

As written above,

the result of the division operator is always a float value.

Even if it operates with two integer values.

Q205 (Please refer to this number, if you want to write me about this question.)

Domain

03 – Operators

Question 24Skipped

Q207 – Operators

Consider the following code.

  1. x = 1
  2. x = x == x

The value eventually assigned to x is equal to:

1

Explanation

The code snippet assigns the result of the comparison operation (x == x) to the variable x. Since x is initially assigned the value 1, the comparison x == x will evaluate to True, which is not equal to 1. Therefore, the value eventually assigned to x is not 1.

Correct answer

True

Explanation

The code snippet assigns the result of the comparison operation (x == x) to the variable x. Since x is initially assigned the value 1, the comparison x == x will evaluate to True, and this result will be assigned back to x. Therefore, the value eventually assigned to x is True.

0

Explanation

The code snippet assigns the result of the comparison operation (x == x) to the variable x. Since x is initially assigned the value 1, the comparison x == x will not result in 0. Therefore, the value eventually assigned to x is not 0.

False

Explanation

The code snippet assigns the result of the comparison operation (x == x) to the variable x. Since x is initially assigned the value 1, the comparison x == x will always evaluate to True. Therefore, the value eventually assigned to x is not False.

Overall explanation

Topic: equal to operator

Try it yourself:

  1. x = 1
  2. x = x == x
  3. print(x) # True
  4. x = 1
  5. x = x == x
  6. x = (1 == 1)
  7. x = True

Explanation:

x has the value 1

x gets compared with the equal to operator with itself.

It is true, that x is equal to x

True gets stored in the same variable, in x

Q207 (Please refer to this number, if you want to write me about this question.)

Domain

03 – Operators

Question 25Skipped

Q243 – Basics

Which of the following variable names is illegal?

tRUE

Explanation

The variable name "tRUE" is a valid variable name in Python as it does not conflict with any reserved keywords. Python is case-sensitive, so "tRUE" is different from "True".

Correct answer

True

Explanation

The variable name "True" is illegal because Python is case-sensitive, and the keyword "True" is a reserved keyword in Python used to represent the boolean value True. Using reserved keywords as variable names is not allowed in Python.

true

Explanation

The variable name "true" is a valid variable name in Python as it does not conflict with any reserved keywords. Python is case-sensitive, so "true" is different from "True".

TRUE

Explanation

The variable name "TRUE" is illegal because it is the same as the reserved keyword "True" in Python. Using reserved keywords as variable names is not allowed in Python.

Overall explanation

Topic: naming variables

Try it yourself:

  1. True = 3 # SyntaxError: cannot assign to True

  2. Those three work, because Python is case sensitive:

  3. true = 7
  4. tRUE = 23
  5. TRUE = 42
  6. print(true, tRUE, TRUE) # 7 23 42

Explanation:

You can not name a variable like a Python keyword.

Q243 (Please refer to this number, if you want to write me about this question.)

Domain

01 – Basics

Question 26Skipped

Q236- Modules

You know that a function named func() resides in a module named mod

The module has been imported using the following line:

import mod

How can you invoke the function?

func()

Explanation

Simply calling ‘func()’ without specifying the module name will result in a NameError because the interpreter will not be able to find the function in the current namespace. You need to use the module name followed by a dot to access the function.

Correct answer

mod.func()

Explanation

To invoke a function that resides in a module that has been imported using the ‘import’ statement, you need to use the module name followed by a dot and then the function name. In this case, ‘mod.func()’ is the correct way to invoke the function ‘func()’ from the ‘mod’ module.

mod::func()

Explanation

Using the ‘::’ operator to invoke a function from a module is not valid syntax in Python. The correct way to access a function from an imported module is by using the module name followed by a dot and then the function name.

mod‑>func()

Explanation

The ‘->’ operator is not used to invoke functions from modules in Python. To access and invoke a function from an imported module, you need to use the module name followed by a dot and then the function name, as in ‘mod.func()’.

Overall explanation

Topic: import

Try it yourself:

  1. First execute the following to create the needed file:

  2. text = ”’

  3. def func():

  4. print("I am a function, goo goo g'joob!")
    
  5. ”’

  6. with open(‘mod.py’, ‘w’) as f:

  7. f.write(text)
    
  8. import mod

  9. mod.func() # I am a function, goo goo g’joob!

Explanation:

If you import the whole module

you have to add the entity by dot notation.

Q236 (Please refer to this number, if you want to write me about this question.)

Domain

09 – Modules

Question 27Skipped

Q201 – Operators

What is the expected output of the following code?

print(1 / 1)

This can not be evaluated.

Explanation

The division operation of two integers in Python will always return a float value, even if the result is a whole number. Therefore, the code print(1 / 1) can be evaluated and the expected output is 1.0.

This can not be predicted.

Explanation

In Python, the division operator (/) always returns a float value, so the code print(1 / 1) can be predicted to output 1.0. The output is deterministic and can be evaluated.

Correct answer

1.0

Explanation

The division operator (/) in Python always returns a float value, even if both operands are integers. Therefore, the expected output of the code print(1 / 1) is 1.0 as it performs floating-point division.

1

Explanation

While the division of two integers in Python would normally result in a float value, it is important to note that the output of the code print(1 / 1) will specifically be 1.0 due to the behavior of the division operator in Python.

Overall explanation

Topic: division operator

Try it yourself:

print(1 / 1)  # 1.0

Explanation:

All you have to know here is,

that the division operator always returns a float.

Even if it is operating with two integers.

Q201 (Please refer to this number, if you want to write me about this question.)

Domain

03 – Operators

Question 28Skipped

Q256 – I/O

What is the expected result of the following code?

  1. b = bytearray(3)
  2. print(b)

bytearray(b'3')

Explanation

This choice is incorrect because the code does not create a bytearray with the value ‘3’, but it creates a bytearray with three null bytes.

3

Explanation

This choice is incorrect because the code does not print the length of the bytearray but the actual content of the bytearray, which is three null bytes.

bytearray(0, 0, 0)

Explanation

This choice is incorrect because the syntax used to create a bytearray with specific values is not correct. The correct way to initialize a bytearray with specific values is by passing them as a sequence, not as separate arguments.

Correct answer

bytearray(b'\x00\x00\x00')

Explanation

The code creates a bytearray object with a length of 3, initialized with null bytes. Therefore, the expected result is a bytearray containing three null bytes represented as b’\x00\x00\x00′.

Overall explanation

Topic: bytearray()

Try it yourself:

  1. b = bytearray(3)

  2. print(b) # bytearray(b’\x00\x00\x00′)

  3. The bytearray works better with sequences of integers:

  4. print(bytearray([3])) # bytearray(b’\x03′)

  5. print(bytearray([65, 66, 67])) # bytearray(b’ABC’)

Explanation:

Read more about it here:

https://www.programiz.com/python-programming/methods/built-in/bytearray

Q256 (Please refer to this number, if you want to write me about this question.)

Domain

07 – I/O

Question 29Skipped

Q251 – Modules

If you want to import pi from math, which line will you use?

from pi import math

Explanation

The syntax ‘from pi import math’ is incorrect for importing the ‘pi’ constant from the ‘math’ module. This line suggests importing ‘math’ from ‘pi’, which is not the correct way to access constants or functions from a module in Python.

import pi from math

Explanation

The syntax ‘import pi from math’ is also incorrect for importing the ‘pi’ constant from the ‘math’ module. In Python, the correct order for importing is ‘from module import item’, where ‘module’ is the module name and ‘item’ is the specific constant or function to be imported.

Correct answer

from math import pi

Explanation

The correct way to import the ‘pi’ constant from the ‘math’ module in Python is to use the syntax ‘from math import pi’. This line specifically tells Python to import the ‘pi’ constant directly into the current namespace from the ‘math’ module.

Overall explanation

Topics: import math pi

Try it yourself:

  1. from math import pi
  2. print(pi) # 3.141592653589793

Explanation:

The order is from big to small.

First the module than the variable:

From the math module import the variable pi.

Q251 (Please refer to this number, if you want to write me about this question.)

Domain

09 – Modules

Question 30Skipped

Q221 – Data Aggregates

What is the expected output of the following code?

  1. data = set([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
  2. print(len(data))

10

Explanation

The output is not 10 because the set ‘data’ contains only 4 unique elements [1, 2, 3, 4]. The len() function returns the number of elements in the set, which is 4, not 10.

3

Explanation

The output is not 3 because the set ‘data’ contains more than three unique elements. The set ‘data’ contains elements [1, 2, 3, 4], and the len() function returns the number of elements in the set, which is 4.

Correct answer

4

Explanation

The code creates a set with unique elements from the list [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]. Since sets only store unique elements, the duplicates are removed, resulting in a set with elements {1, 2, 3, 4}. The len() function then returns the number of elements in the set, which is 4.

0

Explanation

The code does not result in an empty set, so the output is not 0. The set ‘data’ contains elements [1, 2, 3, 4], and the len() function returns the number of elements in the set, which is 4.

1

Explanation

The output is not 1 because the set ‘data’ contains more than one unique element. The set ‘data’ contains elements [1, 2, 3, 4], and the len() function returns the number of elements in the set, which is 4.

2

Explanation

The output is not 2 because the set ‘data’ contains more than two unique elements. The set ‘data’ contains elements [1, 2, 3, 4], and the len() function returns the number of elements in the set, which is 4.

Overall explanation

Topics: list set() len()

Try it yourself:

  1. data = set([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])

  2. print(len(data)) # 4

  3. print(type(data)) # <class ‘set’>

  4. print(data) # {1, 2, 3, 4}

  5. Also works directly:

  6. print(len({1, 2, 2, 3, 3, 3, 4, 4, 4, 4})) # 4

Explanation:

A set can not have duplicates.

Q221 (Please refer to this number, if you want to write me about this question.)

Domain

04 – Data Aggregates

Question 31Skipped

Q246 – Operators

What is the expected output of the following code?

  1. x = 9
  2. y = 12
  3. result = x // 2 * 2 / 2 + y % 2 ** 3
  4. print(result)

Correct answer

8.0

Explanation

The code first performs integer division (//) of x by 2, resulting in 4. Then, it multiplies the result by 2, which gives 8. Next, it divides the result by 2, resulting in 4.0. Finally, it adds the remainder of y divided by 2 to the power of 3, which is 0. Therefore, the final result is 8.0.

9.0

Explanation

This choice is incorrect because it does not accurately represent the calculations performed in the given code. The correct calculation results in the final output of 8.0, not 9.0.

8

Explanation

This choice is incorrect because it does not accurately represent the calculations performed in the given code. The correct calculation results in the final output of 8.0, not 8.

7.0

Explanation

This choice is incorrect because it does not accurately represent the calculations performed in the given code. The correct calculation results in the final output of 8.0, not 7.0.

Overall explanation

Topics: arithmetic operators operator precedence

Try it yourself:

  1. x = 9

  2. y = 12

  3. result = x // 2 * 2 / 2 + y % 2 ** 3

  4. print(result) # 8.0

  5. print(x // 2 * 2 / 2 + y % 2 ** 3) # 8.0

  6. print(9 // 2 * 2 / 2 + 12 % 2 ** 3) # 8.0

  7. print(9 // 2 * 2 / 2 + 12 % (2 ** 3)) # 8.0

  8. print(9 // 2 * 2 / 2 + 12 % 8) # 8.0

  9. print((9 // 2) * 2 / 2 + 12 % 8) # 8.0

  10. print(4 * 2 / 2 + 12 % 8) # 8.0

  11. print((4 * 2) / 2 + 12 % 8) # 8.0

  12. print(8 / 2 + 12 % 8) # 8.0

  13. print((8 / 2) + 12 % 8) # 8.0

  14. print(4.0 + 12 % 8) # 8.0

  15. print(4.0 + (12 % 8)) # 8.0

  16. print(4.0 + 4) # 8.0

  17. print(8.0) # 8.0

Explanation:

The operators here are from three different groups:

"Exponent" has the highest precedence.

Followed by "Multiplication, Division, Floor division, Modulus".

"Addition, Subtraction" has the lowest precedence.

Therefore the order of operations here is: ** -> // -> * -> / -> % -> +

Q246 (Please refer to this number, if you want to write me about this question.)

Domain

03 – Operators

Question 32Skipped

Q231 – Error Handling

What is the expected output of the following code?

  1. try:

  2. print('try')
    
  3. except:

  4. print('except')
    
  5. finally:

  6. print('finally')
    
  7. except

  8. finally

Explanation

The try block is executed first, so ‘try’ should be printed. If an exception is caught, the except block would be executed, but since there is no specific exception specified, it will not be triggered in this case. The finally block is always executed, so ‘finally’ is printed at the end.

  1. finally
  2. except

Explanation

The finally block is always executed, so ‘finally’ should be printed first. Since there is no exception caught in the try block, the except block is not executed, so ‘except’ is not printed.

  1. finally
  2. try

Explanation

The try block is executed first, so ‘try’ is printed. The finally block is always executed, so ‘finally’ is printed at the end.

Correct answer

  1. try
  2. finally

Explanation

The try block is executed first, so ‘try’ is printed. Then, regardless of whether an exception is caught or not, the finally block is always executed. Therefore, ‘finally’ is printed at the end.

The code is erroneous.

Explanation

The code is not erroneous and will run without any errors. The output will be a combination of ‘try’ and ‘finally’.

Overall explanation

Topic: try except finally

Try it yourself:

  1. try:
  2. print('try')      # try
    
  3. except:
  4. print('except')
    
  5. finally:
  6. print('finally')  # finally
    

Explanation:

The snippet will try to execute print('try') and succeed.

The finally block always gets execute.

Q231 (Please refer to this number, if you want to write me about this question.)

Domain

08 – Error Handling

Question 33Skipped

Q215 – Functions

What is the expected output of the following code?

  1. people = {}

  2. def add_person(index):

  3. if index in people:
    
  4.     people[index] += 1
    
  5. else:
    
  6.     people[index] = 1
    
  7. add_person(‘Peter’)

  8. add_person(‘Paul’)

  9. add_person(‘peter’)

  10. print(len(people))

Correct answer

3

Explanation

The code defines a dictionary called ‘people’ and a function ‘add_person’ that takes an index as a parameter. The function checks if the index is already in the ‘people’ dictionary. If it is, it increments the value associated with that index by 1. If not, it adds the index to the dictionary with a value of 1. In this case, ‘Peter’, ‘Paul’, and ‘peter’ are added as keys to the dictionary, resulting in a total of 3 unique keys when ‘len(people)’ is printed.

2

Explanation

The code correctly handles case sensitivity when adding keys to the ‘people’ dictionary. As ‘Peter’ and ‘peter’ are considered as different keys, the final count of unique keys in the dictionary is 3 when ‘len(people)’ is printed.

1

Explanation

The code correctly increments the count for each unique index added to the ‘people’ dictionary. Since ‘Peter’, ‘Paul’, and ‘peter’ are considered as different keys due to case sensitivity, the final count of unique keys in the dictionary is 3, resulting in the output of 3 when ‘len(people)’ is printed.

The code is erroneous.

Explanation

The code is not erroneous. It correctly adds keys to the ‘people’ dictionary and increments the count for each unique key. The output of the code is 3, which represents the total number of unique keys in the dictionary.

Overall explanation

Topics: def shadowing dictionary

Try it yourself:

  1. people = {}

  2. def add_person(index):

  3. if index in people:
    
  4.     people[index] += 1
    
  5. else:
    
  6.     people[index] = 1
    
  7. add_person(‘Peter’)

  8. add_person(‘Paul’)

  9. add_person(‘peter’)

  10. print(len(people)) # 3

  11. print(people) # {‘Peter’: 1, ‘Paul’: 1, ‘peter’: 1}

Explanation:

Peter is a different index than peter

because P is a different character than p

and therefore the dictionary will have three entries.

Q215 (Please refer to this number, if you want to write me about this question.)

Domain

06 – Functions

Question 34Skipped

Q245 – Data Aggregates

What is the expected output of the following code?

  1. data = [1, 2, 3, 4, 5, 6]

  2. for i in range(1, 6):

  3. data[i - 1] = data[i]
    
  4. for i in range(0, 6):

  5. print(data[i], end=' ')
    

2 3 4 5 6 1

Explanation

This choice is incorrect because the code snippet shifts each element to the left by one position, resulting in 2 3 4 5 6 6 as the output, not 2 3 4 5 6 1.

1 2 3 4 5 6

Explanation

This choice is incorrect because the code snippet shifts each element to the left by one position, resulting in 2 3 4 5 6 6 as the output, not 1 2 3 4 5 6.

Correct answer

2 3 4 5 6 6

Explanation

The code snippet iterates over the list ‘data’ and shifts each element to the left by one position. As a result, the output will be 2 3 4 5 6 6, where the last element is repeated.

1 1 2 3 4 5

Explanation

This choice is incorrect because the code snippet shifts each element to the left by one position, resulting in 2 3 4 5 6 6 as the output, not 1 1 2 3 4 5.

Overall explanation

Topics: for range() print() with end parameter  list indexing

Try it yourself:

  1. data = [1, 2, 3, 4, 5, 6]

  2. for i in range(1, 6): # 1 -> 2 -> 3 -> 4 -> 5

  3. data[i - 1] = data[i]
    
  4. print(data) # [2, 3, 4, 5, 6, 6]

  5. This is just for output:

  6. for i in range(0, 6):

  7. print(data[i], end=' ')  # 2 3 4 5 6 6 
    

Explanation:

In the first for loop, the five last values of data

get written to the first five indexes of data

The value of the last index stays the same.

range(1, 6) will produce the numbers 1, 2, 3, 4, 5

And because the first of these number is 1 we need the data[i -1] to start at index 0

The old value at index 1 is 2

That gets written at index 0

And so forth …

Q245 (Please refer to this number, if you want to write me about this question.)

Domain

04 – Data Aggregates

Question 35Skipped

Q206 – Operators

What is the expected output of the following code?

print(1 // 2 * 3)

Correct answer

0

Explanation

The code snippet performs integer division (//) first, which results in 0, and then multiplies the result by 3. Therefore, the expected output is 0.

0.0

Explanation

The code snippet does not involve floating-point division, so the result will be an integer value. Therefore, the output will not be 0.0.

4.5

Explanation

The code snippet performs integer division (//) first, which results in 0, and then multiplies the result by 3. Therefore, the expected output is not 4.5.

0.16666666666666666

Explanation

The code snippet does not involve floating-point division, so the result will be an integer value. Therefore, the output will not be a decimal value like 0.16666666666666666.

Overall explanation

Topics: arithmetic operators operator precedence

Try it yourself:

  1. print(1 // 2 * 3) # 0

  2. print((1 // 2) * 3) # 0

  3. print(0 * 3) # 0

  4. print(0) # 0

Explanation:

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.

Therefore the order of operations here is: // -> *

Q206 (Please refer to this number, if you want to write me about this question.)

Domain

03 – Operators

Question 36Skipped

Q216 – Control Flow

How many stars will the following code print to the monitor?

  1. x = 1
  2. while x < 10:
  3. print('*')
    
  4. x = x << 1
    

eight

Explanation

The code prints a star on each iteration of the while loop. The value of x is left-shifted by 1 on each iteration, effectively doubling its value. The loop will run until x is no longer less than 10, which will happen after 4 iterations. Therefore, the code will print four stars to the monitor, not eight.

Correct answer

four

Explanation

The code starts with x=1 and prints a star on each iteration of the while loop. The value of x is left-shifted by 1 on each iteration, effectively doubling its value. The loop will run until x is no longer less than 10, which will happen after 4 iterations. Therefore, the code will print four stars to the monitor.

two

Explanation

The code prints a star on each iteration of the while loop. The value of x is left-shifted by 1 on each iteration, effectively doubling its value. The loop will run until x is no longer less than 10, which will happen after 4 iterations. Therefore, the code will print four stars to the monitor, not just two.

one

Explanation

The code prints a star on each iteration of the while loop. However, since the value of x is left-shifted by 1 on each iteration, it effectively doubles its value. The loop will run until x is no longer less than 10, which will happen after 4 iterations. Therefore, the code will print four stars to the monitor, not just one.

Overall explanation

Topics: while bit operator

Try it yourself:

  1. x = 1

  2. while x < 10:

  3. print('*')
    
  4. x = x << 1
    
  5. print('x:', x)            # 2 -> 4 -> 8 -> 16
    
  6. print('bin(x):', bin(x))  # 0b10->0b100->0b1000->0b10000
    
  7. """

  8. 1 -> 00001 << 1 -> 00010 (2)

  9. 2 -> 00010 << 1 -> 00100 (4)

  10. 4 -> 00100 << 1 -> 01000 (8)

  11. 8 -> 01000 << 1 -> 10000 (16)

  12. """

Explanation:

Left shift by one, a classic way to double values.

Every value goes to the bit on its left and thereby doubles in value.

And 1248 are all smaller than 10 but not the 16

and therefore four stars will be printed.

Q216 (Please refer to this number, if you want to write me about this question.)

Domain

05 – Control Flow

Question 37Skipped

Q253 – Basics

A code point is:

A code containing a point.

Explanation

This choice is incorrect because a code point is not a code containing a point. Instead, it is a numerical value that corresponds to a specific character in the Unicode character set, enabling the representation of characters in a programming language like Python.

A point used to write a code.

Explanation

This choice is incorrect because a code point is not a point used to write a code. Instead, it is a numerical value that represents a character in the Unicode character set, allowing for the manipulation and display of text in programming languages like Python.

Correct answer

A number which makes up a character.

Explanation

A code point in Python is a numerical value that represents a specific character in the Unicode character set. It is essentially a number assigned to a character, allowing for the representation and manipulation of text in a programming language like Python.

Overall explanation

Topic: code points

Try it yourself:

print(ord('A')) # 65

Explanation:

For example in ASCII the number 65 makes up the character A

https://en.wikipedia.org/wiki/Code_point

Q253 (Please refer to this number, if you want to write me about this question.)

Domain

01 – Basics

Question 38Skipped

Q227 – Data Types

What is the expected output of the following code?

print('Peter' 'Wellert')

Correct answer

PeterWellert

Explanation

When two string literals are placed next to each other without any operator, they are automatically concatenated in Python. Therefore, the expected output of the code ‘print(‘Peter’ ‘Wellert’)’ is ‘PeterWellert’.

The code is erroneous.

Explanation

This choice is incorrect because the code is not erroneous. The code will successfully concatenate the two string literals ‘Peter’ and ‘Wellert’ and print the output ‘PeterWellert’.

Wellert

Explanation

This choice is incorrect because the code does not contain any spaces or operators between the two string literals ‘Peter’ and ‘Wellert’, so they will be concatenated into a single string ‘PeterWellert’, not separate strings.

Peter

Explanation

This choice is incorrect because the code does not contain any spaces or operators between the two string literals ‘Peter’ and ‘Wellert’, so they will be concatenated into a single string ‘PeterWellert’.

Overall explanation

Topic: string concatenation

Try it yourself:

  1. print(‘Peter’ ‘Wellert’) # PeterWellert

  2. x = ‘Hello’ ‘world’

  3. print(x) # Helloworld

Explanation:

String literals that are delimited by whitespace are automatically concatenated.

Q227 (Please refer to this number, if you want to write me about this question.)

Domain

02 – Data Types

Question 39Skipped

Q211 – Control Flow

Which of the following sentences correctly describes

the output of the below Python code?

  1. data = [4, 2, 3, 2, 1]

  2. res = data[0]

  3. for d in data:

  4. if d < res:
    
  5.     res = d
    
  6. print(res)

res is the average of all the number in the list.

Explanation

The code does not calculate the average of all numbers in the list. It simply finds the smallest number in the list, so ‘res’ cannot be the average of all numbers.

Correct answer

res is the smallest number in the list.

Explanation

The code initializes the variable ‘res’ with the first element of the ‘data’ list. Then, it iterates over each element in the list and updates ‘res’ if a smaller element is found. Therefore, ‘res’ will hold the smallest number in the list when the loop finishes.

None of the above.

Explanation

The code explicitly finds the smallest number in the list and stores it in the ‘res’ variable. Therefore, ‘res’ being the smallest number in the list makes it different from the other choices.

res is the sum of all the number in the list.

Explanation

The code does not perform any addition operation to calculate the sum of all numbers in the list. It only finds the smallest number in the list, so ‘res’ cannot be the sum of all numbers.

res is the largest number in the list.

Explanation

The code specifically looks for the smallest number in the list by comparing each element with the current value of ‘res’. Therefore, ‘res’ will hold the smallest number in the list, not the largest.

Overall explanation

Topics: for if list

Try it yourself:

  1. data = [4, 2, 3, 2, 1]
  2. res = data[0]
  3. for d in data:
  4. if d < res:
    
  5.     print('d in if:', d)  # 2 -> 1
    
  6.     res = d
    
  7. print(res) # 1

Explanation:

Classic way the find the smallest number.

Take the first element as possible result.

Compare the next number with the possible result.

If the next number is smaller,

it becomes the new possible result and so forth.

In the end the result is the smallest number.

Q211 (Please refer to this number, if you want to write me about this question.)

Domain

05 – Control Flow

Question 40Skipped

Q209 – Control Flow

How many stars will the following snippet print to the monitor?

  1. i = 0
  2. while i <= 5:
  3. i += 1
    
  4. if i % 2 == 0:
    
  5.     break
    
  6. print('*')
    

three

Explanation

The loop breaks as soon as i becomes even, which means the condition for printing a star is not met. Only one star will be printed to the monitor before the loop is terminated. Therefore, the correct choice is one star.

two

Explanation

The loop breaks when i becomes even, which means the condition for printing a star is not met. As a result, only one star will be printed before the loop is exited. Therefore, the correct choice is one star.

zero

Explanation

Since the condition for printing a star is based on the value of i being odd (i.e., not divisible by 2), and the loop breaks when i becomes even, no stars will be printed to the monitor. The loop terminates before any star can be printed.

Correct answer

one

Explanation

The code snippet initializes the variable i to 0 and enters a while loop that increments i by 1 in each iteration. Inside the loop, there is a conditional statement that checks if i is divisible by 2 without a remainder. If this condition is met, the loop is terminated using the break statement. Therefore, only one star will be printed to the monitor before the loop is exited.

Overall explanation

Topics: while break

Try it yourself:

  1. i = 0
  2. while i <= 5:
  3. print('1. i: ', i)  # 0 -> 1
    
  4. i += 1
    
  5. print('2. i: ', i)  # 1 -> 2
    
  6. if i % 2 == 0:  # False, True
    
  7.     break
    
  8. print('*')  # *
    

Explanation:

i % 2 == 0 is known as test for even numbers.

In the first iteration i is an odd 1

and therefore the break does not get triggered

and a star gets printed.

In the second iteration i is an even 2

the break gets triggered and there is no more stars.

Q209 (Please refer to this number, if you want to write me about this question.)

Domain

05 – Control Flow

Question 41Skipped

Q213 – Functions

What is the expected output of the following code?

  1. def func(message, num=1):

  2. print(message * num)
    
  3. func(‘Hello’)

  4. func(‘Welcome’, 3)

  5. Hello

Explanation

This choice is incorrect because it only includes the output of the first function call ‘func(‘Hello’)’, which prints ‘Hello’ once. It does not consider the output of the second function call ‘func(‘Welcome’, 3)’, which prints ‘Welcome’ three times.

  1. Hello
  2. Welcome Welcome Welcome

Explanation

This choice is incorrect because it includes the output of the first function call ‘func(‘Hello’)’, which prints ‘Hello’ once. It then incorrectly formats the output of the second function call ‘func(‘Welcome’, 3)’ as ‘Welcome Welcome Welcome’ with spaces, whereas the actual output does not include spaces between the repeated ‘Welcome’ strings.

  1. Hello
  2. Welcome,Welcome,Welcome

Explanation

This choice is incorrect because it includes the output of the first function call ‘func(‘Hello’)’, which prints ‘Hello’ once. It then incorrectly adds ‘Welcome,Welcome,Welcome’ to the output, which does not match the actual output of the second function call ‘func(‘Welcome’, 3)’.

Correct answer

  1. Hello
  2. WelcomeWelcomeWelcome

Explanation

The expected output of the code is ‘Hello’ printed once followed by ‘Welcome’ printed three times, resulting in ‘WelcomeWelcomeWelcome’. This is because the function ‘func’ is called with different arguments, where the default value of ‘num’ is 1 for the first call and explicitly set to 3 for the second call.

  1. Hello
  2. Viewers

Explanation

This choice is incorrect because it includes the output of the first function call ‘func(‘Hello’)’, which prints ‘Hello’ once. However, it incorrectly adds ‘Viewers’ to the output, which is not part of the code provided.

Overall explanation

Topics: def default parameter multiply operator string concatenation

Try it yourself:

  1. def func(message, num=1):

  2. print(message * num)
    
  3. func(‘Hello’) # Hello

  4. func(‘Welcome’, 3) # WelcomeWelcomeWelcome

Explanation:

In the function a string concatenation by multiplication takes place.

Once with the default value of num (1)

and once with the one passed by argument (3)

Q213 (Please refer to this number, if you want to write me about this question.)

Domain

06 – Functions

Question 42Skipped

Q254 – Operators

The += operator, when applied to strings, performs:

Correct answer

Concatenation

Explanation

The += operator, when applied to strings, concatenates the string on the left-hand side with the string on the right-hand side. This means that the strings are combined to create a new string that contains the contents of both original strings.

Subtraction

Explanation

The += operator does not perform subtraction when applied to strings. Subtraction is not a valid operation for strings in Python, as strings are immutable and cannot be subtracted from each other.

Multiplication

Explanation

The += operator does not perform multiplication when applied to strings. Multiplication with strings in Python is done using the * operator, where a string can be multiplied by an integer to repeat the string multiple times.

Overall explanation

Topic: add and assign operator

Try it yourself:

  1. text = ‘Hello’
  2. text += ‘ ‘
  3. text += ‘World’
  4. print(text) # Hello World
  5. print(‘Hello’ + ‘ ‘ + ‘World’) # Hello World

Explanation:

The add and assign operator when applied to strings,

performs a string concatenation.

Just like the addition operator

Q254 (Please refer to this number, if you want to write me about this question.)

Domain

03 – Operators

Question 43Skipped

Q210 – Control Flow

How many stars will the following code print to the monitor?

  1. i = 0
  2. while i < i + 2:
  3. i += 1
    
  4. print('*')
    
  5. else:
  6. print('*')
    

two

Explanation

This choice is incorrect because the code will not terminate and will instead enter an infinite loop. Therefore, it will not print two stars.

Correct answer

The snippet will enter an infinite loop.

Explanation

The condition i < i + 2 will always be true since i is initially 0. This will cause the while loop to continue indefinitely, incrementing i by 1 each iteration. As a result, the code will enter an infinite loop and keep printing ‘*’ to the monitor.

one

Explanation

This choice is incorrect because the code will not terminate and will instead enter an infinite loop. Therefore, it will not print one star.

zero

Explanation

This choice is incorrect because the code will not terminate and will instead enter an infinite loop. Therefore, it will not print zero stars.

Overall explanation

Topics: while else (nobreak)

Try it yourself:

  1. i = 0
  2. while i < i + 2:
  3. i += 1
    
  4. print('*')
    
  5. if i == 1000: break  # Safeguard
    
  6. else:
  7. print('*')
    

Explanation:

i gets incremented inside the while loop,

BUT i will always be smaller than i + 2

Therefore the while condition will always be True

and we build ourselves a nice infinite loop.

Q210 (Please refer to this number, if you want to write me about this question.)

Domain

05 – Control Flow

Question 44Skipped

Q222 – Basics

UTF‑8 is …

Correct answer

an encoding form of the Unicode Standard.

Explanation

UTF-8 is an encoding form of the Unicode Standard, which is used to represent text in various languages and characters. It is a variable-width encoding that can represent every character in the Unicode character set.

the 9th version of the UTF Standard.

Explanation

UTF-8 is not the 9th version of the UTF Standard. It is a specific encoding form within the Unicode Standard that allows for efficient representation of characters using variable-length byte sequences.

a synonym for "byte".

Explanation

UTF-8 is not a synonym for "byte." It is a specific encoding scheme that allows for efficient representation of Unicode characters using variable-length byte sequences.

a Python version name.

Explanation

UTF-8 is not a Python version name. It is a character encoding standard that is widely used in various programming languages and systems to represent text data.

Overall explanation

Topic: UTF-8

Explanation:

UTF-8 is one of three encoding forms of the Unicode Standard.

The others are UTF-16 and UTF-32.

UTF-8 is the most popular one, because it is most flexibel.

UTF-8 requires 8, 16, 24 or 32 bits (one to four bytes)

to encode a Unicode character,

UTF-16 requires either 16 or 32 bits to encode a character,

and UTF-32 always requires 32 bits to encode a character.

Q222 (Please refer to this number, if you want to write me about this question.)

Domain

01 – Basics

Question 45Skipped

Q214 – Functions

Which of the following function calls can be used to invoke

the below function definition?

def test(a, b, c, d):

Choose three.

test(a=1, 2, c=3, 4)

Explanation

This function call uses a mix of positional and keyword arguments but does not provide a value for the ‘b’ parameter, which does not match the function definition.

Correct selection

test(1, 2, 3, 4)

Explanation

This function call matches the function definition by providing values for all parameters in the correct order.

Correct selection

test(a=1, b=2, c=3, d=4)

Explanation

This function call uses keyword arguments to match the function definition, providing values for all parameters in any order.

test(a=1, b=2, c=3, 4)

Explanation

This function call uses keyword arguments but provides a value for the ‘d’ parameter without providing a value for the ‘b’ parameter, which does not match the function definition.

test(a=1, 2, 3, 4)

Explanation

This function call uses keyword arguments but does not provide a value for the ‘b’ parameter, which does not match the function definition.

Correct selection

test(1, 2, 3, d=4)

Explanation

This function call mixes positional and keyword arguments to match the function definition, providing values for all parameters in a valid combination.

Overall explanation

Topics: def positional/keyword arguments

Try it yourself:

  1. def test(a, b, c, d):

  2. print(a, b, c, d)
    
  3. test(1, 2, 3, 4) # 1 2 3 4

  4. test(a=1, b=2, c=3, d=4) # 1 2 3 4

  5. test(1, 2, 3, d=4) # 1 2 3 4

  6. test(a=1, 2, 3, 4). # SyntaxError: …

  7. test(a=1, b=2, c=3, 4) # SyntaxError: …

  8. test(a=1, 2, c=3, 4) # SyntaxError: …

  9. print(end=”, ‘Hello’) # SyntaxError: …

Explanation:

The keyword arguments always have to be at the end.

Q214 (Please refer to this number, if you want to write me about this question.)

Domain

06 – Functions

Question 46Skipped

Q218 – Control Flow

Consider the following code.

  1. for n in range(1, 6, 1):
  2. print(??? * 5)
    

What would you insert instead of ???

so that the program prints the following pattern to the monitor?

  1. 11111
  2. 22222
  3. 33333
  4. 44444
  5. 55555

n

Explanation

Inserting n directly will print the current value of n in each iteration of the loop, which is not what is needed to achieve the desired pattern. It will print a sequence of numbers from 1 to 5, rather than repeating each number 5 times.

-1

Explanation

Inserting -1 will not produce the desired pattern, as it will result in printing -1 five times in each iteration of the loop. This choice does not align with the goal of printing the pattern 11111, 22222, 33333, 44444, 55555.

1

Explanation

Inserting 1 will print the number 1 five times in each iteration of the loop, which is not the desired outcome. It will result in a pattern of 11111, rather than the pattern that repeats each number from 1 to 5 five times.

Correct answer

str(n)

Explanation

Using str(n) will convert the integer value of n to a string, allowing it to be repeated 5 times in the print statement. This will result in the desired pattern of numbers being printed to the monitor.

2

Explanation

Inserting 2 will print the number 2 five times in each iteration of the loop, which is not the desired outcome. It will result in a pattern of 22222, rather than the pattern that repeats each number from 1 to 5 five times.

Overall explanation

Topics: for range() str() multiply operator string concatenation

Try it yourself:

  1. for n in range(1, 6, 1):

  2. print(str(n) * 5)
    
  3. """

  4. 11111

  5. 22222

  6. 33333

  7. 44444

  8. 55555

  9. """

  10. print(‘———-‘)

  11. for n in range(1, 6, 1):

  12. print(n * 5)
    
  13. """

  14. 5

  15. 10

  16. 15

  17. 20

  18. 25

  19. """

  20. print(‘———-‘)

  21. for n in range(1, 6, 1):

  22. print(-1 * 5)
    
  23. """

  24. -5

  25. -5

  26. -5

  27. -5

  28. -5

  29. """

  30. print(‘———-‘)

  31. for n in range(1, 6, 1):

  32. print(1 * 5)
    
  33. """

  34. 5

  35. 5

  36. 5

  37. 5

  38. 5

  39. """

  40. print(‘———-‘)

  41. for n in range(1, 6, 1):

  42. print(2 * 5)
    
  43. """

  44. 10

  45. 10

  46. 10

  47. 10

  48. 10

  49. """

Explanation:

range(1, 6, 1) delivers the right numbers 1, 2, 3, 4, 5.

(It would also works without step 1, because that’s the default value.)

You need the str() function here to get more numbers.

Otherwise a calculation takes place

and you end up with one number per row.

By string concatenation you get the right result:

  1. ‘1’ * 5 -> ‘11111’
  2. ‘2’ * 5 -> ‘22222’
  3. ‘3’ * 5 -> ‘33333’
  4. ‘4’ * 5 -> ‘44444’
  5. ‘5’ * 5 -> ‘55555’

Q218 (Please refer to this number, if you want to write me about this question.)

Domain

05 – Control Flow

Question 47Skipped

Q229 – I/O

What is the expected output of the following code?

  1. with open(‘data.txt’, ‘w’) as f:

  2. f.write("I'm gonna make him an offer he can't refuse.")
    
  3. with open(‘data.txt’, ‘r’) as f:

  4. data = f.readlines()
    
  5. for line in data:
    
  6.     words = line.split()
    
  7.     print(words)
    

The code is erroneous.

Explanation

This choice is incorrect. The code is not erroneous; it successfully opens, reads, and processes the file ‘data.txt’. It splits the text into words and prints them as expected.

Correct answer

["I'm", 'gonna', 'make', 'him', 'an', 'offer', 'he', "can't", 'refuse.']

Explanation

The code opens a file named ‘data.txt’ in write mode and writes the specified text into it. Then, it opens the same file in read mode, reads the content line by line, splits each line into words using the split() method, and prints the words as a list. The expected output is a list of words from the written text.

I'm gonna make him an offer he can't refuse.

Explanation

This choice does not match the expected output of the code. The code splits the text into words and prints each word separately, not the entire text as a single string.

I

Explanation

This choice does not match the expected output of the code. The code splits the text into words and prints each word separately, not just the first word ‘I’.

Overall explanation

Topics: open() write() with readlines() for split()

Try it yourself:

  1. with open(‘data.txt’, ‘w’) as f:

  2. f.write("I'm gonna make him an offer he can't refuse.")
    
  3. with open(‘data.txt’, ‘r’) as f:

  4. data = f.readlines()
    
  5. print(data)  # ["I'm gonna make him an offer he can't refuse."]
    
  6. for line in data:
    
  7.     words = line.split()
    
  8.     print(words)
    

Explanation:

The method readlines() always returns a list.

In this case there is only one line in the file

and readlines() returns a list with one element.

Therefore the for loop only has one iteration.

The one element is a string.

The split() method with no argument passed

will split the string at its whitespaces and return a list of the parts.

At the end this list gets printed.

Actually the for loop is superfluous. The following would have sufficed:

print(data[0].split())

Q229 (Please refer to this number, if you want to write me about this question.)

Domain

07 – I/O

Question 48Skipped

Q232 – Error Handling

What is the expected output of the following code?

  1. try:
  2. raise Exception(1, 2, 3)
    
  3. except Exception as e:
  4. print(len(e.args))
    

Correct answer

3

Explanation

The code raises an Exception with three arguments (1, 2, 3). When the exception is caught and the length of the arguments is printed, the output will be 3, as there are three arguments in the exception.

1

Explanation

The code does not print the individual arguments of the exception, but rather the length of the arguments. Therefore, the output will not be 1, as it is not counting the number of individual arguments.

The code is erroneous.

Explanation

The code is not erroneous; it raises an Exception with three arguments and catches it properly. The length of the arguments is then printed, so the code will execute without errors.

2

Explanation

Similarly, the code does not print the individual arguments of the exception, but rather the length of the arguments. Therefore, the output will not be 2, as it is not counting the number of individual arguments.

Overall explanation

Topics: try except args len() Exception

Try it yourself:

  1. try:

  2. raise Exception(1, 2, 3)
    
  3. except Exception as e:

  4. print(len(e.args))   # 3
    
  5. print(type(e.args))  # <class 'tuple'>
    
  6. print(e.args)        # (1, 2, 3)
    
  7. try:

  8. x = 1 / 0
    
  9. except Exception as e:

  10. print(len(e.args))  # 1
    
  11. print(e.args)       # ('division by zero',)
    

Explanation:

If you raise an Exception you can pass a list of arguments.

They will be assign as a tuple to the args attribute of the Exception object.

Q232 (Please refer to this number, if you want to write me about this question.)

Domain

08 – Error Handling

Question 49Skipped

Q252 – Error Handling

The part of your code where the handling of an exception takes place should be placed inside:

Correct answer

the except: branch

Explanation

The correct place to handle an exception in Python code is inside the except branch. This is where you can specify the actions to be taken when a specific exception is raised during the execution of the try block.

the try: branch

Explanation

The try block is where you place the code that you want to monitor for exceptions. The except block is where you handle those exceptions that occur within the try block. Therefore, the handling of an exception should be placed inside the except branch.

the exception: branch

Explanation

In Python, there is no exception branch for handling exceptions. The correct structure for exception handling is to place the handling code inside the except block, which is specifically designed for catching and handling exceptions that occur within the try block.

Overall explanation

Topic: except

Try it yourself:

  1. try:
  2. # number = input('Please enter a number\n')
    
  3. number = 'one'
    
  4. zahl = int(number)
    
  5. print('Perfekt!')
    
  6. except:
  7. print('Something went wrong.')
    

Explanation:

It is about exceptions, but the branch is called except:

Q252 (Please refer to this number, if you want to write me about this question.)

Domain

08 – Error Handling

Question 50Skipped

Q217 – Functions

What is the expected output of the following code?

  1. data = {}

  2. def func(d, key, value):

  3. d[key] = value
    
  4. print(func(data, ‘1’, ‘Peter’))

Peter

Explanation

The output is not ‘Peter’ because the function func does not return the value that was assigned to the key in the dictionary. It simply updates the dictionary with the key-value pair ‘1’: ‘Peter’.

Correct answer

None

Explanation

The expected output of the code is None because the function func modifies the dictionary data by adding the key-value pair ‘1’: ‘Peter’, but it does not return any value explicitly. Therefore, the print statement outputs None.

1

Explanation

The output is not 1 because the function func does not return the key that was added to the dictionary. It only modifies the dictionary by assigning the value ‘Peter’ to the key ‘1’.

The code is erroneous.

Explanation

The code is not erroneous as it runs without any syntax errors. However, the function func does not have a return statement, so it implicitly returns None.

value

Explanation

The output is not ‘value’ because the function func does not return the value that was passed as an argument. It only updates the dictionary with the key-value pair ‘1’: ‘Peter’.

Overall explanation

Topics: def return

Try it yourself:

  1. data = {}

  2. def func(d, key, value):

  3. d[key] = value
    
  4. print(func(data, ‘1’, ‘Peter’)) # None

Explanation:

func() has no return statement.

Therefore None gets returned.

Q217 (Please refer to this number, if you want to write me about this question.)

Domain

06 – Functions

Question 51Skipped

Q220 – Modules

Consider the following code.

  1. import random
  2. data = [10, 20, 30]
  3. random.shuffle(data)
  4. print(data)

Which of the following statements best describes the behavior

of the random.shuffle() method?

It will not modify the list.

This function is just a placeholder and yet to be implemented.

Explanation

This statement is incorrect. The random.shuffle() method does modify the original list by shuffling its elements. It is not a placeholder function and is fully implemented for shuffling lists in Python.

It returns a list where the elements 1020 and 30

would be at a random positions.

Explanation

This statement is incorrect. The random.shuffle() method does not return a new list with elements 10, 20, and 30 at random positions. Instead, it shuffles the elements of the original list directly.

It shuffles the elements for the number of times equal to the size of the list.

Explanation

This statement is incorrect. The random.shuffle() method does not shuffle the elements for a specific number of times based on the size of the list. It shuffles the elements in the list once.

Correct answer

It shuffles the elements of the list in-place.

Explanation

The random.shuffle() method shuffles the elements of the list in-place, meaning it modifies the original list directly rather than creating a new shuffled list.

Overall explanation

Topics: random.shuffle() list

Try it yourself:

  1. import random

  2. data = [10, 20, 30]

  3. random.shuffle(data)

  4. print(data) # e.g. [20, 10, 30]

  5. print(random.shuffle(data)) # None

Explanation:

The original list gets shuffled in-place.

The return value is None

Q220 (Please refer to this number, if you want to write me about this question.)

Domain

09 – Modules

Question 52Skipped

Q257 – Functions

What is the expected behavior of the following snippet?

  1. x = 1

  2. def a(x):

  3. return 2 * x
    
  4. x = 2 + a(x) # Line 8

  5. print(a(x)) # Line 9

It will:

print 4

Explanation

This choice is incorrect because the expected output will not be 4. The function a(x) multiplies the input x by 2, so the correct output will be 8, not 4.

Correct answer

print 8

Explanation

The function a(x) takes an input x and returns 2 * x. On Line 8, x is updated to 2 + a(x), which means x will be 2 + 2 * x. When a(x) is called on Line 9 with the updated value of x, it will return 2 * (2 + 2 * x), resulting in 8.

print 6

Explanation

This choice is incorrect because the expected output will not be 6. The function a(x) multiplies the input x by 2, so the correct output will be 8, not 6.

cause a runtime exception on Line 9

Explanation

This choice is incorrect because there will not be a runtime exception on Line 9. The code will run without any errors, and the expected output will be printed successfully.

cause a runtime exception on Line 8

Explanation

This choice is incorrect because there will not be a runtime exception on Line 8. The code will run without any errors, and the expected output will be printed successfully.

Overall explanation

Topics: def return multiplication operator addition operator

Try it yourself:

  1. x = 1

  2. def a(x):

  3. return 2 * x
    
  4. x = 2 + a(x) # Line 8

  5. print(a(x)) # Line 9

  6. 8

Explanation:

The first call of the function a() will pass 1 to the function.

2 * 1 -> 2

The function will return 2

2 + 2 -> 4

The second call of the function a() will pass 4 to the function.

2 * 4 -> 8

8 will be printed.

Q257 (Please refer to this number, if you want to write me about this question.)

Domain

06 – Functions

Question 53Skipped

Q223 – Basics

What is the expected output of the following code?

  1. x = ‘\\’
  2. print(len(x))

The code is erroneous.

Explanation

The code is not erroneous as it correctly assigns a string to the variable x and prints the length of the string. The expected output is 2, not an error.

4

Explanation

The variable x is assigned the string ‘\\’, which represents two backslashes. Therefore, the length of the string is 2, not 4.

1

Explanation

The variable x is assigned the string ‘\\’, which represents two backslashes. Therefore, the length of the string is 2, not 1.

Correct answer

2

Explanation

The variable x is assigned the string ‘\\’, which represents two backslashes. Therefore, the length of the string is 2, resulting in the output of 2.

Overall explanation

Topics: escaping len()

Try it yourself:

  1. print(len(”)) # SyntaxError: …

  2. print(len(‘\’)) # 1
  3. print(len(‘\’)) # SyntaxError: …

  4. print(len(‘\\’)) # 2

Explanation:

The backslash is the character to escape another character.

If you write '\' the backslash escapes

the ending single quote to a normal character.

It takes its syntactical meaning

and the single quote becomes a normal character

and it looses its ability to end the string.

And therefore we get the syntax error.

If you write '\\' the one backslash escapes the other

and you end up with a string with one normal backslash.

If you write '\\\\' it is kind of the same

and you end up with a string with two normal backslashes.

Q223 (Please refer to this number, if you want to write me about this question.)

Domain

01 – Basics

Question 54Skipped

Q204 – Data Aggregates

What is the expected output of the following code?

  1. data = [
  2. [1, 2, 3, 4],
    
  3. [5, 6, 7, 8],
    
  4. [9, 10, 11, 12],
    
  5. [13, 14, 15, 16]
    
  6. ]
  7. for i in range(0, 4):
  8. print(data[i].pop(), end=' ')
    

1 5 9 13

Explanation

The code is popping the last element from each sublist, not printing the first element of each sublist. Therefore, the expected output will be the last elements of each sublist: 4, 8, 12, 16.

Correct answer

4 8 12 16

Explanation

The code iterates through each sublist in the ‘data’ list and removes the last element from each sublist using the pop() method. Therefore, the expected output will be the last elements of each sublist: 4, 8, 12, 16.

13 14 15 16

Explanation

The code is popping the last element from each sublist, not printing all elements of the last sublist. Therefore, the expected output will be the last elements of each sublist: 4, 8, 12, 16.

1 2 3 4

Explanation

The code is popping the last element from each sublist, not printing the entire sublist. Therefore, the expected output will be the last elements of each sublist: 4, 8, 12, 16.

Overall explanation

Topics: list for range() pop() print() with end parameter

Try it yourself:

  1. data = [

  2. [1, 2, 3, 4],
    
  3. [5, 6, 7, 8],
    
  4. [9, 10, 11, 12],
    
  5. [13, 14, 15, 16]
    
  6. ]

  7. for i in range(0, 4):

  8. print(data[i].pop(), end=' ')  # 4 8 12 16
    
  9. print()

  10. print(list(range(0, 4))) # [0, 1, 2, 3]

  11. print([1, 2, 3, 4].pop()) # 4

  12. print([5, 6, 7, 8].pop()) # 8

  13. print([9, 10, 11, 12].pop()) # 12

  14. print([13, 14, 15, 16].pop()) # 16

Explanation:

data is a two dimensional list.

In every iteration of the for loop,

pop() removes the last element of the corresponding inner list.

That last element gets printed.

The default value of the print() functions end parameter is the line feed.

That gets overwritten here by a single space character.

Q204 (Please refer to this number, if you want to write me about this question.)

Domain

04 – Data Aggregates

Question 55Skipped

Q235 – Modules

Consider the following code.

from x.y import z

The code causes the import of …

entity y from module x from package z

Explanation

This explanation is incorrect because the code from x.y import z does not import the entity y from the module x within the package z. The import statement specifically imports z from y within x, not the other way around.

entity z from module x from package y

Explanation

This explanation is incorrect because the code from x.y import z imports the entity z from the module y within the package x, not the entity z from the module x within the package y.

Correct answer

entity z from module y from package x

Explanation

The code from x.y import z imports the entity z from the module y within the package x. This is the correct explanation as it accurately describes the import statement provided in the code snippet.

entity x from module y from package z

Explanation

This explanation is incorrect because the code from x.y import z does not import the entity x from the module y within the package z. The import statement specifically imports z from y within x, not the other way around.

Overall explanation

Topics: from import

Try it yourself:

  1. First execute the following to create the needed folder and file:

  2. import os

  3. if not os.path.isdir(‘my_package’):

  4. os.mkdir('my_package')
    
  5. text = ”’

  6. def my_function():

  7. print("I am my_function, goo goo g'joob!")
    
  8. ”’

  9. with open(‘my_package/my_module.py’, ‘w’) as f:

  10. f.write(text)
    
  11. from my_package.my_module import my_function

  12. my_function() # I am my_function, goo goo g’joob!

Explanation:

The order is from big to small:

from package.module import entity

Q235 (Please refer to this number, if you want to write me about this question.)

Domain

09 – Modules

Question 56Skipped

Q225 – Data Types

What is the expected output of the following code?

print(chr(ord('z') - 2))

a

Explanation

The code snippet does not involve adding or subtracting any value to the ASCII value of ‘z’. Therefore, the expected output is not ‘a’.

y

Explanation

The code snippet subtracts 2 from the ASCII value of ‘z’ and converts the resulting value back to a character. The ASCII value of ‘y’ is 121, so the expected output is not ‘y’.

Correct answer

x

Explanation

The code snippet first converts the character ‘z’ to its ASCII value using the ord() function, which is 122. Then, it subtracts 2 from the ASCII value and converts the resulting value back to a character using the chr() function. The ASCII value of ‘x’ is 120, so the expected output is ‘x’.

z

Explanation

The code snippet subtracts 2 from the ASCII value of ‘z’ and converts the resulting value back to a character. The ASCII value of ‘z’ is 122, so the expected output is not ‘z’.

Overall explanation

Topics: chr() ord()

Try it yourself:

  1. print(chr(ord(‘z’) – 2)) # x
  2. print(ord(‘z’)) # 122
  3. print(chr(120)) # x

Explanation:

ord() returns an integer representing the Unicode character.

chr() turns that integer back to the Unicode character.

You don’t need to remember the number of every character,

but like in the alphabet x is two before z

Q225 (Please refer to this number, if you want to write me about this question.)

Domain

02 – Data Types

Question 57Skipped

Q233 – Error Handling

The following statement …

assert x == 0

Correct answer

will stop the program if x is not equal to 0

Explanation

This choice is correct because the assert statement in Python is used for debugging purposes to check if a condition is True. If the condition is False, the program will stop and raise an AssertionError, which means that the program will stop if x is not equal to 0.

is erroneous.

Explanation

This choice is incorrect. The assert statement in Python is not erroneous; it is a valid way to check conditions during debugging.

will stop the program if x is equal to 0

Explanation

This choice is incorrect. The program will not stop if x is equal to 0 because the assert statement checks for the condition to be True. If x is equal to 0, the condition is True, and the program will continue running.

has no effect.

Explanation

This choice is incorrect. The assert statement in Python does have an effect, as mentioned earlier. It checks the condition and raises an AssertionError if the condition is False.

Overall explanation

Topic: assert AssertionError

Try it yourself:

  1. x = 0

  2. assert x == 0

  3. print(‘Hello’) # Hello

  4. x = 7

  5. assert x == 0 # AssertionError

  6. print(‘Hello’)

Explanation:

If the assertion (here x == 0) is True

the program will continue.

Otherwise an AssertionError occurs.

Q233 (Please refer to this number, if you want to write me about this question.)

Domain

08 – Error Handling