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

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

Back to result overview

Attempt 1

All domains

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

Collapse all questions

Question 1Skipped

Q541 – Modules

What is the expected output of the following code?

  1. import random
  2. print(random.seed(3))

The code is erroneous.

Explanation

The code is not erroneous; it is using the random.seed() function correctly. However, the output of print(random.seed(3)) will be None because the function does not return any value.

None of the above.

Explanation

The correct output of the code print(random.seed(3)) is None, so none of the above choices accurately reflect the expected output.

Correct answer

None

Explanation

The random.seed() function sets the seed for the random number generator, but it does not return any value. Therefore, the output of print(random.seed(3)) will be None.

3

Explanation

The random.seed() function does not return the seed value that was set. It simply initializes the random number generator with the provided seed value. Therefore, the output of print(random.seed(3)) will not be 3.

Overall explanation

Topics: import random.seed()

Try it yourself:

  1. import random
  2. print(random.seed(3)) # None

Explanation:

The seed() method is used to initialize the random number generator.

The random number generator needs a number (a seed value) to start with.

By default the random number generator uses the current system time.

You can use the seed() method to customize

the start number of the random number generator.

The seed() method has no defined return value and therefore it returns None

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

Domain

09 – Modules

Question 2Skipped

Q538 – Modules

Which of the following functions can be used to check if a file exists?

os.isFile()

Explanation

The os.isFile() function does not exist in the Python os module. This is an invalid function name and cannot be used to check if a file exists.

Correct answer

os.path.isfile()

Explanation

The os.path.isfile() function is used to check if a path is an existing regular file. It returns True if the path exists and is a file, otherwise it returns False. This function is specifically designed for checking the existence of files.

os.path.isFile()

Explanation

The os.path.isFile() function does not exist in the Python os module. This is an invalid function name and cannot be used to check if a file exists.

os.path.exists()

Explanation

The os.path.exists() function is used to check if a path exists, regardless of whether it is a file or directory. While it can be used to check the existence of files, it is not specifically designed to only check if a file exists like the os.path.isfile() function.

Overall explanation

Topic: os.path.isfile()

Try it yourself:

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

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

  3. f.write('Hello')
    
  4. import os

  5. if not os.path.isdir(‘folder’):

  6. os.mkdir('folder')
    
  7. import os

  8. print(os.path.isfile(‘data.txt’)) # True

  9. print(os.path.isfile(‘folder’)) # False

  10. print(os.path.exists(‘data.txt’)) # True

  11. print(os.path.exists(‘folder’)) # True

  12. print(os.isfile(‘data.txt’)) # AttributeError: …

  13. print(os.path.isFile(‘data.txt’)) # AttributeError: …

Explanation:

The isfile() method is the right choice here.

It checks whether the passed argument is a file.

The exists() method checks if something exists at a given path.

But that could still be a folder.

Python is case sensitive and therefore you have to

write isfile() with a lowercase f

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

Domain

09 – Modules

Question 3Skipped

Q554 – Error Handling

What is the expected output of the following code?

  1. try:
  2. print("5" / 0)
    
  3. except ArithmeticError:
  4. print("arith")
    
  5. except ZeroDivisionError:
  6. print("zero")
    
  7. except:
  8. print("some")
    

Correct answer

some

Explanation

The code will raise a ZeroDivisionError when trying to divide by zero, which will be caught by the except ZeroDivisionError block. Therefore, the output will be "zero".

0

Explanation

The code will raise a ZeroDivisionError when trying to divide by zero, which will be caught by the except ZeroDivisionError block. Therefore, the output will be "zero".

zero

Explanation

The code will raise a ZeroDivisionError when trying to divide by zero, which will be caught by the except ZeroDivisionError block. Therefore, the output will be "zero".

arith

Explanation

The code will raise a ZeroDivisionError when trying to divide by zero, which will be caught by the except ZeroDivisionError block. Therefore, the output will be "zero".

Overall explanation

Topics: try except ArithmeticError ZeroDivisionError TypeError

Try it yourself:

  1. try:

  2. print("5" / 0)
    
  3. except ArithmeticError:

  4. print("arith")
    
  5. except ZeroDivisionError:

  6. print("zero")
    
  7. except:

  8. print("some")  # some
    
  9. print("5" / 0) # TypeError

Explanation:

To use the division operator with a string raises a TypeError

and therefore the broad except: branch is executed.

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

Domain

08 – Error Handling

Question 4Skipped

Q513 – Operators

What is the expected output of the following code?

x = 2

y = 6

x += 2 ** 3

x //= y // 2 // 3

print(x)

0

Explanation

This choice is incorrect because it does not accurately reflect the calculations performed in the code. The correct output is 10, not 0.

Correct answer

10

Explanation

The code first calculates 2 raised to the power of 3, which is 8. Then, it adds 8 to the current value of x (2), resulting in x being 10. Next, it performs integer division by calculating y divided by 2 and then dividing the result by 3. Since y is 6, y // 2 // 3 equals 1. Finally, x is divided by 1, resulting in x being 10.

11

Explanation

This choice is incorrect because it does not accurately reflect the calculations performed in the code. The correct output is 10, not 11.

9

Explanation

This choice is incorrect because it does not accurately reflect the calculations performed in the code. The correct output is 10, not 9.

Overall explanation

Topics: exponentiation operator floor division operator

add and assign operator floor-divide and assign operator

operator precedence

