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

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

Back to result overview

Attempt 1

All domains

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

Collapse all questions

Question 1Skipped

Q327 – Data Types

What is the expected output of the following code?

print(type(1J))

Correct answer

<type 'complex'>

Explanation

The code print(type(1J)) will output “ because the value 1J represents a complex number in Python. The type() function returns the type of the object passed to it, and in this case, it will return the type as complex.

<type 'dict'>

Explanation

The choice “ is incorrect because the value 1J is not a dictionary type in Python. The correct type for the complex number 1J is complex, not dict.

<type 'float'>

Explanation

The choice “ is incorrect because the value 1J is not a floating-point number in Python. It is specifically used to represent a complex number, so the output will not be of type float.

<type 'unicode'>

Explanation

The choice “ is incorrect because the value 1J is not a Unicode string in Python. It is a complex number, so the output will not be of type unicode.

Overall explanation

Topics: type() complex

Try it yourself:

  1. print(type(1J)) # <class ‘complex’>

  2. c = 1j

  3. print(c.real) # 0.0

  4. print(c.imag) # 1.0

  5. print(type(0 + 1j)) # <class ‘complex’>

Explanation:

You can use J or j for complex numbers.

1j is a complex number where the real part is 0 and the imaginary part is 1

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

Domain

02 – Data Types

Question 2Skipped

Q347 – Error Handling

What is the expected output of the following code?

  1. try:
  2. if '1' != 1:
    
  3.     raise FirstError
    
  4. else:
    
  5.     print('FirstError has not occured.')
    
  6. except FirstError:
  7. print('FirstError has occured.')
    
  8. else:
  9. print('None of the above.')
    

None of the above.

Explanation

This choice is incorrect because the code will not reach the "else" block as there is an error in the exception handling part. The code will raise a NameError before reaching the "else" block.

FirstError has occured.

Explanation

This choice is incorrect because the exception "FirstError" is not defined or imported in the code, so it will raise a NameError when trying to raise it. Therefore, the output will not be ‘FirstError has occured.’

Correct answer

The code is erroneous.

Explanation

The code contains an error in the exception handling part. The exception "FirstError" is not defined or imported in the code, so it will raise a NameError when trying to raise it. This makes the code erroneous.

FirstError has not occured.

Explanation

This choice is incorrect because the code will not reach the "else" block as there is an error in the exception handling part. The code will raise a NameError before reaching the "else" block, so the output will not be ‘FirstError has not occurred.’

Overall explanation

Topics: try except if else raise

Try it yourself:

  1. """

  2. class FirstError(Exception):

  3. pass
    
  4. """

  5. try:

  6. if '1' != 1:  # True
    
  7.     raise FirstError
    
  8. else:
    
  9.     print('FirstError has not occured.')
    
  10. except FirstError:

  11. print('FirstError has occured.')
    
  12. else:

  13. print('None of the above.')
    
  14. NameError: name ‘FirstError’ is not defined

Explanation:

FirstError is not a know Python exception.

If you use you own exception class,

it needs to inherit from an existing Python exception class.

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

Domain

08 – Error Handling

Question 3Skipped

Q357 – Control Flow

What is the expected output of the following snippet?

  1. s = ‘python’
  2. for i in range(len(s)):
  3. i = s[i].upper()
    
  4. print(s, end=”)

Correct answer

python

Explanation

The code iterates over each character in the string ‘python’ and converts it to uppercase, but the changes are not reflected back to the original string ‘s’. Therefore, the output remains ‘python’.

The code is erroneous.

Explanation

The code does not have any errors in terms of syntax, but it fails to update the original string ‘s’ with the uppercase characters. As a result, the output remains ‘python’.

P Y T H O N

Explanation

The code attempts to convert each character in the string ‘python’ to uppercase, but since the modifications are not applied to the original string ‘s’, the output remains ‘python’ without any spaces.

P y t h o n

Explanation

The code iterates over each character in the string ‘python’ and converts it to uppercase, but the changes are not saved back to the original string ‘s’. Therefore, the output remains ‘python’ without any spaces.

PYTHON

Explanation

Although the code tries to convert each character in the string ‘python’ to uppercase, the modifications are not stored back in the original string ‘s’. As a result, the output remains ‘python’.

Python

Explanation

The code attempts to convert each character in the string ‘python’ to uppercase, but since the changes are not applied to the original string ‘s’, the output remains ‘python’.

Overall explanation

Topics: for range() len() upper() string indexing

Try it yourself:

  1. s = ‘python’
  2. for i in range(len(s)):
  3. i = s[i].upper()
    
  4. # s[i] = s[i].upper()  # TypeError: ...
    
  5. print(s, end="") # python

Explanation:

A string is immutable.

You can not change it, even if you tried.

Here it is not even tried

otherwise the code would cause a TypeError

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

Domain

05 – Control Flow

Question 4Skipped

Q325 – Operators

Which of the following code snippets will print True to the monitor?

Correct selection

  1. print(‘is’ in ‘This IS Python code.’)

Explanation

The ‘in’ operator in Python checks if a specified value exists in a sequence (string, list, tuple, etc.). In this code snippet, the ‘is’ operator is used to check if the string ‘is’ is present in the string ‘This IS Python code.’. Since the substring ‘is’ is present in the string, the expression will evaluate to True.

Correct selection

  1. print(‘t’ in ‘Peter’)

Explanation

The ‘in’ operator in Python checks if a specified value exists in a sequence (string, list, tuple, etc.). In this code snippet, the ‘t’ character is checked for in the string ‘Peter’. Since the character ‘t’ is present in the string, the expression will evaluate to True.

  1. x = ‘Peter Wellert’
  2. y = ‘Peter Wellert’.lower()
  3. print(x is y)

Explanation

The ‘is’ operator in Python checks if two variables refer to the same object in memory. In this code snippet, the variable x is assigned the string ‘Peter Wellert’, while y is assigned the lowercase version of the same string. Since the two strings are stored in different memory locations due to the case difference, the expression will evaluate to False.

  1. x = 42
  2. y = 42
  3. print(x is not y)

Explanation

The ‘is’ operator in Python checks if two variables refer to the same object in memory. In this code snippet, the variables x and y are assigned the same integer value of 42. However, since integers are immutable objects in Python, they are stored in different memory locations. Therefore, the expression will evaluate to False.

  1. x = [‘Peter’, ‘Paul’, ‘Mary’]
  2. y = [‘Peter’, ‘Paul’, ‘Mary’]
  3. print(x is y)

Explanation

The ‘is’ operator in Python checks if two variables refer to the same object in memory. In this code snippet, two lists x and y are created with the same elements. Even though the elements are the same, lists are mutable objects in Python, and each list is stored in a different memory location. Therefore, the expression will evaluate to False.

Overall explanation

Topics: lower() identity operator membership operator list

Try it yourself:

  1. print(‘is’ in ‘This IS Python code.’) # True

  2. print(‘t’ in ‘Peter’) # True

  3. x = 42

  4. y = 42

  5. print(x is not y) # False

  6. x = ‘Peter Wellert’

  7. y = ‘Peter Wellert’.lower()

  8. print(x is y) # False

  9. x = ‘Peter Wellert’

  10. y = ‘Peter Wellert’

  11. print(x is y) # True

  12. x = [‘Peter’, ‘Paul’, ‘Mary’]

  13. y = [‘Peter’, ‘Paul’, ‘Mary’]

  14. print(x is y) # False

  15. print(x == y) # True

Explanation:

The membership operator works very good with strings.

It looks for a string in a string.

The identity operator with immutable data types (here int and string):

The 42 in x and y will reference to the same object.

Therefore they have the same identity

and the not identity operator will evaluate to False

One string will be changed by lower() to peter wellert

and therefore they will not have the same identity.

The identity operator with mutable data types (here list):

A new list will be a new object even if the values are the same.

Therefore they will not have the same identity.

But they will have the same values,

which you can check with the equal to operator

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

Domain

03 – Operators

Question 5Skipped

Q309 – Control Flow

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

  1. data = [[x for x in range(y)] for y in range(3)]

  2. for d in data:

  3. if len(d) < 2:
    
  4.     print('*')
    

Correct answer

two

Explanation

The list comprehension generates lists with varying lengths: [0], [0, 1], and [0, 1, 2]. The loop iterates over each list and checks if the length is less than 2. Only the first list [0] has a length less than 2, so the print statement will execute once, resulting in two stars being printed.

three

Explanation

The list comprehension generates lists with lengths [0], [0, 1], and [0, 1, 2]. The print statement inside the loop only executes when the length of the list is less than 2. Since only the first list [0] meets this condition, the print statement will execute once, resulting in three stars being printed.

one

Explanation

The list comprehension generates lists with lengths [0], [0, 1], and [0, 1, 2]. The print statement inside the loop only executes when the length of the list is less than 2. Since only the first list [0] meets this condition, only one star will be printed to the monitor.

zero

Explanation

The list comprehension generates lists with lengths [0], [0, 1], and [0, 1, 2]. However, the print statement inside the loop only executes when the length of the list is less than 2. Since only the first list [0] meets this condition, no stars will be printed to the monitor.

Overall explanation

Topics: list comprehension if len()

Try it yourself:

  1. data = [[x for x in range(y)] for y in range(3)]

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

  3. for d in data:

  4. print('d:', d)  # [] -> [0] -> [0, 1]
    
  5. if len(d) < 2:
    
  6.     print('*')  # * *
    

Explanation:

The list comprehension produces a two-dimensional list.

The outer list has three elements.

Each of which is as long as its index: [][0] and [0, 1]

The if in the for loop checks that length.

Two of the three are smaller than 2 and therefore two stars are printed.

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

Domain

05 – Control Flow

Question 6Skipped

Q355 – Modules

You want to find the hypotenuse of a right-angled triangle where perpendicular and base are known:

  1. Line 1

  2. parendicular = 3
  3. base = 4
  4. print(hypot(parendicular, base))

What is missing in Line 1?

Correct answer

from math import hypot

Explanation

The correct choice is to import the hypot function from the math module in order to use it in the code. This allows the code to access the hypot function from the math module and calculate the hypotenuse of the triangle.

Nothing at all.

Explanation

Importing the hypot function from the math module is required in order to use it for calculating the hypotenuse. Without importing the hypot function from the math module, the code will not recognize the hypot function and will result in a NameError.

import math

Explanation

While importing the entire math module is a valid option, it is not necessary to import the entire module when only the hypot function is needed. Importing the entire math module may result in unnecessary overhead and decrease code readability.

import hypot

Explanation

There is no standalone hypot module in Python, so importing ‘hypot’ directly will result in a ModuleNotFoundError. The hypot function is a part of the math module, so importing ‘math’ and then using ‘hypot’ from it is the correct approach.

Overall explanation

Topics: math.hypot()

Try it yourself:

  1. from math import hypot
  2. parendicular = 3
  3. base = 4
  4. print(hypot(parendicular, base)) # 5.0

Explanation:

If you want to use the hypot() function without having to write math

in front of it you have to import it like this.

The alternative would be:

  1. import math
  2. parendicular = 3
  3. base = 4
  4. print(math.hypot(parendicular, base)) # 5.0

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

Domain

09 – Modules

Question 7Skipped

Q341 – Error Handling

What is the expected output of the following code?

  1. try:
  2. file = open('data.txt', 'r')
    
  3. file.write('Hello file!')
    
  4. except:
  5. print('An error occurred.')
    
  6. else:
  7. print('The content is written successfully.')
    

The code is erroneous.

Explanation

The code is not erroneous, but it will raise an error when trying to write to a file opened in read mode (‘r’). The output will not be ‘The code is erroneous.’

Hello file!

Explanation

The code will not reach the ‘file.write()’ line because the file is opened in read mode (‘r’). Therefore, the ‘try’ block will not be able to write to the file, and the output will not be ‘Hello file!’

Correct answer

An error occurred.

Explanation

The code will raise an error when trying to write to a file that is opened in read mode (‘r’). The ‘except’ block will be executed, and the output will be ‘An error occurred.’

The content is written successfully.

Explanation

Since the file is opened in read mode (‘r’), the ‘file.write()’ line will raise an error, causing the ‘except’ block to be executed. Therefore, the output will not be ‘The content is written successfully.’

Overall explanation

Topics: try except else open() write()

io.UnsupportedOperation

Try it yourself:

  1. try:

  2. file = open('data.txt', 'r')
    
  3. file.write('Hello file!')
    
  4. except:

  5. print('An error occurred.')  # An error occurred.
    
  6. else:

  7. print('The content is written successfully.')
    
  8. This happens, when the file doesn’t exist:

  9. file = open(‘data.txt’, ‘r’) # FileNotFoundError

  10. This happens, when the file exists:

  11. file = open(‘data.txt’, ‘w’)

  12. file.close()

  13. file = open(‘data.txt’, ‘r’)

  14. file.write(‘Hello file!’). # io.UnsupportedOperation: not writable

Explanation:

If a file gets opened with the modus r it is only readable.

But if the file does not exist, you will get a FileNotFoundError

The except block will be executed.

If the file did exist,

in the next line the write() method will fail,

because the file is only opened for reading.

You will get an io.UnsupportedOperation error

and the except block will be executed.

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

Domain

08 – Error Handling

Question 8Skipped

Q317 – Data Aggregates

What is the expected output of the following code?

  1. data = ()
  2. print(data.len())

1

Explanation

This choice is incorrect because the code initializes an empty tuple, so the length of the tuple is 0. Therefore, the expected output is not 1.

Correct answer

0

Explanation

The code initializes an empty tuple named ‘data’ and then uses the len() method to get the length of the tuple. Since the tuple is empty, the length of the tuple is 0, so the expected output is 0.

The code is erroneous.

Explanation

This choice is incorrect because the code is not erroneous. It correctly initializes an empty tuple and prints the length of the tuple, which is 0.

None

Explanation

This choice is incorrect because the code explicitly calls the len() method on the tuple ‘data’ and prints the result. It does not return None as the output.

Overall explanation

Topics: __len__() tuple

Try it yourself:

  1. data = ()

  2. print(data.len()) # 0

  3. print(len(data)) # 0

  4. print(type(data)) # <class ‘tuple’>

Explanation:

Every object has the method __len__()

Normally we use the function len() which calls the method __len__()

And sure, the length of an empty tuple is 0

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

Domain

04 – Data Aggregates

Question 9Skipped

Q326 – Functions

What is the expected output of the following code?

  1. def test(x=1, y=2):

  2. x = x + y
    
  3. y += 1
    
  4. print(x, y)
    
  5. test()

3 1

Explanation

This choice is incorrect because the value of x is updated to x + y, which makes x equal to 3. However, y is incremented by 1, resulting in y being equal to 3. Therefore, the correct output is 3 3, not 3 1.

1 1

Explanation

This choice is incorrect because the values of x and y are not left unchanged. The function modifies the values of x and y according to the defined operations, resulting in x = 3 and y = 3.

1 3

Explanation

This choice is incorrect because the value of x is updated to x + y, which makes x equal to 3. However, y is incremented by 1, resulting in y being equal to 3. Therefore, the correct output is 3 3, not 1 3.

Correct answer

3 3

Explanation

The default values for x and y are 1 and 2, respectively. In the function, x is updated to x + y, which results in x being 3 (1 + 2). Then, y is incremented by 1, making y equal to 3. Therefore, the output of the function will be 3 3.

The code is erroneous.

Explanation

This choice is incorrect because the code provided is not erroneous. The function definition and execution are valid, and the output can be determined based on the operations performed within the function.

Overall explanation

Topics: def parameters

Try it yourself:

  1. def test(x=1, y=2):

  2. x = x + y    # 1 + 2 -> 3
    
  3. y += 1       # 2 + 1 -> 3
    
  4. print(x, y)  # 3 3
    
  5. test()

Explanation:

The function gets called without an argument.

The parameter x and y get filled with their default values.

Then two little calculations and the printing.

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

Domain

06 – Functions

Question 10Skipped

Q334 – Modules

Assuming that all three files x.pyy.py, and z.py reside in the same folder,

what will be the output produced by running the z.py file?

x.py:

  1. print(‘x’, end=”)

y.py:

  1. import x
  2. print(‘y’, end=”)

z.py:

  1. print(‘z’, end=”)
  2. import x
  3. import y

zyx

Explanation

This choice is incorrect because the correct order of execution will be ‘zxy’, not ‘zyx’. The z.py file first prints ‘z’, then imports the x module which prints ‘x’, and finally imports the y module which prints ‘y’.

zxxy

Explanation

This choice is incorrect because the correct output will not have two ‘x’s in it. The order of execution will be ‘zxy’, with ‘z’ printed first, followed by ‘x’ and then ‘y’.

The code is erroneous.

Explanation

This choice is incorrect as the code is not erroneous. The output will be ‘zxy’ as explained in the correct choice. The code imports the x and y modules correctly and prints ‘z’, ‘x’, and ‘y’ in the expected order.

Correct answer

zxy

Explanation

The output will be ‘zxy’ because the z.py file first prints ‘z’, then imports the x module which prints ‘x’, and finally imports the y module which prints ‘y’. The order of execution will be z -> x -> y.

Overall explanation

Topic: import

Try it yourself:

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

  2. text = ”’

  3. print(‘x’, end=”)

  4. ”’

  5. with open(‘x.py’, ‘w’) as f:

  6. f.write(text)
    
  7. text = ”’

  8. import x

  9. print(‘y’, end=”)

  10. ”’

  11. with open(‘y.py’, ‘w’) as f:

  12. f.write(text)
    
  13. text = ”’

  14. print(‘z’, end=”)

  15. import x

  16. import y

  17. ”’

  18. with open(‘z.py’, ‘w’) as f:

  19. f.write(text)
    
  20. import z # zxy

Explanation:

Remember that imported files get executed only once.

When you import them a second time, they will not get executed again.

When you run the file z.py z gets printed.

x gets imported and x gets printed.

Then y gets imported.

That will not import x again, because x has already been import.

y gets printed and that’s it.

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

Domain

09 – Modules

Question 11Skipped

Q333 – Data Types

Consider the following python code:

  1. x1 = ’23’

  2. y1 = 7

  3. z1 = x1 * y1

  4. x2 = 42

  5. y2 = 7

  6. z2 = x2 / y2

  7. x3 = 4.7

  8. y3 = 1

  9. z3 = x3 / y3

What are the data types of the variables z1z2 and z3?

str, int, float

Explanation

The variable z1 is the result of multiplying a string (’23’) by an integer (7), which will result in a string. The variable z2 is the result of dividing an integer (42) by another integer (7), which will result in an integer. The variable z3 is the result of dividing a float (4.7) by an integer (1), which will result in a float.

str, int, int

Explanation

The variable z1 is the result of multiplying a string (’23’) by an integer (7), which will result in a string. The variable z2 is the result of dividing an integer (42) by another integer (7), which will result in an integer. The variable z3 is the result of dividing a float (4.7) by an integer (1), which will result in an integer.

str, str, str

Explanation

The variable z1 is the result of multiplying a string (’23’) by an integer (7), which will result in a string. The variable z2 is the result of dividing an integer (42) by another integer (7), which will result in an integer. The variable z3 is the result of dividing a float (4.7) by an integer (1), which will result in a string.

Correct answer

str, float, float

Explanation

The variable z1 is the result of multiplying a string (’23’) by an integer (7), which will result in a string. The variable z2 is the result of dividing an integer (42) by another integer (7), which will result in a float. The variable z3 is the result of dividing a float (4.7) by an integer (1), which will also result in a float.

Overall explanation

Topics: string integer float division operator

multiply operator string concatenation

Try it yourself:

  1. x1 = ’23’

  2. y1 = 7

  3. z1 = x1 * y1

  4. print(’23’ * 7) # ‘23232323232323’

  5. x2 = 42

  6. y2 = 7

  7. z2 = x2 / y2

  8. print(42 / 7) # 6.0

  9. x3 = 4.7

  10. y3 = 1

  11. z3 = x3 / y3

  12. print(4.7 / 1) # 4.7

  13. print(type(z1)) # <class ‘str’>

  14. print(type(z2)) # <class ‘float’>

  15. print(type(z3)) # <class ‘float’>

Explanation:

First the string 23 will be multiplied by 7

Second the integer 42 is divided by the integer 7

The result is the float 6.0

Remember the division operator always returns a float

Third the float 4.7 is divided by the integer 1

and surely the result is the float 4.7

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

Domain

02 – Data Types

Question 12Skipped

Q310 – Operators

What is the expected output of the following code?

  1. x = True

  2. y = False

  3. z = False

  4. if x or y and z:

  5. print('TRUE')
    
  6. else:

  7. print('FALSE')
    

The code is erroneous.

Explanation

The code is not erroneous as it follows the correct syntax and logic of Python. The output of the code will be ‘TRUE’ based on the evaluation of the logical operators used in the if statement.

None of the above.

Explanation

None of the above choices are correct as the expected output of the code is ‘TRUE’ based on the evaluation of the logical operators used in the if statement.

Correct answer

TRUE

Explanation

The expected output of the code is ‘TRUE’ because the ‘or’ operator has a higher precedence than the ‘and’ operator. Therefore, the expression ‘x or y and z’ will be evaluated as ‘x or (y and z)’, resulting in ‘True or (False and False)’, which simplifies to ‘True or False’, and since ‘True’ is one of the operands, the result is ‘True’.

FALSE

Explanation

The expected output of the code is not ‘FALSE’ because the ‘or’ operator has a higher precedence than the ‘and’ operator. Therefore, the expression ‘x or y and z’ will be evaluated as ‘x or (y and z)’, resulting in ‘True or (False and False)’, which simplifies to ‘True or False’, and since ‘True’ is one of the operands, the result is ‘True’, not ‘False’.

Overall explanation

Topics: logical operators operator precedence if else

Try it yourself:

  1. x = True

  2. y = False

  3. z = False

  4. if x or y and z:

  5. print('TRUE')                 # TRUE
    
  6. else:

  7. print('FALSE')
    
  8. print(x or y and z) # True

  9. print(True or False and False) # True

  10. print(True or (False and False)) # True

  11. print(True or False) # True

  12. print(True) # True

Explanation:

The one important thing here is, that the logical and operator

has a higher precedence than the logical or operator

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

Domain

03 – Operators

Question 13Skipped

Q314 – Functions

What is the expected output of the following code?

  1. def func(item):

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

  4. func(data)

  5. print(len(data))

4

Explanation

The output is not 4 because the function func modifies the original list data by adding an element to it. As a result, the length of the data list will be 5, not 4.

The code is erroneous.

Explanation

The code is not erroneous. The function func modifies the original list data by adding an element to it, and the length of the modified data list is printed correctly.

2

Explanation

The output is not 2 because the function func modifies the original list data by adding an element to it. As a result, the length of the data list will be 5, not 2.

Correct answer

5

Explanation

The expected output of the code is 5 because the function func takes a list item as a parameter, appends the value 1 to it, and modifies the original list data. Therefore, the length of the modified data list will be 5.

Overall explanation

Topics: list plus operator list concatenation mutable argument

Try it yourself:

  1. def func(item):

  2. item += [1]   # [1, 2, 3, 4] + [1] -> [1, 2, 3, 4, 1]
    
  3. data = [1, 2, 3, 4]

  4. func(data)

  5. print(len(data)) # 5

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

  7. x = [1, 2, 3, 4]

  8. x.append([1])

  9. print(x) # [1, 2, 3, 4, [1]]

Explanation:

Inside the function a list concatenation by plus operator takes place.

The plus operator merges the elements of the second list into the first list.

append() would insert the list itself into the other list.

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

Domain

06 – Functions

Question 14Skipped

Q353 – Basics

UNICODE is a standard:

Correct answer

like ASCII, but much more expansive.

Explanation

UNICODE is a standard that encompasses a much wider range of characters compared to ASCII. It includes characters from various languages, symbols, emojis, and special characters, making it more expansive and versatile for encoding text.

used by coders from universities.

Explanation

UNICODE is a standard used by a wide range of developers, organizations, and industries, not just coders from universities. It is a fundamental standard for text encoding and character representation in various software applications, websites, and communication protocols.

for coding floating-point numbers.

Explanation

UNICODE is primarily designed for encoding text characters and symbols, not specifically for coding floating-point numbers. Floating-point numbers are typically represented using different standards or formats, such as IEEE 754, rather than UNICODE.

honored by the whole universe.

Explanation

While UNICODE is a widely accepted and used standard for encoding text, it is not necessarily honored by the entire universe. It is a standard adopted by many organizations, software developers, and industries, but its usage may vary depending on the specific requirements and technologies used.

Overall explanation

Topics: Unicode ASCII

Explanation:

Read about it here:

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

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

Domain

01 – Basics

Question 15Skipped

Q303 – Operators

What is the expected output of the following code?

x = 4.5

y = 2