Try it yourself:

  1. x = 2

  2. y = 6

  3. x += 2 ** 3

  4. x //= y // 2 // 3

  5. print(x) # 10

  6. x += 2 ** 3

  7. x = x + (2 ** 3)

  8. print(2 + (2 ** 3)) # 10

  9. print(2 + 8) # 10

  10. print(10) # 10

  11. x //= y // 2 // 3

  12. x = x // (y // 2 // 3)

  13. print(10 // (6 // 2 // 3)) # 10

  14. print(10 // ((6 // 2) // 3)) # 10

  15. print(10 // (3 // 3)) # 10

  16. print(10 // 1) # 10

  17. print(10) # 10

Explanation:

The exponentiation operator has a much higher precedence

than the add and assign operator

And the floor division operator has a higher precedence

than the floor-divide and assign operator

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

Domain

03 – Operators

Question 5Skipped

Q502 – Data Aggregates

What is the expected output of the following code?

  1. data1 = ‘1’, ‘2’
  2. data2 = (‘3’, ‘4’)
  3. print(data1 + data2)

Correct answer

('1', '2', '3', '4')

Explanation

The expected output of the code is a tuple that combines the elements of data1 and data2. Since data1 and data2 are tuples, the concatenation operation using the plus (+) operator will result in a new tuple with all the elements from both tuples, resulting in (‘1’, ‘2’, ‘3’, ‘4’).

['1', '2', '3', '4']

Explanation

This choice is incorrect because the output will not be a list. The original data1 and data2 variables are tuples, so the output will also be a tuple, not a list.

The code is erroneous.

Explanation

This choice is incorrect as the code is not erroneous. The code correctly combines two tuples using the plus operator to create a new tuple with all the elements from both original tuples.

(1, 2, 3, 4)

Explanation

This choice is incorrect because the output will not be a tuple with integer values (1, 2, 3, 4). The original data1 and data2 variables contain strings, so the output will be a tuple of strings, not integers.

Overall explanation

Topics: plus operator tuple concatenation

Try it yourself:

  1. data1 = ‘1’, ‘2’
  2. data2 = (‘3’, ‘4’)
  3. print(data1 + data2) # (‘1’, ‘2’, ‘3’, ‘4’)

Explanation:

You do not need the parentheses to create a tuple

The rest is normal tuple concatenation.

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

Domain

04 – Data Aggregates

Question 6Skipped

Q546 – Error Handling

The unnamed except block …

must be the first one.

Explanation

Placing the unnamed except block as the first one is not valid in Python. The interpreter will match exceptions in the order they are defined, so having the unnamed block first would prevent any named blocks from being able to catch specific exceptions before the generic one.

Correct answer

must be the last one.

Explanation

The unnamed except block must be the last one in the sequence of except blocks. This is because Python will match exceptions in the order they are defined, and having the unnamed block last ensures that it catches any exceptions that were not handled by the named blocks before it.

can be placed anywhere.

Explanation

The unnamed except block must be the last one in the sequence of except blocks. Placing it anywhere else may result in specific exceptions not being caught by the named blocks before it, leading to unexpected behavior in error handling.

cannot be used if any named block has been used.

Explanation

The unnamed except block can still be used even if named blocks have been defined. However, it must be placed as the last except block in the sequence to ensure that it catches any exceptions that were not handled by the named blocks.

Overall explanation

Topic: except SyntaxError

Try it yourself:

  1. try:

  2. # user_input = input('Please enter a number!')
    
  3. user_input = 'one'  # Just for convenience
    
  4. # user_input = 1
    
  5. num = 100 / int(user_input)
    
  6. except ValueError:

  7. print('You need to use digits!')
    
  8. except:

  9. print('Error')
    
  10. else:

  11. print('Result:', num)
    
  12. """

  13. try:

  14. # user_input = input('Please enter a number!')
    
  15. user_input = 'one'  # Just for convenience
    
  16. num = 100 / int(user_input)
    
  17. except: # SyntaxError: default ‘except:’ must be last

  18. print('Error')
    
  19. except ValueError:

  20. print('You need to use digits!')
    
  21. else:

  22. print('Result:', num)
    
  23. """

Explanation:

The unnamed except block always needs to be

the last one of the except blocks,

otherwise you will receive a SyntaxError

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

Domain

08 – Error Handling

Question 7Skipped

Q556 – Modules

What is the expected result of the following code?

  1. from datetime import timedelta

  2. delta = timedelta(weeks=1, days=7, hours=11)

  3. print(delta * 2)

7 days, 22:00:00

Explanation

This choice is incorrect because the expected result of the code is not 7 days and 22 hours. The timedelta object created in the code has a duration of 1 week, 7 days, and 11 hours, and when multiplied by 2, it results in 28 days and 22 hours, not 7 days and 22 hours.

Correct answer

28 days, 22:00:00

Explanation

The code imports the timedelta class from the datetime module and creates a timedelta object with a duration of 1 week, 7 days, and 11 hours. When this timedelta object is multiplied by 2, the result is 28 days and 22 hours, as timedelta objects support multiplication by integers to create a new timedelta object with the specified duration.

The code will raise an exception.

Explanation

This choice is incorrect because the code will not raise an exception. The code imports the timedelta class correctly and performs valid operations on timedelta objects, resulting in a timedelta object with a duration of 28 days and 22 hours when multiplied by 2.

2 weeks, 14 days, 22 hours

Explanation

This choice is incorrect because the expected result of the code is not 2 weeks, 14 days, and 22 hours. The timedelta object created in the code has a duration of 1 week, 7 days, and 11 hours, and when multiplied by 2, it results in 28 days and 22 hours, not 2 weeks, 14 days, and 22 hours.

Overall explanation

Topics: datetime timedelta

Try it yourself:

  1. from datetime import timedelta
  2. delta = timedelta(weeks=1, days=7, hours=11)
  3. print(delta * 2) # 28 days, 22:00:00

Explanation:

When you print a timedelta object

you always get the output with days and hours.

It is formatted like that.

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

Domain

09 – Modules

Question 8Skipped

Q537 – Operators

What is the expected output of the following code?

  1. x, y, z = 3, 2, 1
  2. z, y, x = x, y, z
  3. print(x, y, z)

2 1 3

Explanation

This choice is incorrect because the values of x, y, and z are swapped in the code. Therefore, the output will not be 2 1 3.

1 2 2

Explanation

This choice is incorrect because the values of x, y, and z are swapped in the code. Therefore, the output will not be 1 2 2.

3 2 1

Explanation

This choice is incorrect because the values of x, y, and z are swapped in the code. Therefore, the output will not be 3 2 1.

Correct answer

1 2 3

Explanation

The code assigns the values of x, y, and z to 3, 2, and 1 respectively. Then, it reassigns the values of z, y, and x to the values of x, y, and z respectively. Therefore, the output will be 1 2 3, as the values have been swapped.

Overall explanation

Topic: multiple assignments

Try it yourself:

  1. x, y, z = 3, 2, 1
  2. z, y, x = x, y, z # z, y, x = 3, 2, 1
  3. print(x, y, z) # 1, 2, 3

Explanation:

Multiple assignment

y stays the same.

x and z change their values.

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

Domain

03 – Operators

Question 9Skipped

Q551 – Error Handling

What is the expected output of the following code?

  1. class Ex(Exception):

  2. def __init__(self, msg):
    
  3.     Exception.__init__(self, msg + msg)
    
  4.     self.args = (msg,)
    
  5. try:

  6. raise Ex('ex')
    
  7. except Ex as e:

  8. print(e)
    
  9. except Exception as e:

  10. print(e)
    

Correct answer

ex

Explanation

The code raises a custom exception Ex with the message ‘ex’. In the Ex class, the __init__ method initializes the exception with the message concatenated with itself. When the exception is caught as Ex and printed, it will output the original message ‘ex’.

The code is erroneous.

Explanation

The code is not erroneous. It defines a custom exception Ex, raises it with the message ‘ex’, and catches it to print the message. The code structure and exception handling are valid, so there is no error in the code.

An empty line.

Explanation

The code does not result in an empty line. It raises a custom exception Ex with the message ‘ex’ and catches it as Ex or Exception to print the message. Therefore, the output will not be an empty line.

exex

Explanation

The code raises a custom exception Ex with the message ‘ex’. In the Ex class, the __init__ method initializes the exception with the message concatenated with itself. However, when the exception is caught as Ex and printed, it will output the message ‘ex’ concatenated with itself, resulting in ‘exex’.

Overall explanation

Topics: try except raise Exception

class __init__() self

Try it yourself:

  1. class Ex(Exception):

  2. def __init__(self, msg):
    
  3.     Exception.__init__(self, msg + msg)
    
  4.     self.args = (msg,)
    
  5. try:

  6. raise Ex('ex')
    
  7. except Ex as e:

  8. print(e)           # ex
    
  9. except Exception as e:

  10. print(e)
    

Explanation:

Without the line:

self.args = (msg,)

the solution would be: exex

The __init__() method of the parent class Exception gets called with

msg + msg which is 'exex'

But the args variable of the object itself gets assigned (msg,)

which is the tuple ('ex',)

and that gets printed, when the object itself is printed.

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

Domain

08 – Error Handling

Question 10Skipped

Q503 – Data Aggregates

What is the expected output of the following code?

  1. data = ((1, 2),) * 7
  2. print(len(data[3:8]))

5

Explanation

The code correctly slices the tuple data from index 3 to index 8. However, since the slice does not include the element at index 8, the length of the slice is 4, not 5.

Correct answer

4

Explanation

The code creates a tuple data by repeating the tuple (1, 2) seven times. When slicing data[3:8], it selects elements from index 3 up to, but not including, index 8. Since indexing starts at 0, this slice includes elements at indices 3, 4, 5, and 6, resulting in a length of 4.

6

Explanation

The code slices the tuple data from index 3 to index 8, but the slice does not include the element at index 8. Therefore, the length of the slice is 4, not 6.

The code is erroneous.

Explanation

The code is not erroneous. It correctly creates a tuple data and slices it to find the length of a specific range of elements. The expected output is 4, as the slice includes elements at indices 3, 4, 5, and 6.

Overall explanation

Topics: multiply operator tuple concatenation tuple slicing len()

Try it yourself:

  1. data = ((1, 2),) * 7

  2. print(len(data[3:8])) # 4

  3. print(data)

  4. ((1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2), (1, 2))

  5. print(len(data[3:100])) # 4

Explanation:

There is only going to be seven elements.

Therefore 6 is going to be the highest index.

And so the slicing ends up with the indexes 345 ,6

which are four elements.

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

Domain

04 – Data Aggregates

Question 11Skipped

Q519 – Functions

What is the expected output of the following code?

  1. x = 42

  2. def func():

  3. global x
    
  4. print('1. x:', x)
    
  5. x = 23
    
  6. print('2. x:', x)
    
  7. func()

  8. print(‘3. x:’, x)

    1. x: 42
    1. x: 23
    1. x: 42

Explanation

This choice is incorrect because the value of x is updated to 23 within the func() function using the global keyword. Therefore, the output will not be 42 for the third print statement outside the function.

None of the above.

Explanation

This choice is incorrect as the code provided will produce an output, and it is not the case that none of the above choices accurately represent the expected output of the code.

    1. x: 42
    1. x: 42
    1. x: 42

Explanation

This choice is incorrect because the value of x is updated to 23 within the func() function using the global keyword. Therefore, the output will not be 42 for the second print statement inside the function or the third print statement outside the function.

Correct answer

    1. x: 42
    1. x: 23
    1. x: 23

Explanation

The code defines a global variable x with a value of 42. Inside the func() function, the global keyword is used to modify the global variable x. The first print statement inside func() prints the value of x before the assignment, which is 42. Then, x is reassigned to 23, and the second print statement inside func() prints the updated value of x, which is 23. Finally, outside the func() function, the last print statement prints the current value of x, which is still 23.

Overall explanation

Topics: def global scope

Try it yourself:

  1. x = 42

  2. def func():

  3. global x
    
  4. print('1. x:', x)
    
  5. x = 23
    
  6. print('2. x:', x)
    
  7. func()

  8. print(‘3. x:’, x)

  9. """

    1. x: 42
    1. x: 23
    1. x: 23
  10. """

Explanation:

The variable x existed in the outer scope before the function call.

The global keyword turns the variable x into a global variable.

From now on it exists in the outer scope and in the function scope.

Therefore the change inside the function effect x in the outer scope.

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

Domain

06 – Functions

Question 12Skipped

Q557 – Operators

What is the expected output of the following code?

print(2 ** 3 ** 2 ** 1)

64

Explanation

This choice is incorrect because the calculation does not result in 64. The correct calculation involves multiple exponentiation operations, leading to a different output.

Correct answer

512

Explanation

The code uses the exponentiation operator (**) in a chain of operations. The order of operations for exponentiation is from right to left. Therefore, the calculation starts with 2 ** 1, which equals 2. Then, 3 ** 2 is calculated, resulting in 9. Finally, 2 ** 9 is calculated, resulting in 512 as the output.

16.0

Explanation

This choice is incorrect because the output is not a floating-point number. The calculation involves only integers and results in an integer output.

16

Explanation

This choice is incorrect because the calculation does not result in 16. The correct calculation involves multiple exponentiation operations, leading to a different output.

The code is erroneous.

Explanation

This choice is incorrect because the code is not erroneous. It performs a series of exponentiation operations, and the output can be determined through correct evaluation of the operators.

128.0

Explanation

This choice is incorrect because the output is not 128. The correct calculation involves multiple exponentiation operations, resulting in a different output.

Overall explanation

Topics: exponentiation operator associativity of operators

Try it yourself:

  1. print(2 ** 3 ** 2 ** 1) # 512
  2. print(2 ** 3 ** (2 ** 1)) # 512
  3. print(2 ** 3 ** 2) # 512
  4. print(2 ** (3 ** 2)) # 512
  5. print(2 ** 9) # 512
  6. print(512) # 512

Explanation:

This question is about associativity of operators

Most operators have the associativity from left to right.

That means if you have two operators that are the same

or of the same group the left one is executed first.

The exponentiation operator has an associativity from right to left

therefore the right one is executed first.

Just picture the expression on a piece of paper with your handwriting

where you write each exponent a little bit higher than its base.

Naturally you have to start at the top to resolve the expression.

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

Domain

03 – Operators

Question 13Skipped

Q514 – Operators

What is the expected output of the following code?

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

  2. alphas = [‘p’, ‘p’, ‘m’, ‘j’]

  3. print(nums is alphas)

  4. print(nums == alphas)

  5. nums = alphas

  6. print(nums is alphas)

  7. print(nums == alphas)

  8. False

  9. True

  10. True

  11. True

Explanation

The ‘is’ operator in Python checks if two variables refer to the same object in memory. Since ‘nums’ and ‘alphas’ are two different lists, the ‘is’ operator will return False. The ‘==’ operator, on the other hand, checks if the values of the two lists are the same, which is not the case here, so it will return False. After assigning ‘alphas’ to ‘nums’, both variables point to the same list object in memory, so ‘nums is alphas’ will return True. Since both variables now refer to the same list object, ‘nums == alphas’ will also return True.

Correct answer

  1. False
  2. False
  3. True
  4. True

Explanation

The ‘is’ operator in Python checks if two variables refer to the same object in memory. Since ‘nums’ and ‘alphas’ are two different lists, the ‘is’ operator will return False. The ‘==’ operator, on the other hand, checks if the values of the two lists are the same, which is not the case here, so it will also return False. After assigning ‘alphas’ to ‘nums’, both variables point to the same list object in memory, so ‘nums is alphas’ will return True. Since both variables now refer to the same list object, ‘nums == alphas’ will also return True.

  1. False
  2. True
  3. False
  4. True

Explanation

The ‘is’ operator in Python checks if two variables refer to the same object in memory. Since ‘nums’ and ‘alphas’ are two different lists, the ‘is’ operator will return False. The ‘==’ operator, on the other hand, checks if the values of the two lists are the same, which is not the case here, so it will return True. After assigning ‘alphas’ to ‘nums’, both variables point to the same list object in memory, so ‘nums is alphas’ will return True. Since the values of the lists are the same, ‘nums == alphas’ will return True.

  1. True
  2. False
  3. True
  4. False

Explanation

The ‘is’ operator in Python checks if two variables refer to the same object in memory. Since ‘nums’ and ‘alphas’ are two different lists, the ‘is’ operator will return False. The ‘==’ operator, on the other hand, checks if the values of the two lists are the same, which is not the case here, so it will return False. After assigning ‘alphas’ to ‘nums’, both variables point to the same list object in memory, so ‘nums is alphas’ will return True. However, since the values of the lists are not the same, ‘nums == alphas’ will return False.

Overall explanation

Topics: list identity operators equal to operator

Try it yourself:

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

  2. alphas = [‘p’, ‘p’, ‘m’, ‘j’]

  3. print(nums is alphas) # False

  4. print(nums == alphas) # False

  5. print(id(nums)) # e.g. 140539383947452

  6. print(id(alphas)) # e.g. 140539383900864 (a different number)

  7. nums = alphas

  8. print(nums is alphas) # True

  9. print(nums == alphas) # True

  10. print(nums) # [‘p’, ‘p’, ‘m’, ‘j’]

  11. print(alphas) # [‘p’, ‘p’, ‘m’, ‘j’]

  12. print(id(nums)) # e.g. 140539652049216

  13. print(id(alphas)) # e.g. 140539652049216 (the same number)

Explanation:

list is a mutable data type.

The second list is a different object.

Therefore the two lists do not have the same identity and different values.

Then alphas gets assigned to nums

That creates a reference to the same object.

From now on they have the same values and the same identity.

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

Domain

03 – Operators

Question 14Skipped

Q517 – Control Flow

Consider the following code.

  1. nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  2. x = 0
  3. while x < 10: # Line 3
  4. print(nums(x))   # Line 4
    
  5. if nums[x] = 7:  # Line 5
    
  6.     break        # Line 6
    
  7. else:            # Line 7
    
  8.     x += 1       # Line 8
    

You want to print the numbers 1 to 7 to the monitor.

But the code does not work.

What do you have to change?

Choose two.

x = x + 1         # Line 8

Explanation

The statement x += 1 is correct for incrementing the value of x by 1 in each iteration of the loop. This statement ensures that x is updated to move to the next element in the list nums, allowing the loop to progress correctly.

Correct selection

if nums[x] == 7:  # Line 5

Explanation

In Python, the equality comparison operator is ==, not =. Using == in the if statement will correctly compare the value at index x in the nums list to 7, allowing the break statement to execute when the condition is met.

while (x < 10):   # Line 3

Explanation

The while loop condition x < 10 is already correct and does not need to be changed. This condition ensures that the loop continues as long as x is less than 10, which is necessary for iterating through the list nums.

Correct selection

print(nums[x])    # Line 4

Explanation

The correct way to access elements in a list in Python is by using square brackets [], not parentheses (). Therefore, changing nums(x) to nums[x] will correctly access the elements in the list nums.

Overall explanation

Topics: while break if else list equal to operator

Try it yourself:

  1. nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  2. x = 0
  3. while x < 10: # Line 3
  4. print(nums[x])    # Line 4
    
  5. if nums[x] == 7:  # Line 5
    
  6.     break         # Line 6
    
  7. else:             # Line 7
    
  8.     x += 1        # Line 8
    

Explanation:

Line 3 and Line 8 work just fine.

Line 4 needs brackets for the list indexing.

Line 5 needs the equal to operator

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

Domain

05 – Control Flow

Question 15Skipped

Q544 – Error Handling

What is the expected output of the following code?

  1. def func():

  2. try:
    
  3.     return 1
    
  4. finally:
    
  5.     return 2
    
  6. res = func()

  7. print(res)

Correct answer

2

Explanation

The code will output 2 because the finally block will always execute, regardless of whether an exception is raised or not. In this case, the return 2 statement in the finally block will override the return 1 statement in the try block.

1

Explanation

The code will not output 1 because the return 1 statement in the try block is overridden by the return 2 statement in the finally block. The finally block always executes, so the return 2 statement takes precedence.

The code is erroneous.

Explanation

The code is not erroneous; it will execute without any syntax errors. However, the output will be 2, not 1, due to the behavior of the finally block overriding the try block return statement.

None of the above.

Explanation

None of the above is the expected output because the code will output 2, not 1. The finally block always executes, and the return statement within it takes precedence over the return statement in the try block.

Overall explanation

Topics: try finally def

Try it yourself:

  1. def func():

  2. try:
    
  3.     return 1
    
  4. finally:
    
  5.     return 2
    
  6. res = func()

  7. print(res) # 2

  8. For comparison:

  9. def func2():

  10. try:
    
  11.     print(1)  # 1
    
  12. finally:
    
  13.     print(2)  # 2
    
  14. func2()

Explanation:

This question is a little tricky.

The return in the finally block will indeed be the one, that is executed.

For example with print() it is different.

The one in the try block will be executed before the one in the finally block.

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

Domain

08 – Error Handling

Question 16Skipped

Q510 – Operators

What is the expected output of the following code?

  1. x = 1
  2. print(++++x)

Correct answer

1

Explanation

The expression "++++x" can be interpreted as "++ + x", where the first two plus signs are the increment operator, and the third plus sign is the unary plus operator. The increment operator does not work in Python, so the expression simplifies to "+ + x", which is equivalent to "1" when x is 1.

3

Explanation

The expression "++++x" should be broken down as "++ + x" in Python. Since the increment operator "++" is not valid in Python, the expression simplifies to "+ + x", resulting in the output of 1 when x is 1, not 3.

2

Explanation

In Python, the increment operator "++" is not supported. Therefore, the expression "++++x" should be interpreted as "+ + + x", which is equivalent to "1" when x is 1. The output will be 1, not 2.

4

Explanation

The expression "++++x" should be understood as "++ + x" in Python. Since the increment operator "++" is not a valid syntax in Python, the expression simplifies to "+ + x", which evaluates to 1 when x is 1. Therefore, the expected output is 1, not 4.

Overall explanation

Topic: operators

Try it yourself:

  1. x = 1

  2. print(++++x) # 1

  3. print(+1) # 1

  4. print(++1) # 1

  5. print(+++1) # 1

  6. print(++++1) # 1

  7. print(-1) # -1

  8. print(–1) # 1

  9. print(—1) # -1

  10. print(—-1) # 1

Explanation:

First of all there is no increment operator ++ in Python.

You can add as many plus signs as you like, the number stays positive.

By the way, the minus sign works differently.

Two times minus is plus.

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

Domain

03 – Operators

Question 17Skipped

Q552 – Error Handling

Select the true statements.

Choose two.

You cannot define new exceptions as subclasses

derived from predefined exceptions.

Explanation

In Python, you can define new exceptions as subclasses derived from predefined exceptions. This allows you to create custom exceptions that inherit behavior and attributes from existing exception classes, providing more specific error handling capabilities in your code.

The finally branch of the try statement

may be executed if special conditions are met.

Explanation

The finally branch of the try statement is always executed, regardless of any special conditions. It is meant to be a block of code that is guaranteed to run, providing a way to clean up resources or perform final actions before exiting the try block.

Correct selection

The finally branch of the try statement is always executed.

Explanation

The finally branch of the try statement is always executed, regardless of whether an exception is raised or not. It is typically used to perform cleanup actions, such as closing files or releasing resources, ensuring that the code block in the finally section is executed no matter what.

Correct selection

The args property is a tuple designed to gather all

arguments passed to the class constructor.

Explanation

The args property is indeed a tuple that is designed to gather all arguments passed to the class constructor. It is commonly used in custom exception classes to store information about the exception.

Overall explanation

Topics: try finally args

Try it yourself:

  1. try:

  2. raise Exception('Hello', 'World')
    
  3. except Exception as err:

  4. print(err.args)  # ('Hello', 'World')
    
  5. def f(x):

  6. try:
    
  7.     res = 10 // x
    
  8. except ZeroDivisionError:
    
  9.     print('You can not divide by zero!', end='')
    
  10. else:
    
  11.     print('The result is', str(res) + '!', end='')
    
  12. finally:
    
  13.     print(' Always finally!')
    
  14. f(0) # You can not divide by zero! Always finally!

  15. f(2) # The result is 5! Always finally!

Explanation:

Yes, the args property is a tuple designed to gather all

arguments passed to the class constructor.

And absolutely, the finally branch of the try statement is always executed.

And you most definitely can define new exceptions

as subclasses derived from predefined exceptions:

https://www.programiz.com/python-programming/user-defined-exception

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

Domain

08 – Error Handling

Question 18Skipped

Q509 – Data Types

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

  1. x = int(input())
  2. y = int(input())
  3. print(x + y)

Correct answer

6

Explanation

The code takes two integer inputs from the user, adds them together, and then prints the result. If the user enters 2 and 4, the sum of these two numbers is 6, so the expected output is 6.

2

Explanation

This choice is incorrect because it only represents one of the input values (2) and does not consider the addition operation that follows. The code adds the two input values together, so the output will be the sum of 2 and 4, which is 6.

4

Explanation

This choice is incorrect because it only represents one of the input values (4) and does not consider the addition operation that follows. The code adds the two input values together, so the output will be the sum of 2 and 4, which is 6.

24

Explanation

This choice is incorrect because it represents the concatenation of the two input values (2 and 4) as a single string, resulting in the output of 24. However, the code performs addition on the input values, not string concatenation, so the expected output is the sum of 2 and 4, which is 6.

Overall explanation

Topics: input() int() addition operator

Try it yourself:

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

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

  3. x, y = int(‘2’), int(‘4’) # Just for convenience

  4. print(x + y) # 6

  5. print(int(‘2’) + int(‘4’)) # 6

  6. print(2 + 4) # 6

Explanation:

input() return a string but the int() function casts them to an integer

And then the two integers get added to each other.

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

Domain

02 – Data Types

Question 19Skipped

Q555 – Basics

ASCII is:

a character name

Explanation

ASCII is not a character name, but rather a character encoding standard that assigns numerical values to characters for communication and processing in computers. It is used to represent text and control characters in various systems.

a predefined Python variable name

Explanation

ASCII is not a predefined Python variable name. It is a character encoding standard that assigns numerical values to characters for communication and processing in computers. It is used to represent text and control characters in various systems.

a standard Python module name

Explanation

ASCII is not a standard Python module name. It is a character encoding standard that predates Python and is used to represent text and control characters in computer systems.

Correct answer

short for American Standard Code for Information Interchange

Explanation

ASCII stands for American Standard Code for Information Interchange, which is a character encoding standard used in computers and communication equipment to represent text and control characters. It is not a character name, Python module name, or predefined Python variable name.

Overall explanation

Topic: ASCII

Explanation:

Read about it here:

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

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

Domain

01 – Basics

Question 20Skipped

Q547 – I/O

If x is a file opened in read mode, what will the following line do?

data = x.read(1)

Correct answer

Read 1 character from the file.

Explanation

This choice is correct because the read(1) method in Python reads and returns the specified number of characters from the file, in this case, 1 character.

Read 1 line from the file.

Explanation

This choice is incorrect because the read(1) method reads a specified number of characters, not lines, from the file.

Read 1 buffer from the file.

Explanation

This choice is incorrect because the read(1) method reads a specified number of characters, not buffers, from the file.

Read 1 kilobyte from the file.

Explanation

This choice is incorrect because the read(1) method reads a specified number of characters, not kilobytes, from the file.

Overall explanation

Topic: read()

Try it yourself:

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

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

  3. f.write('Peter, Paul, Mary')
    
  4. x = open(‘index.txt’, ‘r’)

  5. print(x.read(1)) # P

Explanation:

file.read([size])

The read() method has one optional parameter.

If it is given, that number of characters are read.

If it is not given, the whole file is read.

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

Domain

07 – I/O

Question 21Skipped

Q506 – Data Aggregates

What is the expected output of the following code?

  1. data = {‘Peter’: 30, ‘Paul’: 31}
  2. print(list(data.keys()))

['Peter': 30, 'Paul': 31]

Explanation

The syntax ['Peter': 30, 'Paul': 31] is incorrect for defining key-value pairs in Python. In dictionaries, key-value pairs are separated by commas and enclosed in curly braces. Additionally, the keys in a list should be strings, not key-value pairs. Therefore, this syntax is not valid for the expected output.

('Peter': 30, 'Paul': 31)

Explanation

The syntax ('Peter': 30, 'Paul': 31) is incorrect for defining key-value pairs in Python. In dictionaries, key-value pairs are separated by commas and enclosed in curly braces. Therefore, this syntax is not valid for the expected output.

Correct answer

['Peter', 'Paul']

Explanation

The code uses the keys() method on the dictionary data to retrieve a list of all the keys in the dictionary. Therefore, the expected output is a list containing the keys ‘Peter’ and ‘Paul’.

('Peter', 'Paul')

Explanation

The syntax ('Peter', 'Paul') represents a tuple, not a list. In this code, the keys() method returns a list, so the output should be enclosed in square brackets, not parentheses.

Overall explanation

Topics: dictionary list() keys()

Try it yourself:

  1. data = {‘Peter’: 30, ‘Paul’: 31}
  2. print(list(data.keys())) # [‘Peter’, ‘Paul’]
  3. print(data.keys()) # dict_keys([‘Peter’, ‘Paul’])

Explanation:

The key() method returns the keys() in a dict_keys object.

list() turns that into a list

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

Domain

04 – Data Aggregates

Question 22Skipped

Q526 – Data Aggregates

Which of the following sentences is true?

  1. str1 = ‘Peter’
  2. str2 = str1[:]

Correct answer

str1 and str2 are different names of the same string.

Explanation

This choice is correct because when the slice operator [:] is used without specifying any start or end index, it creates a shallow copy of the original string. Therefore, both str1 and str2 refer to the same string object in memory.

str2 is longer than str1

Explanation

This choice is incorrect because str1 and str2 are not different strings but rather different names referring to the same string ‘Peter’. Therefore, there is no difference in length between str1 and str2.

str1 and str2 are different (but equal) strings.

Explanation

This choice is incorrect because although str1 and str2 are different variables, they are referencing the same string object. Therefore, they are not different (but equal) strings; they are the same string.

str1 is longer than str2

Explanation

This choice is incorrect because both str1 and str2 are referring to the same string ‘Peter’. There is no difference in length between str1 and str2 as they are essentially the same string.

Overall explanation

Topics: string slicing

Try it yourself:

  1. str1 = ‘Peter’

  2. str2 = str1[:]

  3. str2 = str1 # The same thing

  4. print(id(str1)) # e.g. 140539652049216

  5. print(id(str2)) # e.g. 140539652049216 (the same number than str1)

  6. print(str1 is str2) # True

  7. print(str1 == str2) # True

Explanation:

Copying with [:] only works with mutable data types like a list

string is an immutable data type.

Whether you slice the whole thing or just assign it,

you always end up with a reference to the same object.

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

Domain

04 – Data Aggregates

Question 23Skipped

Q532 – Data Types

Consider the following Python code:

  1. name = ‘Peter’
  2. age = 23
  3. flag = True

What are the types of the variables nameage and flag?

Correct answer

str, int, bool

Explanation

The variable ‘name’ is assigned a string value ‘Peter’, so its type is ‘str’. The variable ‘age’ is assigned an integer value 23, so its type is ‘int’. The variable ‘flag’ is assigned a boolean value True, so its type is ‘bool’.

int, bool, char

Explanation

The variable ‘name’ is assigned a string value ‘Peter’, so its type is ‘str’. The variable ‘age’ is assigned an integer value 23, so its type is ‘int’. The variable ‘flag’ is assigned a boolean value True, so its type is ‘bool’.

float, bool, str

Explanation

The variable ‘name’ is assigned a string value ‘Peter’, so its type is ‘str’. The variable ‘age’ is assigned an integer value 23, so its type is ‘int’. The variable ‘flag’ is assigned a boolean value True, so its type is ‘bool’.

str, int, int

Explanation

The variable ‘name’ is assigned a string value ‘Peter’, so its type is ‘str’. The variable ‘age’ is assigned an integer value 23, so its type is ‘int’. The variable ‘flag’ is assigned a boolean value True, so its type is ‘bool’.

Overall explanation

Topics: integer float boolean string

Try it yourself:

  1. print(type(‘Peter’)) # <class ‘str’>
  2. print(type(23)) # <class ‘int’>
  3. print(type(True)) # <class ‘bool’>

Explanation:

Nothing complicated is going on here.

'Peter' is a string.

23 is an integer.

True is a boolean.

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

Domain

02 – Data Types

Question 24Skipped

Q550 – Control Flow

You are developing a Python application

for an online product distribution company.

You need the program to iterate through a list of products

and escape when a target product ID is found.

  1. productIdList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  2. index = 0

  3. ??? index < 10:

  4. print(productIdList[index])
    
  5. if productIdList[index] == 6:
    
  6.     ???
    
  7. else:
    
  8.     index += 1
    

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

  1. for
  2. break

Explanation

Using a ‘for’ loop in this context would not be suitable as the program needs to iterate through the list until a specific condition is met. The ‘break’ statement is necessary to exit the loop when the target product ID is found.

Correct answer

  1. while
  2. break

Explanation

Using a ‘while’ loop allows the program to iterate through the list of product IDs until a specific condition is met. The ‘break’ statement is used to exit the loop when the target product ID is found.

  1. while
  2. for

Explanation

Combining a ‘while’ loop with a ‘for’ loop in this scenario would not make sense as it would result in unnecessary complexity. The ‘break’ statement is needed to exit the loop when the target product ID is found.

  1. break
  2. while

Explanation

Using only the ‘break’ statement without a loop structure would not allow the program to iterate through the list of product IDs. A loop, such as a ‘while’ loop, is necessary for iteration, and the ‘break’ statement is used to exit the loop when the target product ID is found.

  1. for
  2. while

Explanation

Combining a ‘for’ loop with a ‘while’ loop in this context would not be the most efficient approach. The ‘break’ statement is crucial for exiting the loop when the target product ID is found.

  1. if
  2. break

Explanation

Using an ‘if’ statement here would not be appropriate as it does not provide a mechanism for iteration through the list. The ‘break’ statement is essential for exiting the loop when the target product ID is found.

Overall explanation

Topics: list while for break if else

equal to operator

Try it yourself:

  1. productIdList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

  2. index = 0

  3. while index < 10:

  4. print(productIdList[index])   # 0 1 2 3 4 5 6
    
  5. if productIdList[index] == 6:
    
  6.     break
    
  7. else:
    
  8.     index += 1
    

Explanation:

The while loop is the loop, that works with a condition.

The break keyword ends a loop.

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

Domain

05 – Control Flow

Question 25Skipped

Q549 – Control Flow

You are coding a math utility by using Python.

You are writing a function to compute roots.

The function must meet the following requirements:

If a is non-negative, return a ** (1 / b)

If a is negative and even, return 'Result is an imaginary number'

If a is negaitve and odd, return -(-a) ** (1 / b)

Which of the following functions meets the requirements?

  1. def safe_root(a, b):
  2. if a >= 0:
    
  3.     answer = -(-a) ** (1 / b)
    
  4. elif a % 2 == 0:
    
  5.     answer = 'Result is an imaginary number'
    
  6. else:
    
  7.     answer = a ** (1 / b)
    
  8. return answer
    

Explanation

This function does not meet the requirements as it incorrectly calculates the result for the case where ‘a’ is non-negative. It should return ‘a ** (1 / b)’ instead of ‘-(-a) ** (1 / b)’ when ‘a’ is non-negative.

Correct answer

  1. def safe_root(a, b):
  2. if a >= 0:
    
  3.     answer = a ** (1 / b)
    
  4. elif a % 2 == 0:
    
  5.     answer = 'Result is an imaginary number'
    
  6. else:
    
  7.     answer = -(-a) ** (1 / b)
    
  8. return answer
    

Explanation

This function correctly follows the requirements by first checking if ‘a’ is non-negative and returning the result of ‘a ** (1 / b)’. Then, it checks if ‘a’ is negative and even, returning ‘Result is an imaginary number’. Lastly, if ‘a’ is negative and odd, it returns ‘-(-a) ** (1 / b)’ as specified.

  1. def safe_root(a, b):
  2. if a % 2 == 0:
    
  3.     answer = -(-a) ** (1 / b)
    
  4. elif a >= 0:
    
  5.     answer = 'Result is an imaginary number'
    
  6. else:
    
  7.     answer = a ** (1 / b)
    
  8. return answer
    

Explanation

This function does not meet the requirements as it incorrectly checks if ‘a’ is even before checking if it is non-negative. Additionally, the calculation for the case where ‘a’ is negative and odd is incorrect, as it should return ‘-(-a) ** (1 / b)’ instead of ‘a ** (1 / b)’.

  1. def safe_root(a, b):
  2. if a % 2 == 0:
    
  3.     answer = a ** (1 / b)
    
  4. elif a >= 0:
    
  5.     answer = 'Result is an imaginary number'
    
  6. else:
    
  7.     answer = -(-a) ** (1 / b)
    
  8. return answer
    

Explanation

This function does not meet the requirements as it incorrectly checks if ‘a’ is even before checking if it is non-negative. This order of conditions results in the function not returning the correct output for the given requirements.

Overall explanation

Topics: if elif else def

modulus operator equal to operator

division operator exponentiation operator

Try it yourself:

  1. def safe_root(a, b):

  2. if a >= 0:
    
  3.     answer = a ** (1 / b)
    
  4. elif a % 2 == 0:
    
  5.     answer = 'Result is an imaginary number'
    
  6. else:
    
  7.     answer = -(-a) ** (1 / b)
    
  8. return answer
    
  9. print(safe_root(9, 2)) # 3.0

  10. print(safe_root(-9, 2)) # -3.0

  11. print(safe_root(-16, 2)) # Result is an imaginary number

Explanation:

All the non-negative numbers will enter the if clause: a >= 0

Only negative numbers will remain.

The even numbers will enter the elif clause: a % 2 == 0

Only negative and odd numbers will remain.

Those will enter the else clause.

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

Domain

05 – Control Flow

Question 26Skipped

Q501 – Functions

A built‑in function is a function which …

is hidden from programmers.

Explanation

Built-in functions are not hidden from programmers; they are actually designed to be easily accessible and used by developers. They are openly documented and widely known within the Python community.

has been placed within your code by another programmer.

Explanation

Built-in functions are not functions that have been placed within your code by another programmer. They are predefined functions that are part of the Python language itself and are accessible to all Python developers.

Correct answer

comes with Python, and is an integral part of Python.

Explanation

Built-in functions are predefined functions that are included in Python by default. They are readily available for use without the need for any additional imports or installations, making them an integral part of the Python programming language.

has to be imported before use.

Explanation

Unlike regular functions or modules that need to be imported before use, built-in functions do not require any import statements. They are automatically available in the Python environment without the need for explicit imports.

Overall explanation

Topic: built‑in function

Try it yourself:

  1. To print out the built-in functions:

  2. for i in dir(builtins):

  3. if i[0] != '_' and i[0].islower():
    
  4.     print(i, end=', ')
    
  5. """

  6. abs, all, any, ascii, bin, bool, breakpoint, bytearray, bytes,

  7. callable, chr, classmethod, compile, complex, copyright,

  8. credits, delattr, dict, dir, divmod, enumerate, eval, exec,

  9. exit, filter, float, format, frozenset, getattr, globals,

  10. hasattr, hash, help, hex, id, input, int, isinstance,

  11. issubclass, iter, len, license, list, locals, map, max,

  12. memoryview, min, next, object, oct, open, ord, pow, print,

  13. property, quit, range, repr, reversed, round, set, setattr,

  14. slice, sorted, staticmethod, str, sum, super, tuple, type,

  15. vars, zip

  16. """

Explanation:

The build-in functions do not have to be imported,

they are not hidden from programmers

and not place in your code by another programmer.

The built-in functions come with Python as an integral part of the language.

Just look at the list above.

You will recognize most of them.

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

Domain

06 – Functions

Question 27Skipped

Q504 – Data Aggregates

What is the expected output of the following code?

  1. data = {‘name’: ‘Peter’, ‘age’: 30}
  2. person = data.copy()
  3. print(id(data) == id(person))

0

Explanation

This choice is incorrect as the expected output of the code is a comparison of memory addresses using id(), not a numerical value like 0.

True

Explanation

This choice is incorrect because the comparison of memory addresses using id() will result in False, as ‘data’ and ‘person’ are two separate objects in memory.

Correct answer

False

Explanation

The code creates a dictionary ‘data’ with key-value pairs and then creates a copy of ‘data’ called ‘person’. Since ‘person’ is a copy of ‘data’, they are two separate objects in memory, so the comparison of their memory addresses using id() will result in False.

1

Explanation

This choice is incorrect as the expected output of the code is a comparison of memory addresses using id(), not a numerical value like 1.

Overall explanation

Topics: dictionary copy() id() equal to operator

Try it yourself:

  1. data = {‘name’: ‘Peter’, ‘age’: 30}

  2. person = data.copy()

  3. print(id(data) == id(person)) # False

  4. person = data

  5. print(id(data) == id(person)) # True

Explanation:

The copy() method creates a copy of the dictionary

If you just assign the dictionary a reference is created.

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

Domain

04 – Data Aggregates

Question 28Skipped

Q539 – Functions

Which of the following enclose the input parameters or arguments of a function?

Quotation marks

Explanation

Quotation marks are not used to enclose the input parameters or arguments of a function in Python. Quotation marks are used for defining strings in Python.

Brackets

Explanation

Brackets are not used to enclose the input parameters or arguments of a function in Python. Brackets are typically used for indexing and slicing operations on lists, tuples, and dictionaries.

Curly braces

Explanation

Curly braces are not used to enclose the input parameters or arguments of a function in Python. Curly braces are used for defining dictionaries and sets in Python.

Correct answer

Parentheses

Explanation

Parentheses are used to enclose the input parameters or arguments of a function in Python. This is the standard syntax for defining and calling functions in Python.

Overall explanation

Topics: def arguments parameters

Try it yourself:

  1. Parantheses enclose the input parameters of a function definition:

  2. def func(para1, para2):

  3. return para1 + para2
    
  4. Parantheses enclose the arguments of a function call:

  5. print(func(3, 4)) # 7

  6. Example for the uses of brackets:

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

  8. Example for the uses of curly braces:

  9. print({1, 2, 3}) # {1, 2, 3}

  10. Example for the uses of quotation marks:

  11. Double quotes:

  12. print("Hello") # Hello

  13. Single quotes:

  14. print(‘Hello’) # Hello

Explanation:

Parantheses enclose the input parameters or arguments of a function.

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

Domain

06 – Functions

Question 29Skipped

Q542 – Basics

What is the expected output of the following code?

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

1

Explanation

The code will not run successfully due to the syntax error caused by the backslash at the end of the string. Therefore, the output of the code cannot be determined, and it will not return a length value of 1.

2

Explanation

The code contains a syntax error with the backslash at the end of the string. As a result, the code will not execute properly, and the length of the string cannot be calculated as 2.

3

Explanation

The code provided is not valid in Python syntax due to the backslash at the end of the string. Therefore, the length of the string cannot be determined as 3.

Correct answer

The code is erroneous.

Explanation

The code is erroneous because the backslash character "\" is used to escape characters in Python. In this case, the backslash at the end of the string is not followed by another character to escape, which results in a syntax error.

Overall explanation

Topics: escaping len()

Try it yourself:

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

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

Explanation:

The backslash is the character to escape another character.

If you write '\' the backslash escapes

the ending single quote to a normal character.

It takes its syntactical meaning and the single quote becomes a normal character

and it looses its ability to end the string and therefore we get the syntax error.

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

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

If you write '\\\' you again have the same problem

than with one single backslash.

The first backslash escapes the second one,

but the third backslash escape the ending single quote,

the string does not get closed and you get a syntax error.

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

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

Domain

01 – Basics

Question 30Skipped

Q520 – Functions

What is the expected output of the following code?

  1. def func(x):

  2. if x % 2 == 0:
    
  3.     return 1
    
  4. else:
    
  5.     return
    
  6. print(func(func(2)) + 1)

None

Explanation

The code will output None because the return statement in the else block of the func function does not specify a value to return when x is odd. This will result in a None value being returned, which is then added to 1 in the print statement.

Correct answer

The code is erroneous.

Explanation

The code is erroneous because the return statement in the else block of the func function does not specify a value to return when x is odd. This will result in a None value being returned, leading to an error when trying to add 1 to it in the print statement.

2

Explanation

The code will not output 2 because the return statement in the else block of the func function does not specify a value to return when x is odd. This will result in a None value being returned, which cannot be added to 1 in the print statement.

1

Explanation

The code will not output 1 because the return statement in the else block of the func function does not specify a value to return when x is odd. This will result in a None value being returned, which cannot be added to 1 in the print statement.

Overall explanation

Topics: def return None if else

modulus operator addition operator

Try it yourself:

  1. def func(x):

  2. if x % 2 == 0:
    
  3.     return 1
    
  4. else:
    
  5.     return
    
  6. print(func(func(2)) + 1) # TypeError: …

Explanation:

The condition x % 2 == 0 tests for even numbers.

The first function call func(2) passes an even number

and the return value will be 1

The second function call will therefore pass an odd number func(1)

The return with no value will return None

And you can not calculate with None

(There is a similar question Q620.)

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

Domain

06 – Functions

Question 31Skipped

Q543 – Basics

You have the following file.

  1. index.py:
  2. from sys import argv
  3. print(argv[1] + argv[2])

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

python index.py 42 3

What is the expected oputput?

45

Explanation

The output ’45’ would be incorrect because the script concatenates the command line arguments ’42’ and ‘3’, not adds them together.

126

Explanation

The output ‘126’ would be incorrect because the script concatenates the command line arguments ’42’ and ‘3’, not multiplies them.

424242

Explanation

The output ‘424242’ would be incorrect because the script concatenates the command line arguments ’42’ and ‘3’ without repeating them.

Correct answer

423

Explanation

The expected output is ‘423’ because the script takes the command line arguments ’42’ and ‘3’ and concatenates them together, resulting in ‘423’.

The code is erroneous.

Explanation

The code is not erroneous; it simply concatenates the command line arguments ’42’ and ‘3’ and prints the result, which is ‘423’.

Overall explanation

Topic: sys.argv plus operator string concatenation

Try it yourself:

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

  2. code = ”’

  3. from sys import argv

  4. print(argv[1] + argv[2])

  5. ”’

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

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

  9. python index.py 42 3

Explanation:

The indexes 1 and 2 are the right ones

(Remember the filename always is in index 0).

All the values in argv are going to be strings.

Therefore string concatenation will take place

and the result will be the string '423'

To test it you have to open the folder

where you created the index.py file in a terminal

and run the file by executing python index.py 42 3

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

Domain

01 – Basics

Question 32Skipped

Q525 – Control Flow

The following is a program to validate customer numbers.

  1. customer_number = input(‘Enter the employee number (dd-ddd-dddd): ‘)
  2. parts = customer_number.split(‘-‘)
  3. valid = False
  4. if len(parts) == 3:
  5. if len(parts[0]) == 2 and len(parts[1]) == 3 and len(parts[2]) == 4:
  6. if parts[0].isdigit() and parts[1].isdigit() and parts[2].isdigit():
    
  7.   valid = True
    
  8. print(valid)

The number may only contain numbers and dashes.

The number must have the right format (dd-ddd-dddd).

What is true about this programm?

There will be no error but there will be an unwanted result.

Explanation

The program will not produce an unwanted result if the input meets the specified criteria. It will accurately determine the validity of the customer number based on the format and content requirements.

There will be a SyntaxError.

Explanation

There are no syntax errors in the program. It follows the correct Python syntax and structure for input handling, string manipulation, and conditional statements.

Correct answer

The program works properly.

Explanation

The program correctly validates customer numbers by checking if the input follows the format dd-ddd-dddd, contains only numbers and dashes, and has the correct lengths for each part. If all conditions are met, the program sets the valid variable to True and prints it.

There will be an AttributeError.

Explanation

There are no attribute errors in the program. It correctly uses the split() method to separate the input into parts based on dashes and accesses the length and digit properties of the parts.

Overall explanation

Topics: input() split() boolean len() if

equal to operator list isdigit()

Try it yourself:

  1. customer_number = input(‘Enter the employee number (dd-ddd-dddd): ‘)

  2. customer_number = ’12-345-6789′ # True

  3. customer_number = ‘12345-6789’ # False

  4. customer_number = ‘A2-345-6789’ # False

  5. customer_number = ‘112-345-6789’ # False

  6. parts = customer_number.split(‘-‘)

  7. valid = False

  8. if len(parts) == 3:

  9. if len(parts[0]) == 2 and len(parts[1]) == 3 and len(parts[2]) == 4:

  10. if parts[0].isdigit() and parts[1].isdigit() and parts[2].isdigit():
    
  11.   valid = True
    
  12. print(valid)

  13. You might have to scroll a little to the right to see everything

Explanation:

Everything works fine here.

The string with the number gets splitted into a list.

Then there are three conditions.

First if the list has three parts.

Second if all the parts have the right length.

Third if all the parts only contain digits.

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

Domain

05 – Control Flow

Question 33Skipped

Q530 – Basics

You create a function to calculate the power of a number by using Python.

You need to ensure that the function is documented with comments

You create the following code. Line numbers are included for reference only.

  1. 01 # The calc_power function calculates exponents
  2. 02 # x is the base
  3. 03 # y is the exponent
  4. 04 # The value of x raised to the y power is returned
  5. 05 def calc_power(x, y):
  6. 06 comment = "# Return the value"
  7. 07 return x ** y # raise x to the y power

Which of the following statements are true?

Choose two.

The pond sign (#) is optional for lines 02 and 03.

Explanation

The pound sign (#) is not optional for lines 02 and 03 in Python. It is used to indicate that the following text is a comment. Without the pound sign, Python will interpret the text as part of the code and may result in syntax errors.

The string in Line 06 will be interpreted as a comment.

Explanation

The string in Line 06 is not interpreted as a comment in Python. It is assigned to the variable ‘comment’ but is not used or referenced anywhere in the function. Python will not treat it as a comment and will not affect the execution of the function.

Correct selection

Line 07 contains an inline comment.

Explanation

Line 07 contains an inline comment that explains the purpose of the return statement. Inline comments are used to provide additional information about the code on the same line. In this case, it clarifies the operation being performed by the return statement.

Correct selection

Lines 01 through 04 will be ignored for syntax checking.

Explanation

Lines 01 through 04 are considered as comments and documentation strings (docstrings) in Python. They are not executable code and are meant for providing information about the function. Therefore, they will be ignored for syntax checking.

Overall explanation

Topics: def return (inline) comment exponentiation operator

Try it yourself:

  1. The calc_power function calculates exponents

  2. x is the base

  3. y is the exponent

  4. The value of x raised to the y power is returned

  5. def calc_power(x, y):

  6. comment = "# Return the value"
    
  7. # print(comment)  # '# Return the value'
    
  8. return x ** y   # raise x to the y power
    
  9. print(calc_power(2, 8)) # 256

Explanation:

This question is about how to use a comment right.

The first four lines are commented out and that needs to be that way.

Line 07 has an inline comment

and the comment inside of a string does not work as a comment

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

Domain

01 – Basics

Question 34Skipped

Q548 – I/O

Which of the following commands can be used to read the next line from a file?

read(n)

Explanation

The read(n) command is used to read a specified number of bytes from a file, not specifically the next line. It reads the file in a continuous stream, without distinguishing between lines.

readlines()

Explanation

The readlines() command is used to read all lines from a file and return them as a list of strings. It does not specifically read the next line from the file, but rather reads all lines at once.

Correct answer

readline()

Explanation

The readline() command is used to read the next line from a file. It reads the file line by line, allowing the user to process each line individually.

read()

Explanation

The read() command is used to read a specified number of bytes from a file, not specifically the next line. It reads the file in a continuous stream, without distinguishing between lines.

Overall explanation

Topics: read() readline() readlines()

Try it yourself:

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

  2. data = ”’Peter

  3. Paul

  4. Mary

  5. ”’

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

  7. f.write(data)
    
  8. file = open(‘data.txt’, ‘r’)

  9. print(file.readline()) # Peter

  10. print(file.readline()) # Paul

  11. print(file.readline()) # Mary

  12. print(‘———-‘)

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

  14. print(file.readline()) # Peter

  15. print(file.readlines()) # [‘Paul\n’, ‘Mary\n’]

  16. print(‘———-‘)

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

  18. print(file.readline()) # Peter

  19. print(file.read()) # Paul Mary

  20. print(‘———-‘)

  21. n = 7

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

  23. print(file.readline()) # Peter

  24. print(file.read(n)) # Paul Ma

Explanation:

The readline() method is exactly what you need here.

The read() method will read the rest of the file in one string.

The readlines() method will read the rest of the file and put every line in a list.

read(n) reads n characters from the file.

That could theoretically work, if you know the right number of characters,

but that is definitely not meant here.

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

Domain

07 – I/O

Question 35Skipped

Q535 – Control Flow

Consider the following code.

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

Which of the following code snippets will expand the code,

so that 100 will be printed to the monitor?

Choose two.

  1. for i in (‘Peter’, ‘Steve’, ‘Jane’):
  2. if i not in data:
    
  3.     res += 50
    
  4. print(res)

Explanation

This code snippet iterates over the elements in the tuple (‘Peter’, ‘Steve’, ‘Jane’). For each element, it checks if the element is not in the ‘data’ list. Since ‘Steve’ is not in the ‘data’ list, the ‘res’ variable will be incremented by 50. Finally, it prints the value of ‘res’, which will be 50 in this case.

Correct selection

  1. for i in (‘Peter’, ‘Steve’, ‘Jane’):
  2. if i in data:
    
  3.     res += 50
    
  4. print(res)

Explanation

This code snippet iterates over the elements in the tuple (‘Peter’, ‘Steve’, ‘Jane’). For each element, it checks if the element is in the ‘data’ list. Since ‘Peter’ and ‘Jane’ are in the ‘data’ list, the ‘res’ variable will be incremented by 50 for each of them. Finally, it prints the value of ‘res’, which will be 100 in this case.

  1. for i in (‘Peter’, ‘Steve’, ‘Jane’):
  2. if i in data:
    
  3.     res += 100
    
  4. print(res)

Explanation

This code snippet iterates over the elements in the tuple (‘Peter’, ‘Steve’, ‘Jane’). For each element, it checks if the element is in the ‘data’ list. Since ‘Peter’ and ‘Jane’ are in the ‘data’ list, the ‘res’ variable will be incremented by 100 for each of them. Finally, it prints the value of ‘res’, which will be 200 in this case.

Correct selection

  1. for i in (‘Peter’, ‘Steve’, ‘Jane’):
  2. if i not in data:
    
  3.     res += 100
    
  4. print(res)

Explanation

This code snippet iterates over the elements in the tuple (‘Peter’, ‘Steve’, ‘Jane’). For each element, it checks if the element is not in the ‘data’ list. Since ‘Steve’ is not in the ‘data’ list, the ‘res’ variable will be incremented by 100. Finally, it prints the value of ‘res’, which will be 100 in this case.

Overall explanation

Topics: list for if membership operator not

Try it yourself:

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

  2. res = 0

  3. for i in (‘Peter’, ‘Steve’, ‘Jane’):

  4. if i not in data:
    
  5.     res += 100
    
  6. print(res) # 100

  7. ———————-

  8. res = 0

  9. for i in (‘Peter’, ‘Steve’, ‘Jane’):

  10. if i in data:
    
  11.     res += 50
    
  12. print(res) # 100

  13. ———————-

  14. res = 0

  15. for i in (‘Peter’, ‘Steve’, ‘Jane’):

  16. if i in data:
    
  17.     res += 100
    
  18. print(res) # 200

  19. ———————-

  20. res = 0

  21. for i in (‘Peter’, ‘Steve’, ‘Jane’):

  22. if i not in data:
    
  23.     res += 50
    
  24. print(res) # 50

Explanation:

Only Steve is not in data

Therefore we need the += 100 there.

Peter and Jane are both in data

Therefore we need the += 50 there.

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

Domain

05 – Control Flow

Question 36Skipped

Q534 – Operators

What is the data type of xyz after executing the following snippet?

  1. x = 23 + 42
  2. y = ’23’ + ’42’
  3. z = ’23’ * 7

x is int,

y and z are invalid declarations

Explanation

The expression 23 + 42 results in an integer value, so x is of type int. When concatenating two strings ’23’ and ’42’, the result is a new string ‘2342’, so y is of type str. Multiplying a string ’23’ by 7 is a valid operation in Python, resulting in ‘23232323232323’, so z is also of type str.

Correct answer

int, str, str

Explanation

The expression 23 + 42 results in an integer value, so x is of type int. When concatenating two strings ’23’ and ’42’, the result is a new string ‘2342’, so y is of type str. Multiplying a string ’23’ by 7 results in ‘23232323232323’, so z is also of type str.

int, str, int

Explanation

The expression 23 + 42 results in an integer value, so x is of type int. When concatenating two strings ’23’ and ’42’, the result is a new string ‘2342’, so y is of type str. However, multiplying a string ’23’ by 7 results in ‘23232323232323’, which is still a string, so z is also of type str, not int.

int, int, int

Explanation

The expression 23 + 42 results in an integer value, so x is of type int. When concatenating two strings ’23’ and ’42’, the result is a new string ‘2342’, so y is of type str. Multiplying a string ’23’ by 7 results in ‘23232323232323’, which is still a string, so z is also of type str, not int.

Overall explanation

Topics: addition operator plus operator string concatenation

multiply operator string concatenation

Try it yourself:

  1. print(type(23 + 42)) # <class ‘int’>
  2. print(type(’23’ + ’42’)) # <class ‘str’>
  3. print(type(’23’ * 7)) # <class ‘str’>
  4. print(23 + 42) # 65
  5. print(’23’ + ’42’) # 2342
  6. print(’23’ * 7) # 23232323232323

Explanation:

The first one is a normal addition.

The second one is a string concatenation by addition.

The third one is a string concatenation by multiplication.

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

Domain

03 – Operators

Question 37Skipped

Q540 – Modules

You need a list of seven numbers of random integer values

from  1 (inclusive) to  7 (inclusive).

Which of the following code snippets should you use?

  1. import random
  2. nums = random.randrange(1, 7)

Explanation

This code snippet imports the random module and attempts to generate a single random integer value between 1 and 7 using the randrange() function. It does not create a list of seven numbers as required in the question.

Correct answer

  1. import random
  2. nums = [random.randint(1, 7) for i in range(1, 8)]

Explanation

This code snippet correctly imports the random module and generates a list of seven random integer values between 1 and 7 (inclusive) using the randint() function within a list comprehension.

  1. import random
  2. nums = [random.randint(1, 8) for i in range(1, 8)]

Explanation

This code snippet imports the random module and generates a list of seven random integer values between 1 and 8 (inclusive) using the randint() function within a list comprehension. However, the range should be from 1 to 7 to meet the specified requirements.

  1. import random
  2. nums = random.randint(1, 7)

Explanation

This code snippet imports the random module and generates a single random integer value between 1 and 7 using the randint() function. It does not create a list of seven numbers as required in the question.

Overall explanation

Topics: import random.randint() random.randrange()

list comprehension

Try it yourself:

  1. import random
  2. print([random.randint(1, 7) for i in range(1, 8)])
  3. e.g. [6, 3, 7, 5, 1, 4, 2]

  4. print([random.randint(1, 8) for i in range(1, 8)])
  5. e.g. [6, 7, 3, 1, 8, 7, 8]

  6. print(random.randrange(1, 7)) # e.g. 6
  7. print(random.randint(1, 7)) # e.g. 7

Explanation:

You need a list comprehension here to get a whole list of numbers.

range(1, 8) works to get a list of seven elements,

because with range() the stop is exclusive.

That is different with randint()

With randint() the stop is inclusive.

That is why you need: randint(1, 7)

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

Domain

09 – Modules

Question 38Skipped

Q553 – I/O

The two basic, mutually exclusive, file open modes are named:

binary and ternary

Explanation

The choice binary and ternary is incorrect because ternary is not a file open mode in Python. The two basic, mutually exclusive file open modes in Python are binary and text. Ternary is not a standard file open mode in Python and is not used for reading or writing data in files.

text and image

Explanation

The choice text and image is incorrect because image is not a file open mode in Python. While text mode is used for reading and writing text data, image is not a standard file open mode. In Python, images are typically handled using specific libraries and modules designed for image processing, not as a file open mode.

Correct answer

binary and text

Explanation

The correct choice is binary and text because these are the two basic, mutually exclusive file open modes in Python. The binary mode is used for reading and writing binary data, while the text mode is used for reading and writing text data. These modes are essential for handling different types of data in files efficiently.

Overall explanation

Topic: open() and its modes

Try it yourself:

  1. First you have to run this to create the files:

  2. with open(‘alphabet.bin’, ‘wb’) as f:

  3. f.write(bytes([65, 66, 67]))
    
  4. with open(‘alphabet.txt’, ‘wt’) as f:

  5. f.write('ABC')
    
  6. with open(‘alphabet.bin’, ‘rb’) as f:

  7. print(f.read())  # b'ABC'
    
  8. with open(‘alphabet.txt’, ‘rt’) as f:

  9. print(f.read())  # ABC
    

Explanation:

You have to decide, whether you use binary or text mode:

https://www.w3schools.com/python/ref_func_open.asp

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

Domain

07 – I/O

Question 39Skipped

Q522 – Functions

What is the expected output of the following code?

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

  2. return x * y
    
  3. print(func(y=2))

The code is erroneous.

Explanation

This choice is incorrect because the code is not erroneous. The function func is defined correctly, and when called with y=2, it will return the correct output.

Correct answer

4

Explanation

The function func takes two parameters, x and y, with default values of 2 and 3, respectively. When calling the function func with y=2, it overrides the default value of y with 2. The function then returns the product of x and y, which is 2 * 2 = 4.

2

Explanation

This choice is incorrect because it does not consider the parameter y being passed as 2 when calling the function func. The function will return the product of the passed value of y (2) and the default value of x (2), resulting in 2 * 2 = 4.

6

Explanation

This choice is incorrect because it does not consider the parameter y being passed as 2 when calling the function func. The function will return the product of the passed value of y (2) and the default value of x (2), resulting in 2 * 2 = 4.

Overall explanation

Topics: def default parameter

Try it yourself:

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

  2. return x * y
    
  3. print(func(y=2)) # 4

Explanation:

This is an easy question.

It is good to be able to detect that.

There is not always a hidden complexity.

Click the right answer and move on.

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

Domain

06 – Functions

Question 40Skipped

Q529 – Control Flow

What is the expected output of the following code?

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

  2. count = 0

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

  4. if type(data[i]) == list:
    
  5.     count += 1
    
  6. print(count)

9

Explanation

This choice is incorrect because it does not consider the condition in the code that increments the ‘count’ variable only when the element is a list. It does not represent the total number of elements in the ‘data’ list.

The code is erroneous.

Explanation

This choice is incorrect as the code is not erroneous. It correctly counts the number of elements that are lists in the ‘data’ list and prints the count at the end.

6

Explanation

This choice is incorrect because the ‘count’ variable is only incremented when the element in the ‘data’ list is a list. It does not count the total number of elements in the ‘data’ list.

Correct answer

3

Explanation

The code iterates through the elements of the ‘data’ list and checks if each element is a list. If the element is a list, the ‘count’ variable is incremented by 1. In this case, there are 3 elements in the ‘data’ list that are lists, so the final output will be 3.

Overall explanation

Topics: list for range() len() if type() equal to operator

Try it yourself:

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

  2. count = 0

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

  4. if type(data[i]) == list:
    
  5.     count += 1
    
  6. print(count) # 3

Explanation:

The snippet checks every element of the list, if it itself is a list

and counts the occurrences.

There are three lists inside of the list data: [3, 4][5, 6] and [8, 9]

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

Domain

05 – Control Flow

Question 41Skipped

Q531 – I/O

The following line of code …

for line in open('data.txt', 'r'):

Correct answer

is valid as open returns an iterable object.

Explanation

This choice is correct because the open() function in Python returns a file object, which is an iterable object. Therefore, the code snippet is valid as it iterates over each line in the ‘data.txt’ file.

may be valid if line is a list.

Explanation

This choice is incorrect because the open() function returns a file object, not a list. Therefore, the code snippet is valid regardless of the data type of the variable ‘line’.

is invalid as open returns a non-iterable object.

Explanation

This choice is incorrect because the open() function in Python returns a file object, which is an iterable object. Therefore, the code snippet is valid and can iterate over each line in the ‘data.txt’ file.

is invalid as open returns nothing.

Explanation

This choice is incorrect because the open() function in Python returns a file object, not nothing. Therefore, the code snippet is valid as it iterates over the lines in the ‘data.txt’ file.

Overall explanation

Topics: open() for

Try it yourself:

  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. for line in open(‘data.txt’, ‘r’):

  9. print(line)
    
  10. """

  11. Peter

  12. Paul

  13. Mary

  14. """

  15. print(type(open(‘data.txt’, ‘r’))) # <class ‘_io.TextIOWrapper’>

  16. print(hasattr(open(‘data.txt’, ‘r’), ‘iter‘)) # True

Explanation:

The open() function returns an iterable object.

Therefore it can be iterated by the for loop.

Every iteration will return one line.

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

Domain

07 – I/O

Question 42Skipped

Q527 – Data Types

You want to write a programm that asks the user for a value.

For the rest of the programm you need a whole number,

even if the user enters a decimal value.

What would you have to write?

num = int('How many do you need?')

Explanation

This choice tries to convert the string ‘How many do you need?’ to an integer, which will result in an error. It does not handle user input or convert it to a whole number as required.

Correct answer

num = int(float(input('How many do you need?')))

Explanation

This choice first converts the user input to a float using the float() function, then converts it to an integer using the int() function. This way, even if the user enters a decimal value, the final num variable will be a whole number.

num = float(input('How many do you need?'))

Explanation

This choice directly takes the user input as a float, which means the num variable will store the decimal value entered by the user. It does not ensure that the num variable will be a whole number as required.

num = str(input('How many do you need?'))

Explanation

This choice takes the user input as a string, which means the num variable will store the input as a string. It does not convert the input to a whole number as required.

Overall explanation

Topics: input() float() int() str()

Try it yourself:

  1. num = int(float(input(‘How many do you need?’)))

  2. num = int(float(‘7.3’))

  3. print(num) # 7

  4. print(float(‘7.3’)) # 7.3

  5. print(str(‘7.3’)) # ‘7.3’

  6. print(int(‘7.3’)) # ValueError …

Explanation:

The input() function returns a string and in the end you need an integer

You can not use int() directly,

because you would get a ValueError if the user enters a decimal value.

Therefore you have to cast the input string to a float and then to an integer

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

Domain

02 – Data Types

Question 43Skipped

Q515 – Operators

What would you insert instead of ???

so that the program prints True to the monitor?

  1. x = ‘Peter’
  2. y = ‘Peter’
  3. res = ???
  4. print(res)

x != y

Explanation

The ‘!=’ operator is used to check if two objects are not equal. Since x and y are assigned the same string value ‘Peter’, the expression ‘x != y’ will evaluate to False, not True as required by the question.

Correct answer

x is y

Explanation

The ‘is’ operator in Python is used to compare the memory addresses of two objects. In this case, since both x and y are assigned the same string value ‘Peter’, they will refer to the same memory address, making the expression ‘x is y’ evaluate to True.

x is not y

Explanation

The ‘is not’ operator is the negation of the ‘is’ operator and checks if two objects do not have the same memory address. In this case, since x and y are assigned the same string value ‘Peter’, the expression ‘x is not y’ will evaluate to False, not True as required by the question.

x < y

Explanation

The ‘<‘ operator is used for comparing the values of two objects. In this case, comparing two strings using the ‘<‘ operator will result in a False value, as ‘Peter’ is not less than ‘Peter’ in a string comparison.

Overall explanation

Topics: identity operator less than operator

not equal to operator not

Try it yourself:

  1. x = ‘Peter’

  2. y = ‘Peter’

  3. res = x is y # True

  4. print(res)

  5. print(x < y) # False

  6. print(x != y) # False

  7. print(x is not y) # False

  8. print(id(x)) # e.g. 140539652049216

  9. print(id(y)) # e.g. 140539652049216 (the same number)

Explanation:

string is an immutable data type.

If you create a second string of the same value,

Python will created a reference to the same object.

Therefore those two strings will have the same identity.

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

Domain

03 – Operators

Question 44Skipped

Q528 – Basics

You have the following file.

  1. index.py:
  2. from sys import argv
  3. sum = 0
  4. for i in range(2, len(argv)):
  5. sum += float(argv[i])
    
  6. print(
  7. "The average score for {0} is {1:.2f}"
    
  8. .format(argv[1], sum/(len(argv)-2))
    
  9. )

You want the following output.

The average score for Peter is 200.00

Which command do you have to execute in the command line?

python index.py Peter 100

Explanation

This choice is incorrect because it provides only one numerical value as an argument after the name argument. The script requires at least three numerical values after the name argument to calculate the average score, but this choice only provides one numerical value.

The code is erroneous.

Explanation

This choice is incorrect because the code is not erroneous. The script is written correctly to calculate the average score based on the provided arguments. The issue lies in the input provided when executing the script, not in the script itself.

Correct answer

python index.py Peter 100 200 300

Explanation

This choice is correct because it provides the necessary arguments for the script to run successfully. The script expects the first argument to be the name (Peter in this case) and the following arguments to be numerical values to calculate the average score. In this case, the average score will be calculated as (100 + 200 + 300) / 3 = 200, which matches the desired output.

python index.py Peter 100 200

Explanation

This choice is incorrect because it does not provide enough numerical values as arguments for the script to calculate the average score. The script requires at least three numerical values after the name argument to calculate the average score, but this choice only provides two numerical values.

Overall explanation

Topics: sys.argv for range() format() len()

Try it yourself:

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

  2. code = ”’

  3. from sys import argv

  4. sum = 0

  5. for i in range(2, len(argv)):

  6. sum += float(argv[i])
    
  7. print(

  8. "The average score for {0} is {1:.2f}"
    
  9. .format(argv[1], sum/(len(argv)-2))
    
  10. )

  11. ”’

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

  13. f.write(code)
    
  14. In Terminal:

  15. python index.py Peter 100 200 300

Explanation:

range() starts at 2 because in index 0 always is the filename

and in index 1 will be the name Peter

format() is used here with numbered indexes.

The name 'Peter' from argv[1] will go to {0}

and the average will go to {1}

The numbered index {1} is also formated by {1:.2f}

with is responsible for the two fix point number format: 200.00

To test it, you have to open the folder

where you created the index.py file in a terminal

and run the file by executing python index.py Peter 100 200 300

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

Domain

01 – Basics

Question 45Skipped

Q536 – I/O

You want to be able to read and write data to a file.

The file needs to be automatically created, if it doesn’t exist.

If the file does already exist, you want to override the existing content.

Which of the following commands do you have to choose?

Correct answer

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

Explanation

The ‘w+’ mode in the open() function allows you to read and write to a file. If the file does not exist, it will be automatically created. If the file already exists, the existing content will be overridden, making it the correct choice for the given requirements.

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

Explanation

The ‘r’ mode in the open() function only allows you to read from a file. It does not provide the functionality to write to the file or automatically create it if it doesn’t exist. Therefore, it is not the correct choice for the given requirements.

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

Explanation

The ‘r+’ mode in the open() function allows you to read and write to a file, but it does not automatically create the file if it doesn’t exist. Additionally, it does not override the existing content by default, so it is not the best choice for the specified requirements.

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

Explanation

The ‘w’ mode in the open() function allows you to write to a file, but it does not provide the functionality to read from the file. While it can automatically create the file if it doesn’t exist, it does not meet the requirement of overriding the existing content. Therefore, it is not the correct choice for the given scenario.

Overall explanation

Topic: open() and its modes

Try it yourself:

  1. This works:

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

  3. file.write(‘Hello’)

  4. file.seek(0)

  5. data = file.read()

  6. print(data) # Hello

  7. file.close()

  8. This would not create the not existing file:

  9. To test it, delete the file before running it.

  10. open(‘data.txt’, ‘r+’) # FileNotFoundError: …

  11. """

  12. This only opens for reading:

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

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

  15. """

  16. """

  17. This only opens for writing:

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

  19. file.write(‘Hello’)

  20. file.seek(0)

  21. data = file.read() # io.UnsupportedOperation: not readable

  22. """

Explanation:

You need the plus sign + to have reading and writing.

But only w+ creates the not existing file.

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

Domain

07 – I/O

Question 46Skipped

Q508 – Data Aggregates

What is the expected output of the following code?

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

(4)

Explanation

This choice is incorrect because the parentheses around the number 4 do not affect the output. The value assigned to the variable ‘data’ is an integer, not a tuple. The code directly assigns the integer 4 to the variable ‘data’ and prints it without any additional formatting.

(4,)

Explanation

This choice is incorrect because the code does not create a tuple with a single element. The value assigned to the variable ‘data’ is an integer, not a tuple. The code directly assigns the integer 4 to the variable ‘data’ and prints it without any additional formatting.

44

Explanation

This choice is incorrect because the code does not perform any operations that would result in the value being duplicated or concatenated. The code simply extracts and assigns specific elements from the tuple ‘data’ and prints the final value, which is 4.

Correct answer

4

Explanation

The code first assigns a new tuple containing elements from index -2 (inclusive) to index -1 (exclusive) to the variable ‘data’. This results in a tuple with a single element, which is 4. Then, the code assigns this single element to the variable ‘data’. Finally, the code prints the value of ‘data’, which is 4.

Overall explanation

Topics: tuple slicing tuple indexing

Try it yourself:

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

Explanation:

The slicing start is -2 the second last element.

Here is the value 4

The slicing end is -1 the last element, which is exclusive.

That leaves the value 4 in the tuple

The indexing -1 also takes the last element, the value 4

(which is the only element)

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

Domain

04 – Data Aggregates

Question 47Skipped

Q545 – Error Handling

What is the expected output of the following code?

  1. try:
  2. raise Exception
    
  3. except BaseException:
  4. print('1', end='')
    
  5. else:
  6. print('2', end='')
    
  7. finally:
  8. print('3', end='')
    

1

Explanation

The code will raise an exception of type Exception, which is a subclass of BaseException. The except block will catch the exception, and ‘1’ will be printed. Since there is no else block, ‘2’ will not be printed. Finally, the finally block will always execute, and ‘3’ will be printed. Therefore, the output is ’13’.

23

Explanation

The code will raise an exception of type Exception, which is a subclass of BaseException. The except block will catch the exception, and ‘1’ will be printed. Since there is no else block, ‘2’ will not be printed. The finally block will always execute, and ‘3’ will be printed. Therefore, the output is ’13’.

Correct answer

13

Explanation

The code will raise an exception of type Exception, which is a subclass of BaseException. The except block will catch the exception, and ‘1’ will be printed. Then, the finally block will always execute, regardless of whether an exception was caught or not, and ‘3’ will be printed. Therefore, the expected output is ’13’.

12

Explanation

The code will raise an exception of type Exception, which is a subclass of BaseException. The except block will catch the exception, and ‘1’ will be printed. Since there is no else block, ‘2’ will not be printed. The finally block will always execute, and ‘3’ will be printed. Therefore, the output is ’13’.

Overall explanation

Topics: try except else finally Exception BaseException

Try it yourself:

  1. try:

  2. raise Exception
    
  3. except BaseException:

  4. print('1', end='')  # 1
    
  5. else:

  6. print('2', end='')
    
  7. finally:

  8. print('3', end='')  # 3
    
  9. print(issubclass(Exception, BaseException)) # True

Explanation:

BaseException is the top-most Exception in Python.

Therefore Exception (like any other exception class)

is a subclass of BaseException.

And that is why the except BaseException block is executed.

If an except block is executed, the else block is not executed.

The finally block is always executed.

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

Domain

08 – Error Handling

Question 48Skipped

Q523 – Data Types

How many arguments can the print() function take?

Just one argument.

Explanation

While the print() function can take just one argument, it is not limited to only one argument. Python allows for multiple arguments to be passed to the print() function, making it versatile for various printing needs.

Any number of arguments (excluding zero).

Explanation

The print() function in Python can take any number of arguments, excluding zero. This means that while it can print multiple values and expressions, at least one argument must be provided for the function to execute successfully.

Not more than seven arguments.

Explanation

The print() function in Python is not limited to a specific number of arguments, such as seven. It can take any number of arguments, making it suitable for printing a wide range of values and expressions.

Correct answer

Any number of arguments (including zero).

Explanation

The print() function in Python can take any number of arguments, including zero. This flexibility allows for printing multiple values, strings, variables, and expressions in a single function call.

Overall explanation

Topics: print()

Try it yourself:

  1. print(1) # 1
  2. print() # An empty line
  3. print(1, 2, 3, 4, 5, 6, 7, 8, 11) # 1 2 3 4 5 6 7 8 11

Explanation:

The print() function called without an argument will print an empty line.

The amount of possible arguments depends on the capacities of your computer

but it is going to be more than you will ever need.

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

Domain

02 – Data Types

Question 49Skipped

Q524 – Control Flow

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

  1. for i in range(1):
  2. print('*')
    
  3. else:
  4. print('*')
    

Correct answer

two

Explanation

The snippet will print two stars to the monitor because the loop will iterate once, printing one star, and then the ‘else’ block will execute, printing another star.

three

Explanation

The snippet will not print three stars to the monitor because the loop will iterate once, printing one star, and then the ‘else’ block will execute, printing another star.

zero

Explanation

The snippet will not print zero stars to the monitor because the loop will iterate once, printing one star, and then the ‘else’ block will execute, printing another star.

one

Explanation

The snippet will not print one star to the monitor because the loop will iterate once, printing one star, and then the ‘else’ block will execute, printing another star.

Overall explanation

Topics: for else (nobreak)

Try it yourself:

  1. for i in range(1):
  2. print('i:', 1)  # 1
    
  3. print('*')      # *
    
  4. else:
  5. print('*')      # *
    

Explanation:

There will be just one iteration.

But because there is no break inside the for loop,

the else clause will execute and the second star will be printed.

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

Domain

05 – Control Flow

Question 50Skipped

Q505 – Data Aggregates

What is the expected output of the following code?

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

3

Explanation

This choice is incorrect because the len() function counts all items in the list, including None, empty tuple, and empty list. Therefore, the output of the code will not be 3.

4

Explanation

This choice is incorrect because the len() function counts all items in the list, including None, empty tuple, and empty list. Therefore, the output of the code will not be 4.

5

Explanation

This choice is incorrect because the len() function counts all items in the list, including None, empty tuple, and empty list. Therefore, the output of the code will not be 5.

The code is erroneous.

Explanation

This choice is incorrect because the code is not erroneous. It creates a list and prints the length of the list, which is a valid operation in Python. The expected output can be determined by counting the items in the list.

Correct answer

6

Explanation

The code creates a list ‘data’ containing integers, None, an empty tuple, and an empty list. The len() function in Python returns the number of items in a container, so the output will be 6, as there are 6 items in the ‘data’ list.

Overall explanation

Topics: list len()

Try it yourself:

  1. data = [1, 2, 3, None, (), [], ]
  2. print(len(data)) # 6

Explanation:

An empty element is still an element.

That makes it six.

The trailing comma just gets ignored.

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

Domain

04 – Data Aggregates

Question 51Skipped

Q518 – Functions

What is the expected output of the following code?

  1. def func(data):

  2. data = [7, 23, 42]
    
  3. print('Function scope: ', data)
    
  4. data = [‘Peter’, ‘Paul’, ‘Mary’]

  5. func(data)

  6. print(‘Outer scope: ‘, data)

  7. Function scope: [7, 23, 42]

  8. Outer scope: [7, 23, 42]

Explanation

The function func assigns a new list [7, 23, 42] to the data variable within the function scope and prints it. However, this change is only within the function scope and does not affect the data variable in the outer scope, which remains as ['Peter', 'Paul', 'Mary'].

None of the above.

Explanation

None of the above choices are correct as the correct output is Function scope: [7, 23, 42] Outer scope: [‘Peter’, ‘Paul’, ‘Mary’].

  1. Function scope: [‘Peter’, ‘Paul’, ‘Mary’]
  2. Outer scope: [‘Peter’, ‘Paul’, ‘Mary’]

Explanation

The function func assigns a new list [7, 23, 42] to the data variable within the function scope and prints it. This change is only within the function scope and does not affect the data variable in the outer scope, which remains as ['Peter', 'Paul', 'Mary'].

Correct answer

  1. Function scope: [7, 23, 42]
  2. Outer scope: [‘Peter’, ‘Paul’, ‘Mary’]

Explanation

The function func takes a parameter data, assigns a new list [7, 23, 42] to the data variable within the function scope, and prints it. This change is only within the function scope and does not affect the data variable in the outer scope, which remains as ['Peter', 'Paul', 'Mary'].

Overall explanation

Topics: def list scope

Try it yourself:

  1. def func(data):

  2. data = [7, 23, 42]
    
  3. print('Function scope: ', data)  # [7, 23, 42]
    
  4. data = [‘Peter’, ‘Paul’, ‘Mary’]

  5. func(data)

  6. print(‘Outer scope: ‘, data) # [‘Peter’, ‘Paul’, ‘Mary’]

Explanation:

The parameter data will become a new entity with the function as its scope.

The variable data in the outer scope is a different entity.

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

Domain

06 – Functions

Question 52Skipped

Q512 – Operators

What is the expected output of the following code?

print(3 * 'abc' + 'xyz')

3abcxyz

Explanation

This choice does not accurately reflect the concatenation and multiplication operations happening in the code snippet. It does not represent the correct output of the given code.

abcabcxyzxyz

Explanation

This choice incorrectly combines the repeated ‘abc’ string and the ‘xyz’ string in an incorrect order. It does not accurately represent the expected output of the code snippet.

Correct answer

abcabcabcxyz

Explanation

The code snippet multiplies the string ‘abc’ by 3, resulting in ‘abcabcabc’, and then concatenates ‘xyz’ to the end. Therefore, the expected output is ‘abcabcabcxyz’.

abcxyzabcxyzabcxyz

Explanation

This choice incorrectly repeats the ‘abc’ and ‘xyz’ strings in an alternating pattern, which is not the expected output of the given code snippet. It does not accurately represent the concatenation operation in the code.

Overall explanation

Topics: multiply operator string concatenation

plus operator string concatenation operator precedence

Try it yourself:

  1. print(3 * ‘abc’ + ‘xyz’) # abcabcabcxyz
  2. print((3 * ‘abc’) + ‘xyz’) # abcabcabcxyz
  3. print(‘abcabcabc’ + ‘xyz’) # abcabcabcxyz
  4. print(‘abcabcabcxyz’) # abcabcabcxyz

Explanation:

Only string concatenation is taking place here.

Still you have the usual operator precedence

Multiplication comes before addition.

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

Domain

03 – Operators

Question 53Skipped

Q521 – Functions

What is the expected output of the following code?

  1. def func(x, y):

  2. if x == y:
    
  3.     return x
    
  4. else:
    
  5.     return
    
  6. func(x, y=1)

  7. print(func(0, 3))

1

Explanation

The function func will return None when called with arguments 0 and 3 because the condition if x == y is not satisfied. The output will not be 1.

0

Explanation

The code will not reach the return x statement in the function func because the condition if x == y is not satisfied when calling func(0, 3). Therefore, the function will return None, and the output will not be 0.

Correct answer

The code is erroneous.

Explanation

The code is erroneous because the function func is defined with parameters x and y, but when calling the function func(x, y=1), the variable x is not defined. This will result in a NameError as x is not defined in the function call.

3

Explanation

The function func will return None when called with arguments 0 and 3 because the condition if x == y is not satisfied. The output will not be 3.

Overall explanation

Topics: def argument if else equal to operator NameError

Try it yourself:

  1. def func(x, y):

  2. if x == y:
    
  3.     return x
    
  4. else:
    
  5.     return
    
  6. func(x, y=1) # NameError: name ‘x’ is not defined

  7. print(func(0, 3))

Explanation:

The argument x is not defined.

There is a possibility to save time here.

Once you see the error, click the corresponding answer and move on.

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

Domain

06 – Functions

Question 54Skipped

Q533 – Data Types

You want to print the sum of two number.

What snippet would you insert in the line indicated below:

  1. x = input(‘Enter the first number: ‘)
  2. y = input(‘Enter the second number: ‘)
  3. insert your code here

print('The Result is ' + (int(x + y)))

Explanation

This choice attempts to concatenate the input values x and y as strings directly inside the print statement without converting them to integers first. This would result in a concatenation of the two input strings, not their sum. To calculate the sum of the two numbers, they need to be converted to integers before adding them together.

Correct answer

print('The Result is ' + str(int(x) + int(y)))

Explanation

This choice correctly converts the input values x and y to integers using int() function, adds them together, and then converts the result back to a string using str() function before concatenating it with the rest of the print statement. This ensures that the sum of the two numbers is printed as a string along with the specified message.

print('The Result is ' + (int(x) + int(y)))

Explanation

This choice attempts to add the input values x and y as integers directly inside the print statement without converting them first. This would result in a TypeError because the addition operation cannot be performed on strings. The correct approach is to convert the input values to integers before performing the addition.

print('The Result is ' + str(int(x + y)))

Explanation

This choice attempts to concatenate the input values x and y as a single string inside the print statement without converting them to integers first. This would result in a concatenation of the two input strings, not their sum. To calculate the sum of the two numbers, they need to be converted to integers before adding them together. Additionally, the result should be converted back to a string before concatenating it with the rest of the print statement.

Overall explanation

Topic: int() str() input()

Try it yourself:

  1. x = input(‘Enter the first number: ‘)

  2. y = input(‘Enter the second number: ‘)

  3. x, y = ‘7’, ’11’ # Just for convenience

  4. You cannot concatenate a string and an integer

  5. print(‘The Result is ‘ + (int(x) + int(y))) # TypeError

  6. print(‘The Result is ‘ + (int(x + y))) # TypeError

  7. This works, but you get the wrong result,

  8. because there is a string concatenation

  9. before the type casting to integer:

  10. print(‘The Result is ‘ + str(int(x + y))) # 711

  11. print(‘The Result is ‘ + str(int(x) + int(y))) # 18

Explanation:

As always input() returns a string

Before you add them to each other you need to cast both of them to an integer

You need to cast the result to a string

to be able to concatenate it to the other string

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

Domain

02 – Data Types

Question 55Skipped

Q511 – Operators

What is the expected output of the following code?

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

  2. list2 = [3, 7, 23, 42]

  3. print(list1 is list2)

  4. print(list1 == list2)

  5. True

  6. False

Explanation

This explanation is incorrect because the ‘is’ operator checks for object identity, not object equality. Since list1 and list2 are two separate objects in memory, the ‘is’ operator will return False. The ‘==’ operator, however, will return True because the values of the two lists are the same.

Correct answer

  1. False
  2. True

Explanation

The ‘is’ operator in Python checks if two variables refer to the same object in memory. In this case, list1 and list2 are two separate objects, even though they have the same values. Therefore, the ‘is’ operator will return False. The ‘==’ operator, on the other hand, checks if the values of the two objects are equal, which is True in this case.

  1. False
  2. False

Explanation

This explanation is incorrect because both the ‘is’ and ‘==’ operators will not return False for both statements. The ‘is’ operator will return False because list1 and list2 are two separate objects, while the ‘==’ operator will return True because the values of the two lists are the same.

  1. True
  2. True

Explanation

This explanation is incorrect because the ‘is’ operator will not return True for both statements. The ‘is’ operator checks for object identity, and since list1 and list2 are two separate objects, it will return False. The ‘==’ operator will return True because the values of the two lists are the same.

Overall explanation

Topics: list equal to operator identity operator

Try it yourself:

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

  2. list2 = [3, 7, 23, 42]

  3. print(list1 is list2) # False

  4. print(list1 == list2) # True

  5. print(id(list1)) # e.g. 140532269484352

  6. print(id(list2)) # e.g. 140532269935296 (a different number)

Explanation:

list is a mutable data type.

If you create a second list (even one with the same values)

it will always be a new object.

You can test that with the id() function.

It returns a unique integer, the identity of the object.

The equal to operator compares the values, which are the same.

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

Domain

03 – Operators

Question 56Skipped

Q516 – Control Flow

What is the expected output of the following code?

marks = [80, 70, 90, 90, 80, 100]

average = sum(marks) // len(marks)

grade = ''

  1. if 90 <= average <= 100:

  2. grade = 'A'
    
  3. elif 80 <= average < 90:

  4. grade = 'B'
    
  5. elif 70 <= average < 80:

  6. grade = 'C'
    
  7. elif 65 <= average < 70:

  8. grade = 'D'
    
  9. else:

  10. grade = 'F'
    
  11. print(grade)

C

Explanation

The code assigns a grade based on the average calculated from the marks. However, the average does not fall between 70 and 80, so the grade ‘C’ is not expected as the output.

Correct answer

B

Explanation

The code calculates the average of the marks and assigns a grade based on the average. In this case, the average falls between 80 and 90, so the expected output is ‘B’.

The code is erroneous.

Explanation

The code is correct and error-free, so the output is expected to be one of the defined grades (‘A’, ‘B’, ‘C’, ‘D’, or ‘F’).

D

Explanation

The code assigns a grade based on the average calculated from the marks. Since the average does not fall between 65 and 70, the grade ‘D’ is not expected as the output.

F

Explanation

The code assigns a grade based on the average calculated from the marks. Since the average does not fall below 65, the grade ‘F’ is not expected as the output.

A

Explanation

The code assigns a grade based on the average calculated from the marks. Since the average falls between 80 and 90, the grade is expected to be ‘B’.

Overall explanation

Topics: if elif else list sum() len() chained comparison

Try it yourself:

  1. marks = [80, 70, 90, 90, 80, 100]

  2. average = sum(marks) // len(marks)

  3. grade = ”

  4. if 90 <= average <= 100:

  5. grade = 'A'
    
  6. elif 80 <= average < 90:

  7. grade = 'B'
    
  8. elif 70 <= average < 80:

  9. grade = 'C'
    
  10. elif 65 <= average < 70:

  11. grade = 'D'
    
  12. else:

  13. grade = 'F'
    
  14. print(grade) # B

  15. print(sum(marks)) # 510

  16. print(average) # 85

Explanation:

Here you really have to do a little mental arithmetic.

80 + 70 + 90 + 90 + 80 + 100 -> 510

510 // 6 -> 85

85 is a the grade B

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

Domain

05 – Control Flow

Question 57Skipped

Q507 – Data Aggregates

What is the expected output of the following code?

  1. data = {‘one’: ‘two’, ‘two’: ‘three’, ‘three’: ‘one’}

  2. res = data[‘three’]

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

  4. res = data[res]
    
  5. print(res)

three

Explanation

The code initializes a dictionary ‘data’ with key-value pairs. It then assigns the value corresponding to the key ‘three’ to the variable ‘res’. In the loop, the code iterates through the dictionary ‘data’ for the length of the dictionary, updating ‘res’ with the value corresponding to the current value of ‘res’. However, the final value of ‘res’ will not be ‘three’, so this choice is incorrect.

Correct answer

one

Explanation

The code initializes a dictionary ‘data’ with key-value pairs. It then assigns the value corresponding to the key ‘three’ to the variable ‘res’. In the loop, the code iterates through the dictionary ‘data’ for the length of the dictionary, updating ‘res’ with the value corresponding to the current value of ‘res’. Eventually, ‘res’ will be updated to ‘one’, which is the expected output.

('one', 'two', 'three')

Explanation

The code initializes a dictionary ‘data’ with key-value pairs. It then assigns the value corresponding to the key ‘three’ to the variable ‘res’. In the loop, the code iterates through the dictionary ‘data’ for the length of the dictionary, updating ‘res’ with the value corresponding to the current value of ‘res’. The final value of ‘res’ will not be a tuple containing ‘one’, ‘two’, and ‘three’, so this choice is incorrect.

two

Explanation

The code initializes a dictionary ‘data’ with key-value pairs. It then assigns the value corresponding to the key ‘three’ to the variable ‘res’. In the loop, the code iterates through the dictionary ‘data’ for the length of the dictionary, updating ‘res’ with the value corresponding to the current value of ‘res’. However, the final value of ‘res’ will not be ‘two’, so this choice is incorrect.

Overall explanation

Topics: dictionary for range() len()

Try it yourself:

  1. data = {‘one’: ‘two’, ‘two’: ‘three’, ‘three’: ‘one’}

  2. res = data[‘three’]

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

  4. print(res)  # one - two - three
    
  5. res = data[res]
    
  6. print(res) # one

Explanation:

Before the for loop res is 'one'

data['one']->'two'->data['two']->'three'->data['three']->'one'

After the for loop, res again is 'one'

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

Domain

04 – Data Aggregates