print(x // y)

2.5

Explanation

This choice is incorrect because the floor division operator (//) always rounds down to the nearest integer. In this case, 4.5 divided by 2 results in 2.0, not 2.5.

2.25

Explanation

This choice is incorrect because the floor division operator (//) always rounds down to the nearest integer. In this case, 4.5 divided by 2 results in 2.0, not 2.25.

2

Explanation

This choice is incorrect because the floor division operator (//) always rounds down to the nearest integer. In this case, 4.5 divided by 2 results in 2.0, not 2.

Correct answer

2.0

Explanation

The floor division operator (//) in Python performs division where the result is the quotient rounded down to the nearest integer. In this case, 4.5 divided by 2 results in 2.0 as the output.

Overall explanation

Topic: floor division operator

Try it yourself:

  1. print(4.5 // 2) # 2.0
  2. print(4.5 // 2.0) # 2.0
  3. print(4 // 2.0) # 2.0
  4. print(4 // 2) # 2

Explanation:

If one operand is a float, the floor division operator returns a float.

Only if both operands are an integer,

the floor division operator returns an integer.

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

Domain

03 – Operators

Question 16Skipped

Q305 – Control Flow

What is the expected output of the following code?

  1. my_list = [[3-i for i in range(3)] for j in range(3)]

  2. result = 0

  3. for i in range(3):

  4. result += my_list[i][i]
    
  5. print(result)

Correct answer

6

Explanation

The code creates a 3×3 nested list where each element is the result of subtracting the inner loop variable i from 3. The for loop then iterates over the main list and adds the diagonal elements (my_list[i][i]) to the result variable. In this case, the diagonal elements are [3, 2, 1], which sum up to 6.

4

Explanation

The code does not sum up all elements of the nested list, but only the diagonal elements. The diagonal elements are [3, 2, 1], which sum up to 6. Therefore, the output is not 4.

7

Explanation

The code does not sum up all elements of the nested list, but only the diagonal elements. The diagonal elements are [3, 2, 1], which sum up to 6. Therefore, the output is not 7.

2

Explanation

The code does not sum up all elements of the nested list, but only the diagonal elements. The diagonal elements are [3, 2, 1], which sum up to 6. Therefore, the output is not 2.

Overall explanation

Topics: list comprehension list indexing for

Try it yourself:

  1. data = [[3-i for i in range(3)] for j in range(3)]

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

  3. res = 0

  4. for i in range(3):

  5. print('data[' + str(i) + '][' + str(i) + ']: ', data[i][i])
    
  6. """
    
  7. data[0][0]: 3
    
  8. data[1][1]: 2
    
  9. data[2][2]: 1
    
  10. """
    
  11. res += data[i][i]
    
  12. print(res) # 6 (3 + 2 + 1)

Explanation:

The list comprehension produces a two-dimensional list.

The three elements of the outer list also each have three elements:

the numbers 3, 2, 1

The for loop will add together

the first element of the first list 3

the second element of the second list 2

and the third element of the third list 1

3 + 2 + 1 -> 6

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

Domain

05 – Control Flow

Question 17Skipped

Q350 – Error Handling

Select the true statements.

Choose two.

You cannot use multiple except: branches to handle multiple exceptions coming from the same try: branch.

Explanation

This statement is incorrect. In Python, you can use multiple except: branches to handle multiple exceptions coming from the same try: block. This flexibility allows for more precise error handling based on the specific exceptions that may be raised.

Different except: branches may have unique exception names.

Explanation

Different except: branches in Python may have unique exception names to distinguish between different types of exceptions. This helps in providing specific error handling for each type of exception that may occur in the try: block.

Correct selection

Different except: branches must have unique exception names.

Explanation

In Python, different except: branches must have unique exception names to handle different types of exceptions separately. This allows for specific error handling based on the type of exception raised in the try: block.

Correct selection

You can use multiple except: branches to handle multiple exceptions coming from the same try: branch.

Explanation

You can use multiple except: branches in Python to handle multiple exceptions coming from the same try: block. This allows for more granular error handling by specifying different actions for different types of exceptions that may occur.

Overall explanation

Topics: try except

Try it yourself:

  1. Example 1:

  2. try:

  3. number = int(input('Please enter a number:\n'))
    
  4. result = 42 / number
    
  5. except ValueError:

  6. print('You can only use digits.')
    
  7. except ZeroDivisionError:

  8. print('Do not enter a zero.')
    
  9. else:

  10. print(result)
    
  11. Example 2:

  12. try:

  13. number = int(input('Please enter a number:\n'))
    
  14. result = 42 / number
    
  15. except ValueError:

  16. print('You can only use digits.')
    
  17. except ZeroDivisionError:

  18. print('Do not enter a zero.')
    
  19. except ZeroDivisionError:

  20. print('This code is unreachable.')
    
  21. else:

  22. print(result)
    

Explanation:

Yes, you can absolutely use multiple except: branches

with the same try: branch (Example 1).

And yes, different except: branches must have unique exception names.

You don’t get an error message, but you would have unreachable code.

Like in Example 2:

The first except ZeroDivisionError: branch will be executed

and the second except ZeroDivisionError: branch can never be executed.

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

Domain

08 – Error Handling

Question 18Skipped

Q328 – Data Types

What is the expected output of the following code?

print(ord('c') – ord('a'))

Correct answer

2

Explanation

The ord() function in Python returns the Unicode code point of a character. In this case, ord(‘c’) returns 99 and ord(‘a’) returns 97. Subtracting these values (99 – 97) gives the output of 2.

3

Explanation

This choice is incorrect because subtracting the Unicode code points of ‘c’ and ‘a’ (99 – 97) does not result in 3.

1

Explanation

This choice is incorrect because subtracting the Unicode code points of ‘c’ and ‘a’ (99 – 97) does not result in 1.

0

Explanation

This choice is incorrect because subtracting the Unicode code points of ‘c’ and ‘a’ (99 – 97) does not result in 0.

Overall explanation

Topic: ord()

Try it yourself:

  1. print(ord(‘c’) – ord(‘a’)) # 2
  2. print(ord(‘c’)) # 99
  3. print(ord(‘a’)) # 97

Explanation:

ord() returns an integer representing the Unicode character.

You do not need to remember the number of each character,

but like in the alphabet c is two after a

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

Domain

02 – Data Types

Question 19Skipped

Q343 – Control Flow

Consider the following programm to calculate a discount percentage:

  1. day = input(‘Enter the day of the week:’)

  2. discount = 3

  3. if day == ‘Wednesday’:

  4. discount += 5
    
  5. elif day == ‘Thursday’:

  6. discount += 7
    
  7. elif day == ‘Saturday’:

  8. discount += 10
    
  9. elif day == ‘Sunday’:

  10. discount += 20
    
  11. else:

  12. discount += 2
    

Which of the following inputs will get the user a discount of 5 %?

Wednesday

Explanation

Wednesday is explicitly mentioned in the if-elif chain, and it will trigger the discount increase by 5, resulting in a total discount of 8%.

Saturday

Explanation

Saturday is explicitly mentioned in the if-elif chain, and it will trigger the discount increase by 10, resulting in a total discount of 13%.

Sunday

Explanation

Sunday is explicitly mentioned in the if-elif chain, and it will trigger the discount increase by 20, resulting in a total discount of 23%.

Correct answer

Friday

Explanation

Friday is not explicitly mentioned in the if-elif chain, so the default discount of 3 will be applied, resulting in a 5% discount for the user.

Thursday

Explanation

Thursday is explicitly mentioned in the if-elif chain, and it will trigger the discount increase by 7, resulting in a total discount of 10%.

Overall explanation

Topic: if elif else

Try it yourself:

  1. day = input(‘Enter the day of the week:’)

  2. day = ‘Friday’ # Just for convenience

  3. day = ‘Wednesday’ # 8

  4. day = ‘Thursday’ # 10

  5. day = ‘Saturday’ # 13

  6. day = ‘Sunday’. # 23

  7. discount = 3

  8. if day == ‘Wednesday’:

  9. discount += 5
    
  10. elif day == ‘Thursday’:

  11. discount += 7
    
  12. elif day == ‘Saturday’:

  13. discount += 10
    
  14. elif day == ‘Sunday’:

  15. discount += 20
    
  16. else:

  17. discount += 2
    
  18. print(discount) # 5

Explanation:

Friday is in none of the conditions and therefore the else clause gets executed.

And 3 plus 2 is 5

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

Domain

05 – Control Flow

Question 20Skipped

Q313 – Functions

What is the expected output of the following code?

  1. def func(x, y=2):

  2. num = 1
    
  3. for i in range(y):
    
  4.     num = num * x
    
  5. return num
    
  6. print(func(4))

  7. print(func(4, 4))

  8. 128

  9. 512

Explanation

This choice is incorrect because it does not match the expected output of the code. The function func calculates the result of x raised to the power of y, so the output values should be 16 and 256 for the given input values.

Correct answer

  1. 16
  2. 256

Explanation

The function func takes two parameters, x and y, with a default value of 2 for y. It then initializes num to 1 and multiplies x by num y times using a for loop. When func(4) is called, it calculates 4^2, which is 16. When func(4, 4) is called, it calculates 4^4, which is 256.

  1. 32
  2. 1024

Explanation

This choice is incorrect because it does not match the expected output of the code. The function func calculates the result of x raised to the power of y, so the output values should be 16 and 256 for the given input values.

  1. 8
  2. 16

Explanation

This choice is incorrect because it does not match the expected output of the code. The function func calculates the result of x raised to the power of y, so the output values should be 16 and 256 for the given input values.

Overall explanation

Topics: def for range()

Try it yourself:

  1. def func(x, y=2):

  2. num = 1
    
  3. for i in range(y):
    
  4.     num = num * x
    
  5. return num
    
  6. print(func(4)) # 16 (4 * 4)

  7. print(func(4, 4)) # 256 (4 * 4 * 4 * 4)

  8. import math

  9. print(math.pow(4, 2)) # 16.0

  10. print(math.pow(4)) # TypeError: pow expected 2 arguments, got 1

Explanation:

The second parameter determines

how often the first parameter is multiplied by itself.

Like the method math.pow() but additionally with a default parameter

for the exponent with the default value of 2

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

Domain

06 – Functions

Question 21Skipped

Q308 – Control Flow

What is the expected output of the following code?

print(len([i for i in range(0, -2)]))

Correct answer

0

Explanation

The range function in Python generates a sequence of numbers starting from the first parameter (0 in this case) up to, but not including, the second parameter (-2 in this case). Since there are no numbers between 0 and -2, the list comprehension will not generate any elements, resulting in a length of 0 for the list.

2

Explanation

The range function in Python generates a sequence of numbers starting from the first parameter (0 in this case) up to, but not including, the second parameter (-2 in this case). Since there are no numbers between 0 and -2, the list comprehension will not generate any elements, resulting in a length of 0 for the list, not 2.

3

Explanation

The range function in Python generates a sequence of numbers starting from the first parameter (0 in this case) up to, but not including, the second parameter (-2 in this case). Since there are no numbers between 0 and -2, the list comprehension will not generate any elements, resulting in a length of 0 for the list, not 3.

1

Explanation

The range function in Python generates a sequence of numbers starting from the first parameter (0 in this case) up to, but not including, the second parameter (-2 in this case). Since there are no numbers between 0 and -2, the list comprehension will not generate any elements, resulting in a length of 0 for the list, not 1.

Overall explanation

Topics: list comprehension range() len()

Try it yourself:

  1. print(len([i for i in range(0, -2)])) # 0

  2. Those make more sense:

  3. print(len([i for i in range(0, -2, -1)])) # 2

  4. print(len([i for i in range(-2, 0)])) # 2

Explanation:

The "problem" here is the range(0, -2)

The start value 0 has to be lower than the end value -2

Otherwise range() does not return an element.

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

Domain

05 – Control Flow

Question 22Skipped

Q335 – Modules

What is the expected output of the following code?

  1. import math
  2. print(dir(math))

Correct answer

A list of all the entities residing in the math module.

Explanation

The dir() function in Python returns a list of all the entities (functions, classes, variables, etc.) residing in the specified module. In this case, dir(math) will return a list of all the entities in the math module.

A string containing the fully qualified name of the module.

Explanation

The dir() function does not return a string containing the fully qualified name of the module; it returns a list of entities within the module. This choice is incorrect.

The number of all the entities residing in the math module.

Explanation

The dir() function does not return the number of entities in a module; instead, it returns a list of all the entities. Therefore, this choice is incorrect.

The code is erroneous.

Explanation

The code is not erroneous; it is a valid Python code snippet that imports the math module and prints the list of entities in the module using the dir() function. Therefore, this choice is incorrect.

Overall explanation

Topics: import dir()

Try it yourself:

  1. import math

  2. print(dir(math))

  3. """

  4. [‘doc‘, ‘file‘, ‘loader‘, ‘name‘, ‘package‘,

  5. spec‘, ‘acos’, ‘acosh’, ‘asin’, ‘asinh’, ‘atan’, ‘atan2’,

  6. ‘atanh’, ‘ceil’, ‘comb’, ‘copysign’, ‘cos’, ‘cosh’, ‘degrees’,

  7. ‘dist’, ‘e’, ‘erf’, ‘erfc’, ‘exp’, ‘expm1’, ‘fabs’, ‘factorial’,

  8. ‘floor’, ‘fmod’, ‘frexp’, ‘fsum’, ‘gamma’, ‘gcd’, ‘hypot’, ‘inf’,

  9. ‘isclose’, ‘isfinite’, ‘isinf’, ‘isnan’, ‘isqrt’, ‘lcm’, ‘ldexp’,

  10. ‘lgamma’, ‘log’, ‘log10’, ‘log1p’, ‘log2’, ‘modf’, ‘nan’,

  11. ‘nextafter’, ‘perm’, ‘pi’, ‘pow’, ‘prod’, ‘radians’, ‘remainder’,

  12. ‘sin’, ‘sinh’, ‘sqrt’, ‘tan’, ‘tanh’, ‘tau’, ‘trunc’, ‘ulp’]

  13. """

Explanation:

The dir() function returns the names of all entities (properties and methods)

of the passed module (or object).

(There is another question about the same topic Q444.)

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

Domain

09 – Modules

Question 23Skipped

Q349 – Modules

What is the expected output of the following code?

  1. from random import randint

  2. for i in range(2):

  3. print(randint(1, 2), end='')
    

There are millions of possible combinations,
and the exact output cannot be predicted.

Explanation

While it is true that there are millions of possible combinations due to the random nature of the randint() function, the output is limited to the range specified in the function (1 to 2). Therefore, the exact output can be predicted within the constraints of the specified range.

Correct answer

111221, or 22

Explanation

The randint() function generates a random integer between the specified range (inclusive). In this case, the range is from 1 to 2. Therefore, the output can be either 1 or 2 for each iteration of the loop, resulting in possible combinations of 11, 12, 21, or 22.

12

Explanation

This choice does not account for the fact that the randint() function can generate either 1 or 2 for each iteration. It only considers the possibility of 12 as the output, which is not accurate based on the random nature of the function.

12, or 21

Explanation

This choice only considers the specific combinations of 12 and 21 as the output, which is not correct. Since the randint() function can generate either 1 or 2 randomly, the output can also include combinations like 11 and 22.

Overall explanation

Topics: import random randint() for range()

Try it yourself:

  1. from random import randint

  2. for i in range(2):

  3. print(randint(1, 2), end='')  # 11, 12, 21, or 22
    

Explanation:

The for loop will have two iterations.

Each time a 1 or a 2 will be printed.

Therefore the result can be 111221, or 22

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

Domain

09 – Modules

Question 24Skipped

Q336 – I/O

You are creating a function that reads a data file

and prints each line of the file.

You write the following code.

  1. import os # Line 01
  2. def read_file(file): # Line 02
  3. line = None                 # Line 03
    
  4. if os.path.isfile(file):    # Line 04
    
  5.     data = open(file, 'r')  # Line 05
    
  6. while line != '':           # Line 06
    
  7.     line = data.readline()  # Line 07
    
  8.     print(line)             # Line 08
    

The code attempts to read the file even if the file does not exist.

You need to correct the code.

Which lines have indentation problems?

Each correct answer presents part of the solution.

Choose three.

Correct selection

Line 07

Explanation

Line 07 should be indented to be inside the while loop block. This ensures that the code reads a line from the file and prints it for each iteration of the while loop.

Correct selection

Line 08

Explanation

Line 08 should be indented to be inside the while loop block. This ensures that the line read from the file is printed for each iteration of the while loop.

Line 04

Explanation

Line 04 does not have an indentation problem. It is correctly placed inside the if statement block that checks if the file exists.

Line 02

Explanation

Line 02 does not have an indentation problem. It is correctly placed at the beginning of the function definition block.

Line 05

Explanation

Line 05 does not have an indentation problem. It is correctly placed inside the if statement block that checks if the file exists.

Correct selection

Line 06

Explanation

Line 06 should be indented to be inside the if statement block that checks if the file exists. This ensures that the while loop only runs when the file exists.

Line 01

Explanation

Line 01 does not have an indentation problem. It is correctly placed at the beginning of the code.

Line 03

Explanation

Line 03 does not have an indentation problem. It is correctly placed inside the function definition block.

Overall explanation

Topics: import def None if os.path.isfile() open()

while readline() not equal to operator

Try it yourself:

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

  2. text = ”’Peter

  3. Paul

  4. Mary

  5. ”’

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

  7. f.write(text)
    
  8. import os # Line 01

  9. def read_file(file): # Line 02

  10. line = None # Line 03
    
  11. if os.path.isfile(file): # Line 04
    
  12.     data = open(file, 'r') # Line 05
    
  13.     while line != '': # Line 06
    
  14.         line = data.readline() # Line 07
    
  15.         print(line) # Line 08
    
  16. read_file(‘data.txt’)

Explanation:

The while loop needs to be inside of the if statement

in order to only read the lines if the file exists.

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

Domain

07 – I/O

Question 25Skipped

Q304 – Control Flow

How many elements will the following list contain?

data = [i for i in range(-1, 2)]

four

Explanation

The list comprehension [i for i in range(-1, 2)] generates elements for each value of i in the range from -1 to 1 (inclusive). Since the range includes three values, the list will not contain four elements.

Correct answer

three

Explanation

The list comprehension [i for i in range(-1, 2)] generates elements for each value of i in the range from -1 to 1 (inclusive). Since the range includes -1, 0, and 1, the list will contain three elements.

one

Explanation

The list comprehension [i for i in range(-1, 2)] generates elements for each value of i in the range from -1 to 1 (inclusive). Since the range includes three values, the list will contain more than one element.

two

Explanation

The list comprehension [i for i in range(-1, 2)] generates elements for each value of i in the range from -1 to 1 (inclusive). As the range includes three values, the list will contain more than two elements.

zero

Explanation

The list comprehension [i for i in range(-1, 2)] generates elements for each value of i in the range from -1 to 1 (inclusive). As this range includes three values, the list will not be empty and will contain elements.

Overall explanation

Topics: list comprehension for

Try it yourself:

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

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

  3. print(len(data)) # 3

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

Explanation:

In data is going be a list with the element -10 and 1

The list comprehension is not necessary if I does not get changed.

The start of range() is inclusive -1

and the end is exclusive, meaning 2 is excluded.

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

Domain

05 – Control Flow

Question 26Skipped

Q319 – Data Aggregates

What is the expected output of the following code?

  1. nums = [1, 2, 3]
  2. data = (‘Peter’,) * (len(nums) – nums[::-1][0])
  3. print(data)

('Peter', 'Peter')

Explanation

This choice is incorrect because the code does not output a tuple with two elements ‘Peter’, ‘Peter’ but an empty tuple ().

PeterPeter

Explanation

This choice is incorrect because the code does not output a string ‘PeterPeter’ but an empty tuple ().

Correct answer

()

Explanation

The code initializes a list ‘nums’ with [1, 2, 3] and a tuple ‘data’ with a single element ‘Peter’. The expression (len(nums) – nums[::-1][0]) evaluates to (3 – 3) which is 0. Multiplying a tuple by 0 results in an empty tuple, so the expected output is ().

The code is erroneous.

Explanation

This choice is incorrect because the code is not erroneous. It correctly calculates the length of the list ‘nums’ and creates a tuple ‘data’ based on that length. The output is an empty tuple ().

('Peter')

Explanation

This choice is incorrect because the code does not output a string ‘Peter’ but an empty tuple ().

Overall explanation

Topics: len() list tuple list slicing list indexing

multiply operator tuple concatenation

Try it yourself:

  1. nums = [1, 2, 3]

  2. data = (‘Peter’,) * (len(nums) – nums[::-1][0])

  3. print(data) # ()

  4. print(len(nums) – nums[::-1][0]) # 0

  5. print(len([1, 2, 3]) – [1, 2, 3][::-1][0]) # 0

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

  7. print(3 – 3) # 0

  8. print(0) # 0

  9. print((‘Peter’,)) # (‘Peter’,)

  10. print(type((‘Peter’,))) # <class ‘tuple’>

  11. print(type((‘Peter’))) # <class ‘str’>

  12. print((‘Peter’,) * 0) # ()

  13. print((1, 2, 3) * 0) # ()

Explanation:

The length of nums is 3

[::-1] reverses the list and then 3 is the first index.

3 minus 3 makes 0

The trailing comma marks the tuple with one element.

Otherwise it would be a string with additional parentheses.

Any tuple multiplied by 0 becomes an empty tuple.

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

Domain

04 – Data Aggregates

Question 27Skipped

Q331 – I/O

Which of the following commands is used

to open a file in binary format for writing only?

open('data.txt', 'wb+')

Explanation

The command open(‘data.txt’, ‘wb+’) is used to open a file for reading and writing in binary mode. While this mode allows both reading and writing operations on the file, it does not restrict the file to be opened in binary format for writing only, as the ‘wb’ mode does.

open('data.txt', 'w+')

Explanation

The command open(‘data.txt’, ‘w+’) is used to open a file for reading and writing in text mode, not binary mode. This mode allows both reading and writing operations on the file, but it does not specifically open the file in binary format for writing only.

open('data.txt', 'w')

Explanation

The command open(‘data.txt’, ‘w’) is used to open a file for writing in text mode, not binary mode. This mode is suitable for writing text data to a file but does not handle binary data as efficiently as the ‘wb’ mode.

Correct answer

open('data.txt', 'wb')

Explanation

The command open(‘data.txt’, ‘wb’) is used to open a file in binary format for writing only. The ‘wb’ mode specifies that the file should be opened for writing in binary mode, ensuring that the file is treated as a binary file and not a text file.

Overall explanation

Topic: open() and its modes

Try it yourself:

  1. data = open(‘data.txt’, ‘wb’)

  2. print(type(data)) # <class ‘_io.BufferedWriter’>

  3. print(data.read()) # io.UnsupportedOperation: read

  4. data = open(‘data.txt’, ‘wb+’)

  5. print(type(data)) # <class ‘_io.BufferedRandom’>

  6. print(data.read()) # b”

  7. data = open(‘data.txt’, ‘w’)

  8. print(type(data)) # <class ‘_io.TextIOWrapper’>

  9. data = open(‘data.txt’, ‘w+’)

  10. print(type(data)) # <class ‘_io.TextIOWrapper’>

Explanation:

You will need the w for writing and the b for the binary format.

But that’s it.

You do not want the + because than it will not be writing only,

but updating (writing and reading).

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

Domain

07 – I/O

Question 28Skipped

Q340 – Data Types

You are an intern for ABC electric cars company.

You must create a function that calculates the average velocity

of their vehicles on a 1320 foot (1/4 mile) track.

Consider the following code.

  1. distance = ???(input(‘Enter the distance travelled in feet’))

  2. distance_miles = distance/5280 # convert to miles

  3. time = ???(input(‘Enter the time elapsed in seconds’))

  4. time_hours = time/3600 # convert to hours

  5. velocity = distance_miles/time_hours

  6. print(‘The average Velocity : ‘, velocity, ‘miles/hour’)

The output must be as precise as possible.

What would you insert instead of ??? and ???

  1. float
  2. int

Explanation

Using the float function for the distance input and the int function for the time input may result in loss of precision during the conversion process. Since time is typically measured in seconds, using int for the time input could lead to rounding errors when converting to hours, affecting the accuracy of the average velocity calculation.

Correct answer

  1. float
  2. float

Explanation

Using the float function for both distance and time inputs ensures that the values entered by the user are treated as floating-point numbers, allowing for more precise calculations when converting to miles and hours respectively. This precision is necessary to accurately calculate the average velocity.

  1. int
  2. int

Explanation

Selecting the int function for both distance and time inputs might lead to significant loss of precision during the conversion process. Given that distance and time are typically measured in decimal values, using int could round down the numbers, potentially causing errors in the final average velocity calculation. Utilizing float data types is essential for maintaining accuracy in this scenario.

  1. int
  2. float

Explanation

Using the int function for the distance input and the float function for the time input may also result in loss of precision. While distance is usually measured in feet, converting it to miles requires decimal points, making float a more suitable choice. Introducing an integer value for distance could lead to inaccurate results when calculating velocity.

Overall explanation

Topics: input() float() int() division operator

Try it yourself:

  1. distance = float(input(‘Enter the distance travelled in feet’))

  2. distance = float(‘437723.42’) # Just for convenience

  3. distance_miles = distance/5280

  4. time = float(input(‘Enter the time elapsed in seconds’))

  5. time = float(‘1723.9’) # Just for convenience

  6. time_hours = time/3600 # convert to hours

  7. velocity = distance_miles/time_hours

  8. print(‘The average Velocity : ‘, velocity, ‘miles/hour’)

  9. The average Velocity : 173.1236071486956 miles/hour

  10. print((float(‘437723.42’)/5280) / (float(‘1723.9’)/3600))

  11. 173.1236071486956

  12. print((int(‘437723.42’)/5280) / (int(‘1723.9’)/3600))

  13. ValueError

  14. print((int(float(‘437723.42’))/5280) / (int(float(‘1723.9’))/3600))

  15. 173.21387115496228

Explanation:

To be as precise as possible means,

that you do not want to loose the numbers after the decimal point,

if they are given by the user.

Therefore you need float() for both inputs.

Assuming the user enters a float

the function int() would raise a ValueError anyway.

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

Domain

02 – Data Types

Question 29Skipped

Q354 – I/O

Which of the following open modes allow you to perform read operations?

Choose two.

w

Explanation

The ‘w’ mode in Python allows you to open a file for writing only. This mode is used when you want to create a new file or overwrite the contents of an existing file. It does not allow read operations on the file.

Correct selection

r

Explanation

The ‘r’ mode in Python allows you to open a file for reading only. This mode is used when you want to perform read operations on a file without modifying its contents.

a

Explanation

The ‘a’ mode in Python allows you to open a file for appending data. This mode is used when you want to add new data to the end of an existing file, but it does not allow direct read operations on the file.

Correct selection

r+

Explanation

The ‘r+’ mode in Python allows you to open a file for both reading and writing. In addition to reading data from the file, you can also write data to it. This mode is useful when you need to perform both read and write operations on a file.

Overall explanation

Topic: open() and its modes

Try it yourself:

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

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

  3. f.write('Hello')
    
  4. with open(‘data.txt’, ‘r’) as f:

  5. print(f.read())  # Hello
    
  6. with open(‘data.txt’, ‘r+’) as f:

  7. print(f.read())  # Hello
    
  8. """

  9. with open(‘data.txt’, ‘a’) as f:

  10. print(f.read())  # io.UnsupportedOperation: not readable
    
  11. """

  12. """

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

  14. print(f.read())  # io.UnsupportedOperation: not readable
    
  15. """

Explanation:

The mode r opens in read only mode

and the mode r+ opens in read & write mode.

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

Domain

07 – I/O

Question 30Skipped

Q324 – Operators

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

  1. x = float(input())
  2. y = float(input())
  3. print(y ** (1 / x))

0.0

Explanation

The output will not be 0.0. The calculation involves raising y to the power of (1/x), which will result in a non-zero value when x and y are both non-zero.

1.0

Explanation

The output will not be 1.0. The calculation involves raising y to the power of (1/x), which will not necessarily result in 1.0 when x and y are 2 and 4, respectively.

4.0

Explanation

The output will not be 4.0. The calculation involves raising y to the power of (1/x), which will not result in 4.0 when x and y are 2 and 4, respectively.

Correct answer

2.0

Explanation

The code takes two float inputs from the user and calculates y to the power of (1/x). In this case, if the user enters 2 and 4, the output will be 2.0 as 4 to the power of (1/2) is equal to 2.0.

Overall explanation

Topics: input() float() exponentiation operator

division operator square root

Try it yourself:

  1. x = float(input())

  2. y = float(input())

  3. x, y = float(‘2’), float(‘4’) # Just for convenience
  4. print(y ** (1 / x)) # 2.0
  5. print(4.0 ** (1 / 2)) # 2.0
  6. print(4.0 ** 0.5) # 2.0
  7. import math
  8. print(math.sqrt(4)) # 2.0

Explanation:

As always input() returns a string

They both get casted to a float

Here you need a little bit of mathematical knowledge.

You can take the square root of a number by raising it to the power of 0.5

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

Domain

03 – Operators

Question 31Skipped

Q332 – I/O

You want to write a new player to a file

and print the whole file content to the monitor.

What snippet would you insert in the line indicated below:

  1. customer = ‘Peter Wellert’
  2. with open(‘customers.txt’, ‘a+’) as f:
  3. f.write(customer)
    
  4. # insert your code here
    
  5. data = f.read()
    
  6. print(data)
    

f.begin()

Explanation

There is no f.begin() method in Python file handling. This choice is incorrect as it does not correspond to any valid file operation in Python. It is not applicable to the scenario where you need to read the full file content after writing to it.

f.close()

Explanation

f.close() is used to close the file after reading or writing operations, but if you close the file before reading the content, you won’t be able to access the file data. This choice is incorrect for this scenario where you want to print the whole file content to the monitor after writing a new player.

Correct answer

f.seek(0)

Explanation

Using f.seek(0) will move the file cursor to the beginning of the file, allowing you to read the entire content of the file after writing the new player’s name. This is the correct choice to ensure that you can read the full file content after writing to it.

f.flush()

Explanation

f.flush() is used to flush the internal buffer of the file, but it does not move the file cursor or enable you to read the entire content of the file. It is not the correct choice for this scenario where you need to read the full file content after writing to it.

Overall explanation

Topics: with open() write() seek() read() flush() close()

Try it yourself:

  1. First execute the following to create a file

  2. with already existing players:

  3. players = ”’Peter

  4. Paul

  5. Mary

  6. Jane

  7. ”’

  8. with open(‘players.txt’, ‘w’) as f:

  9. f.write(players)
    
  10. player = ‘Steve’

  11. with open(‘players.txt’, ‘a+’) as f:

  12. f.write(player)
    
  13. f.seek(0)
    
  14. # f.flush()  # -> no error, but also no output
    
  15. # f.begin()  # AttributeError: ...
    
  16. # f.close()  # In the next line: ValueError: ...
    
  17. data = f.read()
    
  18. print(data)
    
  19. """

  20. Peter

  21. Paul

  22. Mary

  23. Jane

  24. Steve

  25. """

Explanation:

seek(0) sets the file position back to zero (to the beginning of the file).

The flush() method only clears the internal buffer of the file,

but the file position would still be behind the last entry

and read() would start reading from there and find nothing.

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

Domain

07 – I/O

Question 32Skipped

Q311 – Functions

Which of the following function definition does not return any value?

A function that returns a random integer from 1 to 100.

Explanation

This function definition explicitly returns a random integer from 1 to 100, so it does return a value. The function has a return statement that provides a specific output.

A function that converts an uppercase letter to lowercase.

Explanation

This function definition converts an uppercase letter to lowercase and returns the lowercase letter as the output. It explicitly returns a value, making it different from a function that does not return any value.

Correct answer

A function that prints integers from 1 to 100.

Explanation

This function definition prints integers from 1 to 100 but does not explicitly return any value. It performs an action (printing) without returning a specific value or result.

Overall explanation

Topics: def return

Try it yourself:

  1. A function that prints integers from 1 to 100:

  2. def f1():

  3. for i in range(1, 101):
    
  4.     print(i)
    
  5. print(f1()) # None

  6. Not to return a value means to return "None"

  7. A function that returns a random integer from 1 to 100:

  8. def f2():

  9. from random import randint
    
  10. return randint(1, 100)
    
  11. print(f2()) # e.g. 87

  12. It returns the random number.

  13. A function that converts an uppercase letter to lowercase:

  14. def f3(s):

  15. return s.lower()
    
  16. print(f3(‘X’)) # x

  17. This function would return the lower letter

Explanation:

The function f1() does not have the return keyword.

Therefore it would return None

Every function, that does not return anything, returns None

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

Domain

06 – Functions

Question 33Skipped

Q321 – Data Aggregates

What is the expected output of the following code?

  1. data = {‘a’: 1, ‘b’: 2, ‘c’: 3}
  2. print(data[‘a’, ‘b’])

[1,2]

Explanation

This choice is incorrect because the code is trying to access values from a dictionary using multiple keys (‘a’ and ‘b’) within a single set of square brackets, which is not valid syntax for dictionary access. The expected output would not be a list containing the values 1 and 2.

{'a':1,'b':2}

Explanation

This choice is incorrect because the code is trying to access values from a dictionary using multiple keys (‘a’ and ‘b’) within a single set of square brackets, which is not valid syntax for dictionary access. The expected output would not be a dictionary containing the key-value pairs ‘a’: 1 and ‘b’: 2.

(1,2)

Explanation

This choice is incorrect because the code is trying to access values from a dictionary using multiple keys (‘a’ and ‘b’) within a single set of square brackets, which is not valid syntax for dictionary access. The expected output would not be a tuple containing the values 1 and 2.

Correct answer

The code is erroneous.

Explanation

The code is erroneous because when accessing values from a dictionary in Python, you need to provide a single key within square brackets. In this case, the code is trying to access values using multiple keys (‘a’ and ‘b’) within a single set of square brackets, which is not valid syntax for dictionary access.

Overall explanation

Topics: dictionary indexing

Try it yourself:

  1. data = {‘x’: 1, ‘y’: 2, ‘z’: 3}

  2. print(data[‘x’, ‘y’]) # KeyError: (‘x’, ‘y’)

  3. print(data[‘x’], data[‘y’]) # 1 2

  4. data = {(‘x’, ‘y’): 1}

  5. print(data[‘x’, ‘y’]) # 1

Explanation:

You can have a tuple as key of a dictionary

but that is not given here.

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

Domain

04 – Data Aggregates

Question 34Skipped

Q301 – Operators

What is the expected output of the following code?

print(type(1 / 2))

<type 'number'>

Explanation

‘number’ is not a valid type in Python. The output of the code will be a specific data type, not a generic ‘number’ type.

<type 'tuple'>

Explanation

The output of the code is not a tuple. The division operation does not return a tuple type.

<type 'int'>

Explanation

The division of two integers in Python results in a floating-point number, not an integer. Therefore, the output of the code will not be ‘int’.

Correct answer

<type 'float'>

Explanation

The code snippet performs division between two integers, which results in a floating-point number. Therefore, the output of the code will be the type ‘float’.

<type 'double'>

Explanation

‘double’ is not a valid type in Python. Python uses ‘float’ to represent floating-point numbers, so the output of the code will be ‘float’.

Overall explanation

Topics: division operator type()

Try it yourself:

  1. print(type(1 / 2)) # <type ‘float’>
  2. print(1 / 2) # 0.5
  3. print(1 / 1) # 1.0

Explanation:

The division operator always returns a float.

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

Domain

03 – Operators

Question 35Skipped

Q316 – Data Aggregates

What is the expected output of the following code?

  1. fruits1 = [‘Apple’, ‘Pear’, ‘Banana’]

  2. fruits2 = fruits1

  3. fruits3 = fruits1[:]

  4. fruits2[0] = ‘Cherry’

  5. fruits3[1] = ‘Orange’

  6. res = 0

  7. for i in (fruits1, fruits2, fruits3):

  8. if i[0] == 'Cherry':
    
  9.     res += 1
    
  10. if i[1] == 'Orange':
    
  11.     res += 10
    
  12. print(res)

0

Explanation

The code modifies fruits2 and fruits3 but does not change the first element of fruits1 to ‘Cherry’ or the second element of fruits1 to ‘Orange’. Therefore, none of the conditions in the loop are met, and the ‘res’ variable remains 0, resulting in an output of 0.

11

Explanation

The code modifies fruits2 and fruits3, but only the first condition in the loop is met when checking fruits2 for ‘Cherry’. The second condition is not met for any list. Therefore, the ‘res’ variable is incremented by 1, resulting in an output of 1.

22

Explanation

The code modifies fruits2 and fruits3, and both conditions in the loop are met when checking fruits2 for ‘Cherry’ and fruits3 for ‘Orange’. The ‘res’ variable is incremented by 1 and 10, respectively, resulting in an output of 22.

Correct answer

12

Explanation

The code creates three lists, fruits1, fruits2, and fruits3, with the same initial values. Then, it modifies fruits2 and fruits3 by changing the first element of fruits2 to ‘Cherry’ and the second element of fruits3 to ‘Orange’. The loop checks each list for specific values and increments the ‘res’ variable accordingly. As a result, the expected output is 12.

Overall explanation

Topics: for copy vs. reference list slicing list indexing

Try it yourself:

  1. fruits1 = [‘Apple’, ‘Pear’, ‘Banana’]

  2. fruits2 = fruits1

  3. fruits3 = fruits1[:]

  4. fruits2[0] = ‘Cherry’

  5. fruits3[1] = ‘Orange’

  6. res = 0

  7. for i in (fruits1, fruits2, fruits3):

  8. if i[0] == 'Cherry':
    
  9.     res += 1
    
  10. if i[1] == 'Orange':
    
  11.     res += 10
    
  12. print(res) # 12

  13. print(id(fruits1)) # e.g. 140539383900864

  14. print(id(fruits2)) # e.g. 140539383900864 (the same number)

  15. print(id(fruits3)) # e.g. 140539652049216 (a different number)

Explanation:

list is a mutable data type.

Assigning it will create a reference.

Slicing it from start to end [:] will create a copy.

Therefore  Cherry goes in fruits2 and thereby also in fruits1

Orange only goes in fruits3

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

Domain

04 – Data Aggregates

Question 36Skipped

Q306 – Control Flow

What is the expected output of the following code?

  1. data = [1, {}, (2,), (), {3}, [4, 5]]

  2. points = 0

  3. for i in range(len(data)):

  4. if type(data[i]) == list:
    
  5.     points += 1
    
  6. elif type(data[i]) == tuple:
    
  7.     points += 10
    
  8. elif type(data[i]) == set:
    
  9.     points += 100
    
  10. elif type(data[i]) == dict:
    
  11.     points += 1000
    
  12. else:
    
  13.     points += 10000
    
  14. print(points)

Correct answer

11121

Explanation

The code iterates through the elements in the ‘data’ list and checks the type of each element. For lists, it adds 1 to ‘points’, for tuples it adds 10, for sets it adds 100, for dictionaries it adds 1000, and for any other type it adds 10000. In this case, the list contains a list, a dictionary, a tuple, a set, and an empty dictionary. Therefore, the expected output is 1 + 1000 + 10 + 10000 + 100 = 11121.

10212

Explanation

The code iterates through the elements in the ‘data’ list and checks the type of each element. For lists, it adds 1 to ‘points’, for tuples it adds 10, for sets it adds 100, for dictionaries it adds 1000, and for any other type it adds 10000. In this case, the list contains a list, a dictionary, a tuple, a set, and an empty dictionary. Therefore, the expected output is not 10212.

21102

Explanation

The code iterates through the elements in the ‘data’ list and checks the type of each element. For lists, it adds 1 to ‘points’, for tuples it adds 10, for sets it adds 100, for dictionaries it adds 1000, and for any other type it adds 10000. In this case, the list contains a list, a dictionary, a tuple, a set, and an empty dictionary. Therefore, the expected output is not 21102.

10221

Explanation

The code iterates through the elements in the ‘data’ list and checks the type of each element. For lists, it adds 1 to ‘points’, for tuples it adds 10, for sets it adds 100, for dictionaries it adds 1000, and for any other type it adds 10000. In this case, the list contains a list, a dictionary, a tuple, a set, and an empty dictionary. Therefore, the expected output is not 10221.

11112

Explanation

The code iterates through the elements in the ‘data’ list and checks the type of each element. For lists, it adds 1 to ‘points’, for tuples it adds 10, for sets it adds 100, for dictionaries it adds 1000, and for any other type it adds 10000. In this case, the list contains a list, a dictionary, a tuple, a set, and an empty dictionary. Therefore, the expected output is not 11112.

Overall explanation

Topics: if elif else type() list tuple set dict

equal to operator add and assign operator

Try it yourself:

  1. data = [1, {}, (2,), (), {3}, [4, 5]]

  2. points = 0

  3. for i in range(len(data)):

  4. if type(data[i]) == list:
    
  5.     points += 1
    
  6. elif type(data[i]) == tuple:
    
  7.     points += 10
    
  8. elif type(data[i]) == set:
    
  9.     points += 100
    
  10. elif type(data[i]) == dict:
    
  11.     points += 1000
    
  12. else:
    
  13.     points += 10000
    
  14. print(points) # 11121

Explanation:

Every element of data gets tested in the for loop.

There is one integer, which executes the else clause.

There is one dictionary: {}

There is one set: {3}

There are two tuples: (2,) and ()

There is one list: [4, 5]

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

Domain

05 – Control Flow

Question 37Skipped

Q329 – Data Aggregates

What is the expected output of the following code?

  1. w = [7, 3, 23, 42]
  2. x = w[1:]
  3. y = w[1:]
  4. z = w
  5. y[0] = 10
  6. z[1] = 20
  7. print(w)

[10, 20, 42]

Explanation

This choice suggests that only the elements at index 0 of ‘y’ and ‘z’ are modified. However, the element at index 1 of ‘z’ is also changed in the code. Therefore, the output is not [10, 20, 42].

Correct answer

[7, 20, 23, 42]

Explanation

The code creates a list ‘w’ with elements [7, 3, 23, 42]. Then, it assigns a slice of ‘w’ starting from index 1 to list ‘x’ and ‘y’. ‘z’ is assigned a reference to the original list ‘w’. When the elements at index 0 of ‘y’ and index 1 of ‘z’ are modified, it directly affects the original list ‘w’. Therefore, the expected output is [7, 20, 23, 42].

[7, 3, 23, 42]

Explanation

This choice does not consider the modifications made to the ‘y’ and ‘z’ lists. Since ‘y’ and ‘z’ are references to the original list ‘w’, any changes made to them will reflect in ‘w’. Therefore, the output is not [7, 3, 23, 42].

[10, 20, 23, 42]

Explanation

This choice considers the modification made to the element at index 0 of ‘y’ but overlooks the change made to the element at index 1 of ‘z’. Since ‘z’ is a reference to the original list ‘w’, the modification to ‘z’ affects ‘w’. Therefore, the output is not [10, 20, 23, 42].

Overall explanation

Topics: list slicing list indexing

Try it yourself:

  1. w = [7, 3, 23, 42]

  2. x = w[1:] # [3, 23, 42]

  3. y = w[1:] # [3, 23, 42]

  4. z = w # A reference

  5. print(z) # [7, 3, 23, 42]

  6. y[0] = 10 # Changes only y

  7. z[1] = 20 # Changes z and w

  8. print(w) # [7, 20, 23, 42]

  9. print(id(x)) # e.g. 140539383900864

  10. print(id(y)) # e.g. 140539383947456 (a different number)

  11. print(id(w)) # e.g. 140539652049216 (the same number than z)

  12. print(id(z)) # e.g. 140539652049216 (the same number than w)

Explanation:

The two list slicings create new lists.

Therefore the change of y does not effect w

The assigning of the list creates a reference to the same object

Therefore the change of z does also effect w

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

Domain

04 – Data Aggregates

Question 38Skipped

Q337 – Basics

You have the following file.

index.py:

  1. from sys import argv
  2. print(argv[0])

You run the file by executing the following command in the terminal.

python index.py Hello

What is the expected oputput?

Hello

Explanation

The output will not be "Hello" because argv[0] in the script refers to the name of the script itself, not the arguments passed to the script. Therefore, the output will be the name of the script, which is "index.py".

Correct answer

index.py

Explanation

The expected output is "index.py" because when the script is executed with the command "python index.py Hello", the value of argv[0] in the script refers to the name of the script itself, which is "index.py".

IndexError

Explanation

The output will not be "IndexError" as there is no indexing error in the script provided. The script simply prints the value of argv[0], which refers to the name of the script itself, so there should be no IndexError in this case.

ImportError

Explanation

The output will not be "ImportError" as there is no import error in the script provided. The script imports the argv module from sys correctly, so there should be no ImportError in this case.

Overall explanation

Topic: sys.argv

Try it yourself:

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

  2. code = ”’

  3. from sys import argv

  4. print(argv[0])

  5. ”’

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

  7. f.write(code)
    
  8. In Terminal:

  9. python index.py Hello

  10. """

  11. index.py

  12. """

Explanation:

You have to open the folder where you created the index.py file in a terminal

and run the file by executing python index.py Hello

The first index (the index 0) of the argv variable is always the filename.

If you want Hello to be the output, you have to write print(argv[1])

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

Domain

01 – Basics

Question 39Skipped

Q356 – Modules

The sys.stderr stream is normally associated with:

the keyboard

Explanation

The sys.stderr stream is not associated with the keyboard. It is used for error messages and output to the screen, while the keyboard is used for input. The sys.stdin stream is typically associated with reading input from the keyboard in Python.

the printer

Explanation

The sys.stderr stream is not normally associated with the printer. It is specifically used for error messages and outputting to the screen, rather than sending data to a physical printer device.

Correct answer

the screen

Explanation

The sys.stderr stream is typically used for error messages and is associated with the screen, where these error messages are displayed to the user. It is the standard error output stream in Python, separate from the standard output stream sys.stdout.

a null device

Explanation

The sys.stderr stream is not typically associated with a null device. A null device is used to discard data, whereas sys.stderr is specifically used for error messages to be displayed on the screen.

Overall explanation

Topic: sys.stderr

Try it yourself:

  1. import sys
  2. print(‘Error 1’, file=sys.stderr) # Error 1
  3. sys.stderr.write(‘Error 2’) # Error 2

Explanation:

Here are two different ways to send a string to the sys.stderr stream.

You will see both messages on the screen,

because the sys.stderr stream is normally associated with the screen.

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

Domain

09 – Modules

Question 40Skipped

Q346 – Control Flow

The ABC company is creating a program

that allows customers to log the number of miles biked.

The program will send messages based on how many miles the customer logs.

You create the following Python code.

  1. ???

  2. name = input('What is your name? ')
    
  3. return name
    
  4. ???

  5. calories = miles * calories_per_mile
    
  6. return calories
    
  7. distance = int(input(‘How many miles did you bike this week? ‘))

  8. burn_rate = 50

  9. biker = get_name()

  10. calories_burned = calc_calories(distance, burn_rate)

  11. print(biker + ‘, you burned about’, calories_burned, ‘calories.’)

What would you insert instead of ??? and ???

def calc_calories():

Explanation

The function calc_calories() is incorrectly defined without any parameters, but it needs to receive the miles biked and the burn rate to calculate the calories burned accurately. It should be defined with two parameters: miles and burn_rate.

def get_name(biker):

Explanation

The function get_name(biker) is incorrectly defined with a parameter biker, which is not needed for this specific functionality. The function should only prompt the user to input their name and return it.

Correct selection

def get_name():

Explanation

The function get_name() is correctly defined with no parameters as it only needs to return the name input by the user. This function will prompt the user to input their name and return it to the main program.

def calc_calories(miles, burn_rate):

Explanation

The function calc_calories(miles, burn_rate) is correctly defined with two parameters: miles and burn_rate. This function will calculate the calories burned based on the miles biked and the burn rate provided.

def get_name(name):

Explanation

The function get_name(name) is incorrectly defined with a parameter name, which is not needed for this specific functionality. The function should only prompt the user to input their name and return it.

Correct selection

def calc_calories(miles, calories_per_mile):

Explanation

The function calc_calories(miles, calories_per_mile) is correctly defined with two parameters: miles and calories_per_mile. This function will calculate the calories burned based on the miles biked and the burn rate provided.

Overall explanation

Topics: def input() multiplication operator int()

Try it yourself:

  1. def get_name():

  2. # name = input('What is your name? ')
    
  3. name = 'Peter'
    
  4. return name
    
  5. def calc_calories(miles, calories_per_mile):

  6. calories = miles * calories_per_mile
    
  7. return calories
    
  8. distance = int(input(‘How many miles did you bike this week? ‘))

  9. distance = int(‘740’)

  10. burn_rate = 50

  11. biker = get_name()

  12. calories_burned = calc_calories(distance, burn_rate)

  13. print(biker + ‘, you burned about’, calories_burned, ‘calories.’)

  14. Peter, you burned about 37000 calories.

Explanation:

biker = get_name() calls get_name() without any arguments

and therefore you can not have any parameters:

def get_name():

calories_burned = calc_calories(distance, burn_rate)

calls calc_calories() with two arguments

and therefore you need two parameters:

def calc_calories(miles, calories_per_mile):

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

Domain

05 – Control Flow

Question 41Skipped

Q307 – Control Flow

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

x = 16

while x > 0:

print('*')

x //= 2

The code will enter an infinite loop.

Explanation

The snippet initializes x to 16 and then enters a while loop that continues as long as x is greater than 0. Inside the loop, it prints a single asterisk ‘*’ and then divides x by 2 using the floor division operator ‘//’. Since x is divided by 2 in each iteration, it will eventually reach 0 after 5 iterations, causing the loop to terminate. The code will not enter an infinite loop.

three

Explanation

The snippet initializes x to 16 and then enters a while loop that continues as long as x is greater than 0. Inside the loop, it prints a single asterisk ‘*’ and then divides x by 2 using the floor division operator ‘//’. This process repeats until x becomes less than or equal to 0. The loop will run 5 times, printing 5 asterisks to the monitor, not 3.

Correct answer

five

Explanation

The snippet initializes x to 16 and then enters a while loop that continues as long as x is greater than 0. Inside the loop, it prints a single asterisk ‘*’ and then divides x by 2 using the floor division operator ‘//’. This process repeats until x becomes less than or equal to 0. The loop will run 5 times, printing 5 asterisks to the monitor.

one

Explanation

The snippet initializes x to 16 and then enters a while loop that continues as long as x is greater than 0. Inside the loop, it prints a single asterisk ‘*’ and then divides x by 2 using the floor division operator ‘//’. This process repeats until x becomes less than or equal to 0. The loop will run 5 times, printing 5 asterisks to the monitor, not just 1.

Overall explanation

Topics: while greater than operator print() with end parameter

floor-divide and assign operator

Try it yourself:

  1. x = 16
  2. while x > 0:
  3. print('1. x:', x)  # 16 -> 8 -> 4 -> 2 -> 1
    
  4. print('*')         # *****
    
  5. x //= 2            # x = x // 2
    
  6. print('2. x:', x)  # 8 -> 4 -> 2 -> 1 -> 0
    

Explanation:

After each printing a floor division by 2 takes place.

And 1 // 2 is 0 and that’s where the while loop ends.

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

Domain

05 – Control Flow

Question 42Skipped

Q338 – Basics

By which variable of the sys module can we access command line arguments?

args

Explanation

The variable ‘args’ is not a valid variable in the sys module to access command line arguments. The correct variable is ‘argv’, which holds the command line arguments as a list.

arguments

Explanation

The variable ‘arguments’ is not a valid variable in the sys module to access command line arguments. The correct variable is ‘argv’, which is specifically designed to hold and access the command line arguments.

argsv

Explanation

The variable ‘argsv’ is not a valid variable in the sys module to access command line arguments. The correct variable is ‘argv’, which is used to access the command line arguments passed to the Python script.

Correct answer

argv

Explanation

The correct variable to access command line arguments in the sys module is argv. This variable is a list that contains all the command line arguments passed to the Python script when it is executed.

Overall explanation

Topic: sys.argv

Try it yourself:

  1. import sys

  2. print(sys.argv[0]) # The first index is the name of the file

  3. Now execute the following to create the needed file:

  4. code = ”’

  5. import sys

  6. for a in sys.argv[1:]:

  7. print(a)
    
  8. ”’

  9. with open(‘argv.py’, ‘w’) as f:

  10. f.write(code)
    
  11. In Terminal:

  12. python argv.py Peter Paul Mary

  13. """

  14. Peter

  15. Paul

  16. Mary

  17. """

Explanation:

sys.argv[1:] slices everything except the first index with holds the filename.

You have to open the folder where you created the argv.py file in a terminal

and run the file by python argv.py Peter Paul Mary

The "v" in argv stands for vector.

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

Domain

01 – Basics

Question 43Skipped

Q318 – Control Flow

What is the expected output of the following code?

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

Correct answer

6

Explanation

The code iterates over each tuple in the ‘data’ list, unpacks the tuple as ‘j’ and ‘i’, and then sums the ‘i’ values. In this case, the sum of 1, 2, and 3 is 6, so the expected output is 6.

The code is erroneous.

Explanation

The code is correct and will produce an output. It sums the ‘i’ values in the tuples, so there is no error in the code. The expected output is 6.

9

Explanation

The sum of the ‘i’ values in the tuples (1, 2, and 3) is 6, not 9. Therefore, the expected output is 6, not 9.

3

Explanation

The code is not simply summing the ‘j’ values, but rather the ‘i’ values in each tuple. Therefore, the sum of 1, 2, and 3 is 6, not 3.

Overall explanation

Topics: sum() list tuple generator expression

Try it yourself:

  1. data = [(0, 1), (1, 2), (2, 3)]

  2. res = sum(i for j, i in data)

  3. print(res) # 6

  4. print(i for j, i in data) # <generator object at …>

  5. print([i for j, i in data]) # [1, 2, 3]

Explanation:

The for loop inside the generator expression

takes the second index from every tuple.

123 add up to 6

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

Domain

05 – Control Flow

Question 44Skipped

Q320 – Data Aggregates

What is the expected output of the following code?

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

(1, 1, 1)

Explanation

This choice is incorrect because the code will raise a TypeError due to trying to modify an element in a tuple, which is not allowed in Python. Therefore, the output will not be (1, 1, 1).

(2, 1, 1)

Explanation

This choice is incorrect because the code will raise a TypeError due to trying to modify an element in a tuple, which is not allowed in Python. Therefore, the output will not be (2, 1, 1).

Correct answer

The code is erroneous.

Explanation

The code is erroneous because tuples are immutable in Python, meaning their elements cannot be changed once they are assigned. Therefore, trying to modify the value at index 0 of the tuple ‘data’ will result in a TypeError.

(2, 2, 2)

Explanation

This choice is incorrect because the code will raise a TypeError due to trying to modify an element in a tuple, which is not allowed in Python. Therefore, the output will not be (2, 2, 2).

Overall explanation

Topics: tuple multiply operator tuple concatenation tuple indexing

Try it yourself:

  1. data = (1,) * 3
  2. data[0] = 2 # TypeError: …
  3. print(data)

Explanation:

A tuple is immutable. You can not change it.

Therefore you can not assign something to one of its indexes.

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

Domain

04 – Data Aggregates

Question 45Skipped

Q312 – Functions

What is the expected output of the following code?

  1. def test(x, y=23, z=10):

  2. print('x is', x, 'and y is', y, 'and z is', z)
    
  3. test(3, 7)

  4. test(42, z=24)

  5. test(z=60, x=100)

The code is erroneous.

Explanation

The code is not erroneous; it defines a function test with default parameter values and makes multiple function calls with different argument assignments.

Correct answer

  1. x is 3 and y is 7 and z is 10
  2. x is 42 and y is 23 and z is 24
  3. x is 100 and y is 23 and z is 60

Explanation

The first function call test(3, 7) assigns 3 to x and 7 to y, leaving z as the default value of 10. The second function call test(42, z=24) assigns 42 to x and overrides the default value of z with 24, leaving y as the default value of 23. The third function call test(z=60, x=100) assigns 100 to x and overrides the default value of z with 60, leaving y as the default value of 23.

  1. x is 3 and y is 7 and z is 10
  2. x is 23 and y is 42 and z is 24
  3. x is 60 and y is 100 and z is 23

Explanation

This choice does not match the expected output based on the function calls and parameter assignments provided in the code snippet.

  1. x is 7 and y is 3 and z is 10
  2. x is 42 and y is 23 and z is 24
  3. x is 23 and y is 100 and z is 60

Explanation

This choice does not match the expected output based on the function calls and parameter assignments provided in the code snippet.

Overall explanation

Topics: def arguments/parameters

Try it yourself:

  1. def test(x, y=23, z=10):

  2. print('x is', x, 'and y is', y, 'and z is', z)
    
  3. test(3, 7) # x is 3 and y is 7 and z is 10

  4. test(42, z=24) # x is 42 and y is 23 and z is 24

  5. test(z=60, x=100) # x is 100 and y is 23 and z is 60

Explanation:

First test(3, 7) is executed:

x gets the first argument 3

y gets the second argument 7

z stays 10

Second test(42, z=24) is executed:

x gets the first argument 42

z gets the second argument 24

y stays 23

Third test(z=60, x=100) is executed:

z gets the first argument 60

x gets the second argument 100

y stays 23

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

Domain

06 – Functions

Question 46Skipped

Q352 – Data Aggregates

An alternative name for a data structure called a stack is:

Correct answer

LIFO

Explanation

LIFO stands for Last In, First Out, which is a characteristic of a stack data structure. In a stack, the last element added is the first one to be removed, making LIFO an alternative name for a stack.

FOLO

Explanation

FOLO is not a commonly used term in computer science or data structures to describe a stack. The correct alternative name for a stack is LIFO, which stands for Last In, First Out.

FIFO

Explanation

FIFO stands for First In, First Out, which is a characteristic of a queue data structure, not a stack. In a queue, the first element added is the first one to be removed, so FIFO is not an alternative name for a stack.

Overall explanation

Topic: LIFO

Try it yourself:

  1. x = []
  2. x.append(1)
  3. x.append(2)
  4. x.append(3)
  5. print(x.pop()) # 3
  6. print(x.pop()) # 2
  7. print(x.pop()) # 1

Explanation:

LIFO stands for Last-In-First-Out.

Here you find a great explanation:

http://bluegalaxy.info/codewalk/2018/08/12/python-how-to-implement-a-lifo-stack/

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

Domain

04 – Data Aggregates

Question 47Skipped

Q302 – Operators

What value will be assigned to the x variable?

  1. z = 2
  2. y = 1
  3. x = y < z or z > y and y > z or z < y

0

Explanation

The expression does not evaluate to 0. The result of the expression is a boolean value (True or False) based on the conditions provided, not an integer value like 0.

Correct answer

True

Explanation

The expression evaluates to True because the logical OR operator (or) returns True if at least one of the conditions is True. In this case, the condition "y < z" is True, so the overall result is True.

False

Explanation

The expression does not evaluate to False. The logical OR operator (or) returns True if at least one of the conditions is True, and in this case, the condition "y < z" is True, so the overall result is True.

1

Explanation

The expression does not evaluate to 1. The result of the expression is a boolean value (True or False) based on the conditions provided, not an integer value like 1.

Overall explanation

Topics: operators relational operators operator precedence

Try it yourself:

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

Explanation:

The operators here are from three different groups.

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

The two comparison operators,

greater than operator and less than operator have the highest precedence.

Then the logical and operator has a higher precedence

than the logical or operators

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

Domain

03 – Operators

Question 48Skipped

Q344 – Functions

What is the expected output of the following code?

  1. def func(x):

  2. global y
    
  3. y = x * x
    
  4. return y
    
  5. func(2)

  6. print(y)

Correct answer

4

Explanation

The code defines a function ‘func’ that takes a parameter ‘x’, calculates the square of ‘x’, assigns it to the global variable ‘y’, and returns the result. When the function is called with ‘2’ as the argument, ‘y’ is assigned the value of ‘2 * 2’, which is 4. Therefore, the expected output when printing ‘y’ is 4.

The code is erroneous.

Explanation

The code is not erroneous. It defines a function ‘func’ that correctly calculates the square of the input parameter ‘x’ and assigns it to the global variable ‘y’. When the function is called with ‘2’ as the argument, ‘y’ is assigned the value of ‘2 * 2’, which is 4. Therefore, the code will output 4, not raise an error.

None

Explanation

The code defines a function ‘func’ that calculates the square of the input parameter ‘x’ and assigns it to the global variable ‘y’. When the function is called with ‘2’ as the argument, ‘y’ is assigned the value of ‘2 * 2’, which is 4. Therefore, the expected output when printing ‘y’ is not ‘None’.

2

Explanation

The code correctly calculates the square of the input parameter ‘x’ and assigns it to the global variable ‘y’. When the function is called with ‘2’ as the argument, ‘y’ is assigned the value of ‘2 * 2’, which is 4. Therefore, the expected output when printing ‘y’ is 4, not 2.

Overall explanation

Topics: def return global

Try it yourself:

  1. def func(x):

  2. global y
    
  3. y = x * x
    
  4. return y
    
  5. func(2)

  6. print(y) # 4

Explanation:

The global keyword can be used to read

and write a global variable inside of a function.

Once you write global y then y also exists in the outer scope.

You would not need the return here.

It is of no use, because the return value of func(2)

does not get processed any further.

But still you can print y because y is global

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

Domain

06 – Functions

Question 49Skipped

Q345 – Basics

What is the expected output of the following code?

  1. num = 2 + 3 * 5
  2. print(Num)

17.0

Explanation

The code will not output 17.0 because the variable num is assigned the value of 2 + 3 * 5, which equals 17. However, the code is trying to print Num (with a capital ‘N’), not num, so the output will not be in floating-point format.

Correct answer

The code is erroneous.

Explanation

The code is erroneous because the variable num is assigned the value of 2 + 3 * 5, which equals 17. However, when trying to print the variable Num (with a capital ‘N’), it will result in an error because Python is case-sensitive and Num is not defined.

25

Explanation

The code will not output 25 because the variable num is assigned the value of 2 + 3 * 5, which equals 17. However, the code is trying to print Num (with a capital ‘N’), not num, so the output will not be 25.

17

Explanation

The code will not output 17 because the variable num is assigned the value of 2 + 3 * 5, which equals 17. However, the code is trying to print Num (with a capital ‘N’), not num, so the output will not be 17.

Overall explanation

Topics: naming variables NameError

Try it yourself:

  1. num = 2 + 3 * 5
  2. print(Num) # NameError: name ‘Num’ is not defined
  3. print(num)

Explanation:

Python is case sensitive.

num is a different variable name than Num

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

Domain

01 – Basics

Question 50Skipped

Q351 – Error Handling

When an exception occurs, we say that it has been:

dropped

Explanation

The term "dropped" is not commonly used in the context of exception handling in Python. When an exception occurs, it is either "raised" or "caught" by an appropriate exception handler.

thrown

Explanation

While the term "thrown" is commonly used in other programming languages to describe the occurrence of an exception, in Python, we typically use the term "raised" to indicate that an exception has occurred.

Correct answer

raised

Explanation

In Python, when an exception occurs, we use the term "raised" to indicate that the exception has been detected and the corresponding error-handling mechanism is triggered.

Overall explanation

Topic: exceptions

Explanation:

"In Python, exceptions can be handled using a try statement.

The critical operation which can raise an exception

is placed inside the try clause.

The code that handles the exceptions is written in the except clause."

https://www.programiz.com/python-programming/exception-handling

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

Domain

08 – Error Handling

Question 51Skipped

Q322 – Data Aggregates

What is the expected output of the following code?

  1. data = (1, 2, 4, 8)
  2. data = data[1:-1]
  3. data = data[0]
  4. print(data)

(2,)

Explanation

The output format (2,) indicates a tuple with a single element. However, since the code explicitly accesses and prints the element at index 0, the output will be the integer 2 without parentheses.

The code is erroneous.

Explanation

The code is not erroneous as it correctly accesses and prints the element at index 0 of the sliced tuple ‘data’. The expected output is the integer 2.

(2)

Explanation

The parentheses around the number 2 indicate a tuple with a single element. However, since the code explicitly accesses and prints the element at index 0, the output will be the integer 2 without parentheses.

Correct answer

2

Explanation

The code first slices the tuple ‘data’ from index 1 to the second-to-last element, resulting in a new tuple (2, 4). Then, it further slices this tuple to extract the element at index 0, which is 2. Therefore, the expected output is 2.

Overall explanation

Topics: tuple slicing tuple indexing

Try it yourself:

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

Explanation:

The start of the slicing is index 1 (inclusive)

and the end is the last index -1 (exclusive).

That would be the numbers 24

The first one of those is the 2

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

Domain

04 – Data Aggregates

Question 52Skipped

Q342 – Error Handling

What is the expected output of the following code?

  1. def func():

  2. try:
    
  3.     print('Monday')
    
  4. finally:
    
  5.     print('Friday')
    
  6. func()

Friday

Explanation

This choice is incorrect because the code will print ‘Monday’ inside the try block, but it will always execute the finally block, printing ‘Friday’ afterwards. Therefore, the output will be ‘Monday’ followed by ‘Friday’.

Monday

Explanation

This choice is incorrect because the code will print ‘Monday’ inside the try block, but it will always execute the finally block, printing ‘Friday’ afterwards. Therefore, the output will be ‘Monday’ followed by ‘Friday’.

The code is erroneous.

Explanation

This choice is incorrect because the code is not erroneous. It will print ‘Monday’ inside the try block and ‘Friday’ in the finally block, as expected.

None of these.

Explanation

This choice is incorrect because the expected output of the code is ‘Monday’ followed by ‘Friday’.

Correct answer

Monday

Friday

Explanation

The code will first print ‘Monday’ inside the try block, and then it will always execute the finally block, printing ‘Friday’ afterwards. This is the expected output of the code.

Friday

Monday

Explanation

This choice is incorrect because the code will print ‘Monday’ inside the try block, but it will always execute the finally block, printing ‘Friday’ afterwards. Therefore, the output will be ‘Monday’ followed by ‘Friday’.

Overall explanation

Topic: try finally

Try it yourself:

  1. def func():

  2. try:
    
  3.     print('Monday')  # Monday
    
  4. finally:
    
  5.     print('Friday')  # Friday
    
  6. func()

Explanation:

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

The finally block always gets execute.

(There are similar questions Q127 and Q235.)

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

Domain

08 – Error Handling

Question 53Skipped

Q323 – Operators

The ** operator …

does not exist.

Explanation

The ** operator does exist in Python and it is used for exponentiation. It is a fundamental operator in Python and is widely used for mathematical calculations involving exponentiation.

performs floating-point multiplication.

Explanation

The ** operator does not perform floating-point multiplication in Python. It is solely used for exponentiation operations and does not have a functionality for performing floating-point multiplication.

performs duplicated multiplication.

Explanation

The ** operator does not perform duplicated multiplication in Python. It is specifically designed for exponentiation operations and does not have a functionality for duplicated multiplication.

Correct answer

performs exponentiation.

Explanation

The ** operator in Python is used for exponentiation, which means raising a number to the power of another number. It is a valid and commonly used operator for performing exponentiation operations in Python.

Overall explanation

Topic: exponentiation operator

Try it yourself:

print(2 ** 8)  # 256

Explanation:

That’s why the operator is called exponentiation operator

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

Domain

03 – Operators

Question 54Skipped

Q339 – Basics

The folder created by Python used to store pyc files is named:

__pyc__

Explanation

The folder named pyc is not the correct folder created by Python to store pyc files. The correct folder is pycache, which is specifically used for storing compiled bytecode files for modules.

__pycfiles__

Explanation

The folder named pycfiles is not the correct folder created by Python to store pyc files. The correct folder is pycache, which is specifically used for storing compiled bytecode files for modules.

__cache__

Explanation

The folder named cache is not the correct folder created by Python to store pyc files. The correct folder is pycache, which is specifically used for storing compiled bytecode files for modules.

Correct answer

__pycache__

Explanation

The folder named pycache is created by Python to store compiled bytecode files (.pyc) for modules. These files are used to improve the performance of Python programs by caching the compiled versions of modules for faster execution.

Overall explanation

Topic: __pycache__

Try it yourself:

  1. You have to run this to create the needed files:

  2. functions = ”’

  3. def func():

  4. print('Hello world')
    
  5. ”’

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

  7. f.write(functions)
    
  8. index = ”’

  9. import functions

  10. functions.func()

  11. ”’

  12. with open(‘index.py’, ‘w’) as f:

  13. f.write(index)
    

Explanation:

First please check, if the files index.py

and functions.py are created as expected.

Now run the file index.py and the folder __pycache__ should be created.

In case your Editor/IDE does not show the folder, check in your file system.

Inside the folder should be a file like functions.cpython-39.pyc

You can always delete the folder __pycache__

It will be created again the next time you run index.py

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

Domain

01 – Basics

Question 55Skipped

Q330 – I/O

Which of the following statements are true regarding the opening modes of a file?

Choose three.

When you open a file for reading,

if the file does not exist, the program will open an empty file.

Explanation

When opening a file for reading, if the file does not exist, the program will not open an empty file. Instead, an error will occur as the program cannot read from a non-existent file.

Correct selection

When you open a file for writing,

if the file does not exist, a new file is created.

Explanation

When opening a file for writing, if the file does not exist, a new file will be created because the program needs a file to write the data into.

Correct selection

When you open a file for writing,

if the file exists, the existing file is overwritten with the new file.

Explanation

When opening a file for writing, if the file exists, the existing file will be overwritten with the new file because the program is set to write new data into the file.

When you open a file for writing,

if the file does not exist, an error occurs.

Explanation

When opening a file for writing, if the file does not exist, an error will not occur. Instead, a new file will be created to write the data into.

Correct selection

When you open a file for reading,

if the file does not exist, an error occurs.

Explanation

When opening a file for reading, if the file does not exist, an error will occur because the program cannot read from a non-existent file.

Overall explanation

Topic: open() write() read() close()

Try it yourself:

  1. When you open a file for reading,

  2. if the file does not exist, an error occurs:

  3. open(‘anyfile.txt’, ‘r’) # FileNotFoundError: …

  4. When you open a file for writing,

  5. if the file does not exist, a new file is created:

  6. file = open(‘peoples.txt’, ‘w’)

  7. file.write(‘Peter, Paul, Mary’)

  8. file.close()

  9. file = open(‘peoples.txt’, ‘r’)

  10. print(file.read()) # Peter, Paul, Mary

  11. file.close()

  12. When you open a file for writing, if the file exists,

  13. the existing file is overwritten with the new file:

  14. file = open(‘peoples.txt’, ‘w’)

  15. file.close()

  16. file = open(‘peoples.txt’, ‘r’)

  17. print(file.read()) # no output, because the file is empty

  18. file.close()

Explanation:

If you want to read from a file, the file needs to exist.

If you want to write to a file, the file does not have to exist.

It will be created, if it does not exist.

If the file already exists, it will be overwritten.

If you do not want to loose the old content of the file,

you can use the append mode: open('myfile.txt', 'a')

That will append the new content at the end of the file.

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

Domain

07 – I/O

Question 56Skipped

Q315 – Data Types

You want to print each name of the list on a new line.

data = ['Peter', 'Paul', 'Mary', 'Jane']

Which statement will you use?

print(data.join('\n'))

Explanation

The join method is used to concatenate elements of a list with a specified separator. However, in this choice, the syntax is incorrect as join should be called on the separator ('\n') rather than on the list data.

Correct answer

print('\n'.join(data))

Explanation

The correct choice uses the join method to concatenate the elements of the list data with a newline character \n in between each element. This will print each name on a new line as desired.

print(data.concatenate('\n'))

Explanation

There is no concatenate method in Python for lists. This choice is incorrect as it does not provide a valid method to concatenate the elements of the list with a newline character.

print(data.join('%s\n', names))

Explanation

The join method should be called on the separator ('\n') to join the elements of the list data. Additionally, the names variable is not defined in the given context, making this choice incorrect.

Overall explanation

Topics: join() list string

Try it yourself:

  1. data = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]

  2. print(‘\n’.join(data))

  3. """

  4. Peter

  5. Paul

  6. Mary

  7. Jane

  8. """

  9. print(data.join(‘\n’)) # AttributeError: …

  10. print(data.concatenate(‘\n’)) # AttributeError: …

  11. print(data.join(‘%s\n’, names)) # AttributeError: …

Explanation:

join() is a string method.

The string is the separator

and the list (or any other iterable) is passed as argument.

The elements of the list will then be joined into a string

using the original string as separator.

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

Domain

02 – Data Types

Question 57Skipped

Q348 – Basics

You develop a Python application for your company.

You want to add notes to your code so other team members will understand it.

What should you do?

Place the notes before the first line of code separated by a blank line.

Explanation

Placing notes before the first line of code separated by a blank line in Python code does not create comments. Comments in Python should be placed on the same line after the # sign or in a multiline comment block using triple quotes. Comments before the first line of code are not considered valid comments in Python.

Correct answer

Place the notes after the # sign on any line.

Explanation

Placing notes after the # sign on any line in Python code is the correct way to add comments. The # sign indicates a single-line comment, and anything after it on the same line is considered a comment and will not be executed as code.

Place the notes inside of parentheses on any line.

Explanation

Placing notes inside parentheses on any line in Python code does not create comments. Instead, it will be treated as part of the code and may cause syntax errors or unexpected behavior.

Place the notes after the last line of code separated by a blank line.

Explanation

Placing notes after the last line of code separated by a blank line in Python code does not create comments. Comments in Python should be placed on the same line after the # sign or in a multiline comment block using triple quotes.

Overall explanation

Topics: comments

Try it yourself:

  1. Example of a whole line as a comment

  2. print(‘Hello’) # Example of the rest of a line as a comment

Explanation:

With the # sign you can comment out a whole line

or you can comment out the rest of a line.

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

Domain

01 – Basics