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

Python ITS-303 Test Exam IV (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

Q417 – Operators

Consider the following code.

x = float('23.42')

Which of the following expressions will evaluate to 2?

Correct answer

bool(x) + True

Explanation

The expression bool(x) will evaluate to True because the float value x (23.42) is considered a truthy value. Adding True to any integer value (which bool(x) evaluates to 1) will result in 2.

str(x)

Explanation

The expression str(x) will evaluate to the string representation of the float value x (23.42). It will not result in 2 as it does not involve any arithmetic operations.

bool(x)

Explanation

The expression bool(x) will evaluate to True because the float value x (23.42) is considered a truthy value. However, adding bool(x) to itself (which evaluates to 1) will result in 1, not 2.

int(x) + False

Explanation

The expression int(x) will evaluate to 23 because it converts the float value x (23.42) to an integer by truncating the decimal part. Adding False (which evaluates to 0) to 23 will not result in 2.

Overall explanation

Topics: float() bool() int() str()

Try it yourself:

  1. x = float(‘23.42’)

  2. print(bool(x) + True) # 2

  3. print(int(x) + False) # 23

  4. print(str(x)) # ‘23.42’

  5. print(bool(x)) # True

  6. print(float(‘23.42’)) # 23.42

  7. print(bool(23.42)) # True

  8. print(True + True) # 2

  9. print(True – False) # 1

  10. print(True * True) # 1

  11. print(True / True) # 1.0

  12. print(True % True) # 0

Explanation:

First the string '23.42' becomes the float 23.42

Casted to a boolean the float 23.42 becomes True

If you calculate with a boolean True becomes 1 and False becomes 0

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

Domain

03 – Operators

Question 2Skipped

Q441 – Error Handling

What is the expected output of the following code?

  1. data = [‘peter’, ‘paul’, ‘mary’]
  2. for d in data:
  3. data.append(d.upper())
    
  4. print(data)

Correct answer

The code will enter an infinite loop.

Explanation

The code will enter an infinite loop because the for loop iterates over the original list ‘data’ and appends the uppercase version of each element back to the list. This results in the list growing indefinitely as new elements are added during each iteration.

['PETER'**,** 'PAUL'**,** 'MARY']

Explanation

The expected output of the code is not [‘PETER’, ‘PAUL’, ‘MARY’]. Since the code enters an infinite loop by continuously appending uppercase versions of the elements, the final list will not be limited to just the original elements in uppercase.

['Peter'**,** 'Paul'**,** 'Mary']

Explanation

The expected output of the code is not [‘Peter’, ‘Paul’, ‘Mary’]. Due to the continuous appending of uppercase versions of the elements in the list ‘data’, the final list will contain an ever-growing number of elements, including the original elements in uppercase.

The code is erroneous.

Explanation

The code is not erroneous, but it will result in unexpected behavior due to the modification of the list ‘data’ while iterating over it. This can lead to unexpected results and potentially cause issues in the program.

Overall explanation

Topics: list for MemoryError append() upper()

Try it yourself:

  1. """

  2. data = [‘peter’, ‘paul’, ‘mary’]

  3. for d in data:

  4. data.append(d.upper())
    
  5. print(data)

  6. """

  7. This would work:

  8. data = [‘peter’, ‘paul’, ‘mary’]

  9. res = []

  10. for d in data:

  11. res.append(d.upper())
    
  12. print(res) # [‘PETER’, ‘PAUL’, ‘MARY’]

Explanation:

The for loop iterates the list data

Inside of the loop a new element is appended to the list data

The for loop wants to iterate that element too.

The for loop can never finish,

because every time it iterates the next element,

again a new element is appended.

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

Domain

08 – Error Handling

Question 3Skipped

Q445 – Control Flow

What is the expected output of the following code?

  1. data = [[42, 17, 23, 13], [11, 9, 3, 7]]
  2. res = data[0][0]
  3. for da in data:
  4. for d in da:
    
  5.     if res > d:
    
  6.         res = d
    
  7. print(res)

42

Explanation

The code is intended to find the smallest element in the ‘data’ list. The smallest element in the ‘data’ list is 3, not 42. Therefore, 42 is not the expected output of the code.

13

Explanation

The code is designed to find the smallest element in the ‘data’ list. However, the smallest element in the ‘data’ list is 3, not 13. Therefore, 13 is not the expected output of the code.

Correct answer

3

Explanation

The code initializes the variable ‘res’ with the first element of the first sublist in ‘data’, which is 42. Then, it iterates through each sublist and each element in the sublist. If the current element is smaller than the current value of ‘res’, ‘res’ is updated to that element. In this case, the smallest element in the ‘data’ list is 3, so the expected output is 3.

The code is erroneous.

Explanation

The code is not erroneous. It correctly iterates through the nested list ‘data’ to find the smallest element and assigns it to the variable ‘res’. The expected output of the code is the smallest element in the ‘data’ list, which is 3.

Overall explanation

Topics: list for if

Try it yourself:

  1. data = [[42, 17, 23, 13], [11, 9, 3, 7]]
  2. res = data[0][0]
  3. print(res) # 42
  4. for da in data:
  5. for d in da:
    
  6.     if res > d:
    
  7.         print('d: ', d)  # 17 -> 13 -> 11 -> 9 -> 3
    
  8.         res = d
    
  9. print(res) # 3

Explanation:

This code snippet looks for the lowest element

in the two dimensional list data

In the beginning the first number data[0][0] gets taken as possible result.

In the inner for loop every number is compared to the possible result.

If one number is lower it becomes the new possible result.

And in the end the result is the lowest number.

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

Domain

05 – Control Flow

Question 4Skipped

Q430 – Data Types

What is the expected output of the following code?

  1. print(type(+1E10))

  2. print(type(5.0))

  3. print(type(‘True’))

  4. print(type(False))

  5. <class ‘int’>

  6. <class ‘float’>

  7. <class ‘str’>

  8. <class ‘bool’>

Explanation

The first line of code prints the type of the expression +1E10, which is a float in Python. The second line prints the type of the expression 5.0, which is also a float. The third line prints the type of the string ‘True’, which is a string (str) in Python. The last line prints the type of the boolean value False, which is a boolean (bool) in Python.

  1. <class ‘float’>
  2. <class ‘float’>
  3. <class ‘bool’>
  4. <class ‘bool’>

Explanation

The first line of code prints the type of the expression +1E10, which is a float in Python. The second line prints the type of the expression 5.0, which is also a float. The third line prints the type of the string ‘True’, which is a string (str) in Python. The last line prints the type of the boolean value False, which is a boolean (bool) in Python.

  1. <class ‘int’>
  2. <class ‘float’>
  3. <class ‘bool’>
  4. <class ‘bool’>

Explanation

The first line of code prints the type of the expression +1E10, which is a float in Python. The second line prints the type of the expression 5.0, which is also a float. The third line prints the type of the string ‘True’, which is a string (str) in Python. The last line prints the type of the boolean value False, which is a boolean (bool) in Python.

Correct answer

  1. <class ‘float’>
  2. <class ‘float’>
  3. <class ‘str’>
  4. <class ‘bool’>

Explanation

The first line of code prints the type of the expression +1E10, which is a float in Python. The second line prints the type of the expression 5.0, which is also a float. The third line prints the type of the string ‘True’, which is a string (str) in Python. The last line prints the type of the boolean value False, which is a boolean (bool) in Python.

Overall explanation

Topics: type() float integer string boolean

scientific notation

Try it yourself:

  1. print(type(+1E10)) # <class ‘float’>
  2. print(type(5.0)) # <class ‘float’>
  3. print(type(‘True’)) # <class ‘str’>
  4. print(type(False)) # <class ‘bool’>

Explanation:

The scientific notation always returns a float

string with the word 'True' is still a string

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

Domain

02 – Data Types

Question 5Skipped

Q452 – Modules

Which one of the following is true?

modules can contain packages

Explanation

Modules in Python are standalone files that contain Python code and can be imported into other Python scripts. Packages, on the other hand, are directories that contain modules and can also contain sub-packages. Therefore, it is not true that modules can contain packages.

Correct answer

packages can contain modules

Explanation

Packages in Python are directories that contain modules. This allows for organizing related modules into a single package for better structure and management. Therefore, it is true that packages can contain modules.

modules can contain modules

Explanation

Modules in Python are individual files that contain Python code. While modules can import and use other modules, they cannot directly contain other modules within them. Modules typically serve as reusable components that can be imported into other Python scripts for functionality.

Overall explanation

Topics: package module

Explanation:

Read about it here:

https://realpython.com/python-modules-packages/#python-packages

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

Domain

09 – Modules

Question 6Skipped

Q412 – Operators

An operator able to check whether two values are equal, is coded as:

is

Explanation

The ‘is’ operator in Python is used to check if two variables refer to the same object in memory, not to check for equality between values. While ‘is’ can be used for comparison in certain cases, it is not the standard operator for checking equality between values in Python.

Correct answer

==

Explanation

The ‘==’ operator in Python is used to check whether two values are equal. It is the correct choice for comparing equality between two values in Python.

=

Explanation

The ‘=’ operator in Python is used for variable assignment, not for checking equality between two values. Using ‘=’ in this context would result in assigning the value on the right to the variable on the left, rather than comparing equality.

===

Explanation

The ‘===’ operator is not valid in Python. Python uses ‘==’ for equality comparison, so ‘===’ is not a recognized operator in Python and would result in a syntax error.

Overall explanation

Topic: equal to operator assign operator

identity operator

Try it yourself:

  1. print(23 == 23) # True

  2. print(23 === 23) # SyntaxError: invalid syntax

  3. w = 42

  4. x = [‘Peter’]

  5. y = [‘Peter’]

  6. print(x is y) # False

Explanation:

The equal to operator == checks, if to values are equal.

The assign operator = is to assign values.

The identity operator is checks, if two values are the same object.

(In more detail explained in other questions.)

There is NO identical operator === in Python.

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

Domain

03 – Operators

Question 7Skipped

Q424 – Data Aggregates

What is the expected output of the following code?

  1. data = ‘Hello@Peter!!’
  2. print(data.lower())

None

Explanation

This choice is incorrect because the lower() method does not return None. It always returns a new string with all characters converted to lowercase.

hellopeter

Explanation

This choice is incorrect because the lower() method does not remove any characters from the string. It only converts uppercase characters to lowercase, so the output will still contain all the characters from the original string.

hello@Peter!!

Explanation

This choice is incorrect because the lower() method converts all characters to lowercase, including the ‘P’ in ‘Peter’. Therefore, the expected output is ‘hello@peter!!’.

Correct answer

hello@peter!!

Explanation

The lower() method in Python converts all characters in a string to lowercase. In this code snippet, the string ‘Hello@Peter!!’ is converted to lowercase, resulting in ‘hello@peter!!’.

Overall explanation

Topics: string lower()

Try it yourself:

  1. data = ‘Hello@Peter!!’
  2. print(data.lower()) # hello@peter!!

Explanation:

The string method lower() converts all

uppercase characters to lowercase characters.

The not uppercase characters do not get touched.

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

Domain

04 – Data Aggregates

Question 8Skipped

Q439 – Modules

The module has been imported using the following line.

from mod import func

How can you invoke the function?

mod:func()

Explanation

The syntax "mod:func()" is incorrect for invoking the function. The colon ":" is not used to call functions in Python; it is used for slicing, specifying key-value pairs in dictionaries, or for labeling in loops. Using "mod:func()" would result in a syntax error.

mod.func()

Explanation

The syntax "mod.func()" is incorrect in this scenario because the function was imported directly using "from mod import func", which means you do not need to reference the module name when invoking the function. Using "mod.func()" would result in a NameError as the function is not accessed through the module name.

mod::func()

Explanation

The syntax "mod::func()" is incorrect for invoking the function. The double colon "::" is not a valid syntax for calling functions in Python. Using "mod::func()" would result in a syntax error.

Correct answer

func()

Explanation

By importing the function using the syntax "from mod import func", you can directly invoke the function by calling its name followed by parentheses, as shown in the choice "func()". This syntax allows you to use the function without referencing the module name.

Overall explanation

Topics: from import

Try it yourself:

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

  2. text = ”’

  3. def func():

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

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

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

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

Explanation:

Only the function func() of the module mod gets imported here.

To invoke the function you just need the function name: func()

(There is another question about this topic Q240.)

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

Domain

09 – Modules

Question 9Skipped

Q425 – Basics

What is the default value of encoding in the string function encode()?

ascii

Explanation

The encoding ascii is not the default value for the encode() function in Python. While ascii encoding is a common encoding for ASCII characters, it is not the default encoding used in the encode() function.

Correct answer

utf-8

Explanation

The default value of encoding in the string function encode() is utf-8. This encoding is commonly used for encoding Unicode text and is the default encoding for Python strings.

utf-16

Explanation

The encoding utf-16 is not the default value for the encode() function in Python. While utf-16 is another common encoding for Unicode text, it is not the default encoding used in the encode() function.

qwerty

Explanation

The encoding qwerty is not a valid encoding option in Python and is not the default value for the encode() function. The default encoding for the encode() function is utf-8, not qwerty.

Overall explanation

Topics: encode() UTF-8

Try it yourself:

  1. print(list(‘a’.encode())) # [97]
  2. print(list(‘a’.encode(‘utf-8’))) # [97]
  3. print(list(‘a’.encode(‘utf-16’))) # [255, 254, 97, 0]
  4. print(list(‘a’.encode(‘utf-32’))) # [255, 254, 0, 0, 97, 0, 0, 0]

Explanation:

The official documentation says it all:

https://docs.python.org/3/library/stdtypes.html?highlight=str.encode#str.encode

str.encode(encoding="utf-8", errors="strict")

Return an encoded version of the string as a bytes object.

Default encoding is ‘utf-8’ …

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

Domain

01 – Basics

Question 10Skipped

Q436 – Modules

Consider the following code.

  1. def get_data(filename, mode):
  2. import os
    
  3. if os.path.isfile(filename):
    
  4.     with open(filename, mode) as file:
    
  5.         return file.readline()
    
  6. else:
    
  7.     return
    

Which of the statements about this code are true?

Choose Two.

Correct selection

This function returns None if the file does not exist.

Explanation

This choice is correct because if the file specified in the filename parameter does not exist, the function returns None as per the else condition in the code.

Correct selection

This function returns the first line of the file if it is available.

Explanation

This choice is correct because the function uses the readline() method to read and return the first line of the file if it exists.

This function returns the total data that is present in the file.

Explanation

This choice is incorrect because the function only reads and returns the first line of the file, not the total data present in the file.

This function returns the last line of the file if it is available.

Explanation

This choice is incorrect because the function specifically uses the readline() method to read and return the first line of the file, not the last line.

Overall explanation

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

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. def get_data(filename, mode):

  9. import os
    
  10. if os.path.isfile(filename):
    
  11.     with open(filename, mode) as file:
    
  12.         return file.readline()
    
  13. else:
    
  14.     return
    
  15. print(get_data(‘data.txt’, ‘r’)) # Peter

  16. print(get_data(‘anyfile.txt’, ‘r’)) # None

Explanation:

The readline() method reads one line of a file

and therefore that is want the get_data() function will return.

(If the file is empty readline() will return an empty string.)

The isfile() method of the os.path module checks, whether a file exists.

If the file, that is passed in the first argument, does not exist,

the else clause will be executed and the single return finishes the function.

return without a given value will return None

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

Domain

09 – Modules

Question 11Skipped

Q455 – I/O

A method able to read data from a file into a bytes object, is named:

readout()

Explanation

The readout() method is not a standard method in Python for reading data from a file. It is not a valid choice for reading data from a file into a bytes object.

Correct answer

read()

Explanation

The read() method in Python is used to read data from a file and return it as a bytes object. It is the correct choice for reading data from a file into a bytes object.

readinto()

Explanation

The readinto() method in Python is used to read data from a file and store it in a pre-allocated bytes-like object. While it is related to reading data into an object, it is not the method specifically used for reading data from a file into a bytes object.

readin()

Explanation

The readin() method is not a standard method in Python for reading data from a file. It is not a valid choice for reading data from a file into a bytes object.

Overall explanation

Topic: read()

Try it yourself:

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

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

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

  5. b1 = f.read()
    
  6. print(b1) # b’ABC’

  7. print(type(b1)) # <class ‘bytes’>

Explanation:

readin() and readout() do not exist.

readinto() is not supported yet:

https://github.com/micropython/micropython/issues/909

BUT, if you get this question without read() as possible answer

you have to choose readinto()

The question would also be a little different like:

"A method able to read data from a file into a byte array object, is named:"

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

Domain

07 – I/O

Question 12Skipped

Q433 – Control Flow

Which of the code snippet below will print the following to the monitor?

  1. Paul

  2. Mary

  3. Jane

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

  5. for d in data:

  6. if len(d) != 4:
    
  7.     print(d)
    

Explanation

This code snippet iterates over the elements in the ‘data’ list and checks if the length of each element is not equal to 4. If the condition is met, it prints the element. Therefore, it will print ‘Peter’ as it is the only element in the list that does not have a length of 4 characters.

  1. data = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]
  2. for d in data:
  3. print(d)
    

Explanation

This code snippet simply iterates over all elements in the ‘data’ list and prints each element. Therefore, it will print all elements in the ‘data’ list, including ‘Peter’, ‘Paul’, ‘Mary’, and ‘Jane’.

Correct answer

  1. data = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]
  2. for d in data:
  3. if len(d) == 4:
    
  4.     print(d)
    

Explanation

This code snippet iterates over the elements in the ‘data’ list and checks if the length of each element is equal to 4. If the condition is met, it prints the element. Therefore, it will print ‘Paul’ and ‘Mary’ as they have a length of 4 characters.

  1. data = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]
  2. da = data[1:]
  3. for d in data:
  4. print(d)
    

Explanation

This code snippet creates a new list ‘da’ by slicing the ‘data’ list from the second element (‘Paul’) to the last element (‘Jane’). Then, it iterates over all elements in the ‘data’ list and prints each element. Therefore, it will print all elements in the ‘data’ list, including ‘Peter’, ‘Paul’, ‘Mary’, and ‘Jane’.

Overall explanation

Topics: list for if len()

equal to operator not equal to operator

Try it yourself:

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

  2. for d in data:

  3. if len(d) == 4:
    
  4.     print(d)
    
  5. """

  6. Paul

  7. Mary

  8. Jane

  9. """

  10. print(‘———-‘)

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

  12. da = data[1:]

  13. for d in data:

  14. print(d)
    
  15. """

  16. Peter

  17. Paul

  18. Mary

  19. Jane

  20. """

  21. print(‘———-‘)

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

  23. for d in data:

  24. if len(d) != 4:
    
  25.     print(d)
    
  26. """

  27. Peter

  28. """

  29. print(‘———-‘)

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

  31. for d in data:

  32. print(d)
    
  33. """

  34. Peter

  35. Paul

  36. Mary

  37. Jane

  38. """

Explanation:

The four searched names have in common, that they all have four letters.

Therefore len(d) == 4 fits the bill.

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

Domain

05 – Control Flow

Question 13Skipped

Q423 – Data Types

What is the expected output of the following code?

print(chr(ord('p') + 3))

t

Explanation

The code converts the character ‘p’ to its ASCII value, which is 112. Adding 3 to this value results in 115, which corresponds to the character ‘t’. However, the correct output is ‘s’, not ‘t’.

r

Explanation

The code converts the character ‘p’ to its ASCII value, which is 112. Adding 3 to this value results in 115, which corresponds to the character ‘r’. However, the correct output is ‘s’, not ‘r’.

Correct answer

s

Explanation

The code first converts the character ‘p’ to its ASCII value using the ord() function, which is 112. Then, it adds 3 to this ASCII value and converts it back to a character using the chr() function. The resulting character is ‘s’, so the expected output is ‘s’.

q

Explanation

The code converts the character ‘p’ to its ASCII value, which is 112. Adding 3 to this value results in 115, which corresponds to the character ‘q’. However, the correct output is ‘s’, not ‘q’.

Overall explanation

Topics: chr() ord()

Try it yourself:

  1. print(chr(ord(‘p’) + 3)) # s
  2. print(ord(‘p’)) # 112
  3. print(chr(115)) # s

Explanation:

ord() returns an integer representing the Unicode character.

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

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

but like in the alphabet s is three after p

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

Domain

02 – Data Types

Question 14Skipped

Q409 – Data Aggregates

What is the expected output of the following code?

  1. data = {‘z’: 23, ‘x’: 7, ‘y’: 42}

  2. for _ in sorted(data):

  3. print(data[_], end=' ')
    

42 23 7

Explanation

The code iterates over the keys of the ‘data’ dictionary in sorted order. Since dictionaries are unordered in Python, the keys are sorted alphabetically. Therefore, the output will be the corresponding values of the keys in sorted order, which are 42, 23, and 7.

Correct answer

7 42 23

Explanation

The code iterates over the keys of the ‘data’ dictionary in sorted order. Since dictionaries are unordered in Python, the keys are sorted alphabetically. Therefore, the output will be the corresponding values of the keys in sorted order, which are 7, 42, and 23.

7 23 42

Explanation

The code iterates over the keys of the ‘data’ dictionary in sorted order. Since dictionaries are unordered in Python, the keys are sorted alphabetically. Therefore, the output will be the corresponding values of the keys in sorted order, which are 7, 23, and 42.

The code is erroneous.

Explanation

The code is not erroneous. It iterates over the keys of the ‘data’ dictionary in sorted order and prints the corresponding values. The output will be 7, 42, and 23 in sorted order.

Overall explanation

Topics: dictionary for sorted() print() with end parameter

Try it yourself:

  1. data = {‘z’: 23, ‘x’: 7, ‘y’: 42}

  2. for _ in sorted(data):

  3. print(data[_], end=' ')  # 7 42 23
    
  4. print()

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

  6. print(data) # {‘z’: 23, ‘x’: 7, ‘y’: 42}

Explanation:

The sorted() function returns a sorted

list from the elements in a dictionary (or any other iterable).

In this case the list ['x', 'y', 'z']

In the for loop those indexes get printed out.

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

Domain

04 – Data Aggregates

Question 15Skipped

Q421 – Functions

What is the expected output of the following code?

  1. def func1(x):

  2. return str(x)
    
  3. def func2(x):

  4. return str(2 * x)
    
  5. print(func1(1) + func2(2))

The code is erroneous.

Explanation

The code is not erroneous. It correctly defines two functions, func1 and func2, that return the string representations of the input values. The print statement concatenates the results of calling func1(1) and func2(2), resulting in ’14’ as the expected output.

Correct answer

14

Explanation

The expected output of the code can be determined by evaluating the return values of func1(1) and func2(2). func1(1) returns the string representation of the integer 1, which is ‘1’. func2(2) returns the string representation of the integer 2 multiplied by 2, which is ‘4’. Therefore, the concatenation of ‘1’ and ‘4’ results in ’14’.

3

Explanation

The output ‘3’ is not the expected result of the code. The function func1(1) returns ‘1’ as a string, and func2(2) returns ‘4’ as a string. When concatenated, ‘1’ and ‘4’ result in ’14’, not ‘3’.

5

Explanation

The output ‘5’ is not the expected result of the code. The function func1(1) returns ‘1’ as a string, and func2(2) returns ‘4’ as a string. When concatenated, ‘1’ and ‘4’ result in ’14’, not ‘5’.

Overall explanation

Topics: def return str() string concatenation

Try it yourself:

  1. def func1(x):

  2. return str(x)
    
  3. def func2(x):

  4. return str(2 * x)
    
  5. print(func1(1) + func2(2)) # 14

Explanation:

Both functions will return a string

func1() the string '1'

and func2() the string '4'

The string concatenation '1' + '4' adds up to '14'

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

Domain

06 – Functions

Question 16Skipped

Q419 – Control Flow

Analyze the following code fragments

that assign a boolean value to the variable even?

  1. num = 42

  2. Code-1

  3. if num % 2 == 0:

  4. even = True
    
  5. else:

  6. even = False
    
  7. Code-2

  8. even = True if num % 2 == 0 else False

  9. Code-3

  10. even = num % 2 == 0

Code-3 has a syntax error

because you attempt to assign a number to even

Explanation

Code-3 does not have a syntax error, as it correctly assigns the result of the condition evaluation to the variable even. There is no attempt to assign a number to even in this code fragment.

Code-2 has a syntax error

because you cannot have True and False literals

in the conditional expression.

Explanation

Code-2 does not have a syntax error, as it correctly uses True and False literals in the ternary conditional expression. These literals are valid in Python and can be used to assign boolean values based on a condition.

Correct answer

All three are correct, but Code-3 is preferred.

Explanation

All three code fragments correctly assign a boolean value to the variable even based on whether num is even or not. However, Code-3 is preferred as it directly assigns the result of the condition evaluation, making the code more concise and readable.

All three are correct, but Code-1 is preferred.

Explanation

All three code fragments correctly assign a boolean value to the variable even based on whether num is even or not. Code-1 is preferred by some developers as it explicitly uses an if-else statement for clarity and readability.

All three are correct, but Code-2 is preferred.

Explanation

All three code fragments correctly assign a boolean value to the variable even based on whether num is even or not. Code-2 is preferred by some developers as it uses a more concise ternary conditional expression, making the code more compact.

Overall explanation

Topics: if else modulus operator format()

Try it yourself:

  1. num = 42

  2. Code-1

  3. if num % 2 == 0:

  4. even = True
    
  5. else:

  6. even = False
    
  7. Code-2

  8. even = True if num % 2 == 0 else False

  9. Code-3

  10. even = num % 2 == 0

Explanation:

They all work without a syntax error but Code-3 is preferred.

The condition num % 2 == 0 evaluates to a boolean

and therefore that is all you need.

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

Domain

05 – Control Flow

Question 17Skipped

Q415 – Operators

What is the expected output of the following code?

  1. a = 1
  2. b = 0
  3. c = a & b
  4. d = a | b
  5. e = a ^ b
  6. print(c + d + e)

0

Explanation

The bitwise AND operator (&) compares the binary representation of the numbers and returns a 1 only if both bits are 1. In this case, a = 1 (binary: 01) and b = 0 (binary: 00), so c = a & b results in 0. The bitwise OR operator (|) returns 1 if at least one of the bits is 1, so d = a | b results in 1. The bitwise XOR operator (^) returns 1 if the bits are different, so e = a ^ b results in 1. Adding c, d, and e together (0 + 1 + 1) does not result in 0.

1

Explanation

The bitwise AND operator (&) compares the binary representation of the numbers and returns a 1 only if both bits are 1. In this case, a = 1 (binary: 01) and b = 0 (binary: 00), so c = a & b results in 0. The bitwise OR operator (|) returns 1 if at least one of the bits is 1, so d = a | b results in 1. The bitwise XOR operator (^) returns 1 if the bits are different, so e = a ^ b results in 1. Adding c, d, and e together (0 + 1 + 1) does not result in 1.

3

Explanation

The bitwise AND operator (&) compares the binary representation of the numbers and returns a 1 only if both bits are 1. In this case, a = 1 (binary: 01) and b = 0 (binary: 00), so c = a & b results in 0. The bitwise OR operator (|) returns 1 if at least one of the bits is 1, so d = a | b results in 1. The bitwise XOR operator (^) returns 1 if the bits are different, so e = a ^ b results in 1. Adding c, d, and e together (0 + 1 + 1) does not result in 3.

Correct answer

2

Explanation

The bitwise AND operator (&) compares the binary representation of the numbers and returns a 1 only if both bits are 1. In this case, a = 1 (binary: 01) and b = 0 (binary: 00), so c = a & b results in 0. The bitwise OR operator (|) returns 1 if at least one of the bits is 1, so d = a | b results in 1. The bitwise XOR operator (^) returns 1 if the bits are different, so e = a ^ b results in 1. Adding c, d, and e together (0 + 1 + 1) gives the expected output of 2.

Overall explanation

Topics: bitwise operators (and, or, xor)

Try it yourself:

  1. a = 1

  2. b = 0

  3. c = a & b

  4. d = a | b

  5. e = a ^ b

  6. print(c + d + e) # 2

  7. print(1 & 0) # 0

  8. print(1 | 0) # 1

  9. print(1 ^ 0) # 1

Explanation:

1 and 0 is 0

1 or 0 is 1

1 xor 0 is 1

The total is 2

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

Domain

03 – Operators

Question 18Skipped

Q449 – Control Flow

You are creating a Python script to evaluate input

and check for upper and lower case.

Code segment 1:

  1. else:
  2. print(name, ‘is mixed case.’)

Code segment 2:

  1. else:
  2. print(name, 'is lower case.')
    

Code segment 3:

  1. name = input(‘Enter your name: ‘)

Code segment 4:

  1. else:
  2. print(name, 'is upper case.')
    

Code segment 5:

  1. elif name.upper() == name:
  2. print(name, 'is all upper case.')
    

Code segment 6:

  1. if name.lower() == name:
  2. print(name, 'is all lower case.')
    

Which four code segments should you use to develop the solution?

Correct answer

Code segment 3

Code segment 6

Code segment 5

Code segment 1

Explanation

Code segment 3 is necessary to prompt the user to enter their name. Code segment 6 checks if the input name is all lower case. Code segment 5 checks if the input name is all upper case. Code segment 1 handles the case where the input name is mixed case.

Code segment 3

Code segment 6

Code segment 5

Code segment 4

Explanation

Code segment 4 is incorrect as it is not needed for the solution. Code segment 3 is necessary to prompt the user to enter their name. Code segment 6 checks if the input name is all lower case. Code segment 5 checks if the input name is all upper case.

Code segment 3

Code segment 6

Code segment 5

Code segment 2

Explanation

Code segment 2 is incorrect as it is not needed for the solution. Code segment 3 is necessary to prompt the user to enter their name. Code segment 6 checks if the input name is all lower case. Code segment 5 checks if the input name is all upper case.

Code segment 1

Code segment 3

Code segment 5

Code segment 6

Explanation

Code segment 1 is incorrect as it is missing the necessary input prompt. Code segment 3 is necessary to prompt the user to enter their name. Code segment 5 checks if the input name is all upper case. Code segment 6 checks if the input name is all lower case.

Overall explanation

Topics: if elif else input() lower() upper()

Try it yourself:

  1. name = input(‘Enter your name: ‘)

  2. name = ‘peter’ # peter is all lower case.

  3. name = ‘PETER’ # PETER is all upper case.

  4. name = ‘Peter’ # Peter is mixed case.

  5. if name.lower() == name:

  6. print(name, 'is all lower case.')
    
  7. elif name.upper() == name:

  8. print(name, 'is all upper case.')
    
  9. else:

  10. print(name, 'is mixed case.')
    

Explanation:

First you need the input()

Then you need the if

Then you need the elif

There are three code segments with an else clause.

'lower' was in the if clause.

'upper' was in the elif clause.

That leaves 'mixed' for the else clause.

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

Domain

05 – Control Flow

Question 19Skipped

Q451 – Operators

Evaluate the following Python arithmetic expression:

(3 * (1 + 2) ** 2 - (2 ** 2) * 3)

What is the result?

69

Explanation

This choice is incorrect because the result of the given Python arithmetic expression is not 69. The correct result is 15, which is obtained by correctly simplifying and calculating the expression step by step following the order of operations.

Correct answer

15

Explanation

The correct result of the given Python arithmetic expression is 15. To calculate this, we first need to evaluate the inner parentheses, which are (1 + 2) and (2 ** 2). This simplifies the expression to (3 * 3 ** 2 – 4 * 3). Then, we calculate the exponentiation (3 ** 2 = 9) and multiplication (3 * 9 = 27) in the first part of the expression. Finally, we calculate the multiplication in the second part of the expression (4 * 3 = 12) and subtract it from the result of the first part (27 – 12 = 15).

3

Explanation

This choice is incorrect because the result of the given Python arithmetic expression is not 3. The correct result is 15, which is obtained by following the order of operations and evaluating the expression step by step.

13

Explanation

This choice is incorrect because the result of the given Python arithmetic expression is not 13. The correct result is 15, which is calculated by correctly evaluating the expression according to the order of operations and mathematical rules.

Overall explanation

Topics: addition operator subtraction operator

multiplication operator exponentiation operator

parentheses operator precedence

Try it yourself:

  1. print((3 * (1 + 2) ** 2 – (2 ** 2) * 3)) # 15
  2. print(3 * 3 ** 2 – (2 ** 2) * 3) # 15
  3. print(3 * 3 ** 2 – 4 * 3) # 15
  4. print(3 * (3 ** 2) – 4 * 3) # 15
  5. print((3 * 9) – 4 * 3) # 15
  6. print(27 – 4 * 3) # 15
  7. print(27 – (4 * 3)) # 15
  8. print(27 – 12) # 15
  9. print(15) # 15

Explanation:

The order of operator precedence here is:

Parantheses

Exponentiation operator

Multiplication operator

Subtraction operator

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

Domain

03 – Operators

Question 20Skipped

Q435 – Functions

What is the expected output of the following code?

  1. def get_names():

  2. names = ['Peter', 'Paul', 'Mary', 'Jane', 'Steve']
    
  3. return names[2:]
    
  4. def update_names(names):

  5. res = []
    
  6. for name in names:
    
  7.     res.append(name[:3].upper())
    
  8. return res
    
  9. print(update_names(get_names()))

['JA', 'ST']

Explanation

This choice is incorrect because it assumes that the update_names() function will only include the first two characters of each name in uppercase. However, the function processes each name in the list returned by get_names() starting from ‘Mary’, so the output will include ‘MAR’, ‘JAN’, and ‘STE’.

Correct answer

['MAR', 'JAN', 'STE']

Explanation

The get_names() function returns a list starting from the third element (‘Mary’) to the end of the list. The update_names() function then iterates over each name in the list and appends the first three characters of each name in uppercase to a new list. Therefore, the expected output is [‘MAR’, ‘JAN’, ‘STE’].

['JAN', 'STE']

Explanation

This choice is incorrect because it does not consider that the get_names() function returns a list starting from the third element (‘Mary’) to the end of the list. The update_names() function then processes each name in this list, so the output will include all names from ‘Mary’ to ‘Steve’.

['MA', 'JA', 'ST']

Explanation

This choice is incorrect because it assumes that the update_names() function will only include the first two characters of each name in uppercase. However, the function processes each name in the list returned by get_names() starting from ‘Mary’, so the output will include ‘MAR’, ‘JAN’, and ‘STE’.

Overall explanation

Topics: def list slicing for append() upper()

Try it yourself:

  1. def get_names():

  2. names = ['Peter', 'Paul', 'Mary', 'Jane', 'Steve']
    
  3. return names[2:]
    
  4. def update_names(names):

  5. res = []
    
  6. for name in names:
    
  7.     res.append(name[:3].upper())
    
  8. return res
    
  9. print(update_names(get_names())) # [‘MAR’, ‘JAN’, ‘STE’]

Explanation:

The slicing in get_names() is a list slicing: names[2:]

It has a start of 2 and no end.

That means, the slicing goes from the second index (inclusive) to the end.

That will be ['Mary', 'Jane', 'Steve']

That list will be passed to the update_names() function.

The other slicing inside the for loop is a string slicing,

that will slice every element of the list

name[:3] will slice from the start to the index 3 (exclusive).

Meaning it takes the first three letters.

The upper() method will then convert those letters to uppercase letters.

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

Domain

06 – Functions

Question 21Skipped

Q429 – Control Flow

What is the expected output of the following code?

  1. x = (1, 4, 7, 9, 10, 11)
  2. y = {2: ‘A’, 4: ‘B’, 6: ‘C’, 8: ‘D’, 10: ‘E’, 12: ‘F’}
  3. res = 1
  4. for z in x:
  5. if z in y:
    
  6.     res += z
    
  7. print(res)

None of the above.

Explanation

This choice is incorrect as the code does produce an output. Since elements 4 and 10 from tuple x are present in dictionary y, the output will be a sum of 1 + 4 + 10 = 15. Therefore, the correct output is one of the given choices, not "None of the above."

6

Explanation

This choice is incorrect because it does not consider the correct logic of adding the values of elements in tuple x that are also keys in dictionary y. The output will not be 6 based on the provided code.

14

Explanation

This choice is incorrect because it does not accurately calculate the sum of the values of elements in tuple x that are also keys in dictionary y. The output will not be 14 based on the provided code.

Correct answer

15

Explanation

The code iterates through the elements in tuple x and checks if each element is a key in dictionary y. If the element is found in y, its value is added to the variable res. The elements 4 and 10 from tuple x are present in dictionary y with values ‘B’ and ‘E’ respectively. Therefore, the expected output is 1 + 4 + 10 = 15.

22

Explanation

This choice is incorrect as it does not correctly calculate the sum of the values of elements in tuple x that are also keys in dictionary y. The output will not be 22 based on the provided code.

Overall explanation

Topics: tuple dictionary for if

Try it yourself:

  1. x = (1, 4, 7, 9, 10, 11)
  2. y = {2: ‘A’, 4: ‘B’, 6: ‘C’, 8: ‘D’, 10: ‘E’, 12: ‘F’}
  3. res = 1
  4. for z in x:
  5. if z in y:
    
  6.     print('z:', z)  # 4 -> 10
    
  7.     res += z
    
  8. print(res) # 15

Explanation:

With values in the tuple or also indexes in the dictionary?

4 + 10 -> 14

The result starts at 1

Makes 15 in total.

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

Domain

05 – Control Flow

Question 22Skipped

Q413 – Operators

What is the expected output of the following code?

print(1 // 2)

Correct answer

0

Explanation

The ‘//’ operator in Python is used for floor division, which means it returns the integer part of the division result. In this case, 1 divided by 2 results in 0 with no remainder, so the expected output is 0.

None of the above.

Explanation

This choice is incorrect because the output of the code is not None. The ‘//’ operator in Python always returns an integer value, so the output will be a valid integer result.

0.0

Explanation

This choice is incorrect because the ‘//’ operator performs floor division, which always returns an integer result. It does not return a float or decimal value like 0.0.

0.5

Explanation

This choice is incorrect because the ‘//’ operator in Python specifically performs floor division, which means it always returns the integer part of the division result. It does not return a float or decimal value like 0.5.

Overall explanation

Topic: floor division operator

Try it yourself:

  1. print(1 // 2) # 0
  2. print(1.0 // 2) # 0.0
  3. print(1 // 2.0) # 0.0
  4. print(1.0 // 2.0) # 0.0

Explanation:

If both operands are an integer the floor division operator will return an integer

If at least one operand is a float the result will also be a float

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

Domain

03 – Operators

Question 23Skipped

Q446 – I/O

Presume f is a file opened in read mode.

What will be the type of data after the following line?

data = f.readlines()

Correct answer

list

Explanation

The readlines() method in Python reads all lines from the file and returns them as a list. Therefore, the type of data after the line data = f.readlines() will be a list, containing each line of the file as an element.

tuple

Explanation

The readlines() method in Python returns the lines of the file as a list, not a tuple. Therefore, the type of data after the line data = f.readlines() will be a list, not a tuple.

string

Explanation

The readlines() method in Python returns the lines of the file as a list, not a single string. Therefore, the type of data after the line data = f.readlines() will be a list, not a string.

dictionary

Explanation

The readlines() method in Python returns the lines of the file as a list, not a dictionary. Therefore, the type of data after the line data = f.readlines() will be a list, not a dictionary.

Overall explanation

Topics: readlines()

Try it yourself:

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

  2. text = ”’Peter

  3. Paul

  4. Mary

  5. ”’

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

  7. f.write(text)
    
  8. f = open(‘index.txt’, ‘r’)

  9. data = f.readlines()

  10. print(data) # [‘Peter\n’, ‘Paul\n’, ‘Mary\n’]

  11. print(type(data)) # <class ‘list’>

  12. f.close()

Explanation:

All you need to know here is,

that the readlines() method returns a list

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

Domain

07 – I/O

Question 24Skipped

Q447 – I/O

What is the expected output of the following code?

  1. file = open(‘data.txt’, ‘r’)
  2. txt = "I’m gonna make him an offer he can’t refuse."
  3. file.writelines(txt)
  4. file.seek(0)
  5. lines = file.readlines()
  6. print(lines)
  7. file.close()

Correct answer

The code is erroneous.

Explanation

The code is erroneous because it attempts to write to a file that was opened in read mode (‘r’). This will result in a ‘UnsupportedOperation’ error when trying to write to the file.

[]

Explanation

The code will not produce an empty list because the file was not successfully written to due to the mode mismatch.

None

Explanation

The code will not output ‘None’ as the file was not successfully written to due to the mode mismatch.

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

Explanation

The code will not output the text "I’m gonna make him an offer he can’t refuse." as the file was not successfully written to due to the mode mismatch.

Overall explanation

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

Try it yourself:

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

  3. txt = "I’m gonna make him an offer he can’t refuse."
  4. file.writelines(txt) # io.UnsupportedOperation: not writable
  5. file.seek(0)
  6. lines = file.readlines()
  7. print(lines)
  8. file.close()

Explanation:

The mode of the open() function is wrong.

It needs to be r+ or w+

Both would allow reading and writing.

But the mode r opens the file in readonly mode

and then you can not write to the file.

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

Domain

07 – I/O

Question 25Skipped

Q426 – Operators

What is the expected output of the following code?

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

  2. list2 = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]

  3. print(list1 is not list2)

  4. print(list1 != list2)

  5. list1 = list2

  6. print(list1 is not list2)

  7. print(list1 != list2)

  8. True

  9. False

  10. False

  11. True

Explanation

The ‘is not’ operator checks if two variables refer to the same object in memory. Since list1 and list2 are separate lists with the same values, the output of ‘list1 is not list2’ will be True. The ‘!=’ operator checks if the values of the two lists are equal, which they are in this case, so the output of ‘list1 != list2’ will be False. After assigning list2 to list1, they both refer to the same object in memory, so ‘list1 is not list2’ will be False. Since the values of list1 and list2 are still equal, ‘list1 != list2’ will be True.

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

Explanation

The ‘is not’ operator checks if two variables refer to the same object in memory. Since list1 and list2 are separate lists with the same values, the output of ‘list1 is not list2’ will be True. The ‘!=’ operator checks if the values of the two lists are equal, which they are in this case, so the output of ‘list1 != list2’ will be False. After assigning list2 to list1, they both refer to the same object in memory, so ‘list1 is not list2’ will be False. Since the values of list1 and list2 are still equal, ‘list1 != list2’ will be True.

Correct answer

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

Explanation

The ‘is not’ operator checks if two variables refer to the same object in memory. Since list1 and list2 are separate lists with the same values, the output of ‘list1 is not list2’ will be True. The ‘!=’ operator checks if the values of the two lists are equal, which they are in this case, so the output of ‘list1 != list2’ will be False. After assigning list2 to list1, they both refer to the same object in memory, so ‘list1 is not list2’ will be False. Since the values of list1 and list2 are still equal, ‘list1 != list2’ will be False.

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

Explanation

The ‘is not’ operator checks if two variables refer to the same object in memory. Since list1 and list2 are separate lists with the same values, the output of ‘list1 is not list2’ will be True. The ‘!=’ operator checks if the values of the two lists are equal, which they are in this case, so the output of ‘list1 != list2’ will be True. After assigning list2 to list1, they both refer to the same object in memory, so ‘list1 is not list2’ will be False. Since the values of list1 and list2 are still equal, ‘list1 != list2’ will be False.

Overall explanation

Topics: list not equal to operator not identity operator

Try it yourself:

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

  2. list2 = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]

  3. print(list1 is not list2) # True

  4. print(list1 != list2) # False

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

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

  7. list1 = list2

  8. print(list1 is not list2) # False

  9. print(list1 != list2) # False

  10. print(id(list1)) # e.g. 140539383900864

  11. print(id(list2)) # e.g. 140539383900864 (the same number)

Explanation:

list is a mutable data type.

The second list will be a different object, although the values are the same.

When list2 gets assigned to list1 Python creates a reference.

From now on the two list have the same identity and the same values.

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

Domain

03 – Operators

Question 26Skipped

Q405 – Data Aggregates

What is the expected output of the following code?

  1. data1 = ‘a’, ‘b’
  2. data2 = (‘a’, ‘b’)
  3. print(data1 == data2)

0

Explanation

The output will not be 0 because the comparison of data1 and data2 will result in True, not in an integer value.

Correct answer

True

Explanation

The expected output of the code is True because both data1 and data2 contain the same values ‘a’ and ‘b’, even though they are defined using different syntaxes (tuple with parentheses and tuple without parentheses).

False

Explanation

The output will not be False because data1 and data2 have the same values ‘a’ and ‘b’, so the comparison will result in True.

1

Explanation

The output will not be 1 because the comparison of data1 and data2 will result in True, not in an integer value.

Overall explanation

Topics: tuple equal to operator

Try it yourself:

  1. data1 = ‘a’, ‘b’
  2. data2 = (‘a’, ‘b’)
  3. print(data1 == data2) # True
  4. print(data1 is data2) # True
  5. print(id(data1)) # e.g. 140539383900864
  6. print(id(data2)) # e.g. 140539383900864 (the same number)

Explanation:

You do not need the parentheses to create a tuple

The second tuple will be exactly the same.

And because a tuple is immutable the second tuple will reference

to the same object than the first tuple

And sure, their value will be the same, too.

is tests for identity of the object.

== tests for equality of the values.

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

Domain

04 – Data Aggregates

Question 27Skipped

Q448 – Error Handling

Consider the file peoples.txt:

  1. Peter:10
  2. Paul:20
  3. Mary:30
  4. Jane:40

What is the expected output of the following code?

(The code is in a file in the same directory than peoples.txt)

  1. points = 0
  2. try:
  3. file = open('peoples.txt', 'r')
    
  4. data = file.readlines()
    
  5. for d in data:
    
  6.     points += float(d.split(':')[1])
    
  7. file.close()
    
  8. print(points)
    
  9. except:
  10. print('The file could not be opened!')
    

10.0

Explanation

This choice is incorrect because the expected output of the code is not the points of the first person (10.0), but the total sum of all points (100.0).

The file could not be opened!

Explanation

This choice is incorrect because the code successfully opens the ‘peoples.txt’ file, reads the data, calculates the total points, and prints the sum. The ‘except’ block is only executed if there is an error opening the file, which is not the case in this scenario.

100

Explanation

This choice is incorrect because the expected output of the code is not just the sum of points (100), but the sum as a floating-point number (100.0).

Correct answer

100.0

Explanation

The code successfully opens the ‘peoples.txt’ file, reads the data line by line, splits each line by ‘:’, and adds the points as floating numbers. The total sum of points is 100.0, which is the expected output.

Overall explanation

Topics: try except open() readlines() for float()

split() BaseException

Try it yourself:

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

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

  3. f.write('Peter:10\nPaul:20\nMary:30\nJane:40')
    
  4. points = 0

  5. try:

  6. file = open('peoples.txt', 'r')
    
  7. data = file.readlines()
    
  8. # Reads all lines and puts them in a list
    
  9. print('content:', data)
    
  10. # ['Peter:10\n', 'Paul:20\n', 'Mary:30\n', 'Jane:40']
    
  11. for d in data:
    
  12.     print('d:', d)
    
  13.     # Peter:10 -> Paul:20 -> Mary:30 -> Jane:40
    
  14.     print("d.split(':')[1]:", d.split(':')[1])
    
  15.     # 10 -> 20 -> 30 -> 40
    
  16.     points += float(d.split(':')[1])
    
  17.     # 10.0 + 20.0 + 30.0 + 40.0 -> 100.0
    
  18. file.close()
    
  19. print(points)
    
  20. except:

  21. print('The file could not be opened!')
    

Explanation:

Everything will work fine.

readlines() will return a list with all the single lines of the file.

The for loop will iterate through that list

Every element will be splitted in the part before and after the semicolon.

The part after the semicolon is the number as a string

The float() function will cast that to a float

Those floats will be added to the existing points.

In the end it will be 100.0 points.

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

Domain

08 – Error Handling

Question 28Skipped

Q414 – Data Types

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

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

Correct answer

0

Explanation

The code first takes two integer inputs from the user and assigns them to variables x and y. Then, it performs modulo operation on x with y twice, which results in x being 1. Next, it calculates y modulo x, which is 0. Therefore, the expected output is 0.

2

Explanation

This choice is incorrect as the code does not lead to y being 2 when the user enters 3 and 2 as inputs. The final calculation results in y being 0, not 2.

1

Explanation

This choice is incorrect because the code does not result in y being 1 when the user enters 3 and 2 as inputs. The calculations lead to y being 0, not 1.

3

Explanation

This choice is incorrect because the code does not result in y being 3 when the user enters 3 and 2 as inputs. The calculations lead to y being 0, not 3.

Overall explanation

Topics: input() int() modulus operator

Try it yourself:

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

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

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

Explanation:

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

Then there is a lot of the modulus operator but you just have to concentrate.

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

Domain

02 – Data Types

Question 29Skipped

Q443 – Error Handling

What is the expected output of the following code?

  1. try:

  2. print('try')
    
  3. print(10 / 0)
    
  4. except:

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

  7. print('else')
    
  8. finally:

  9. print('finally')
    
  10. try

  11. else

  12. finally

Explanation

The code will print ‘try’ as it enters the try block. Since an exception occurs during the division by 0, it will not reach the else block. However, it will execute the finally block and print ‘finally’.

  1. except
  2. finally

Explanation

The code will print ‘try’ as it enters the try block. It will then encounter a ZeroDivisionError, causing it to jump to the except block and print ‘except’. Finally, it will execute the finally block and print ‘finally’.

  1. try
  2. finally

Explanation

The code will print ‘try’ as it enters the try block. It will then encounter a ZeroDivisionError, causing it to jump to the finally block and print ‘finally’. The else block will be skipped as there is an exception.

  1. try
  2. except
  3. else
  4. finally

Explanation

The code will print ‘try’ as it enters the try block. It will then jump to the except block due to the ZeroDivisionError, printing ‘except’. Since there is no exception in the else block, it will be skipped. Finally, the code will execute the finally block and print ‘finally’.

Correct answer

  1. try
  2. except
  3. finally

Explanation

The code will first print ‘try’ as it enters the try block. Then, it will encounter a ZeroDivisionError while trying to divide 10 by 0, causing it to jump to the except block and print ‘except’. Finally, it will execute the finally block and print ‘finally’.

Overall explanation

Topics: try except else finally ZeroDivisionError

Try it yourself:

  1. try:

  2. print('try')      # try
    
  3. print(10 / 0)
    
  4. except:

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

  7. print('else')
    
  8. finally:

  9. print('finally')  # finally
    
  10. print(10 / 0) # ZeroDivisionError: division by zero

Explanation:

You can not divide by zero (ZeroDivisionError).

The printing of 'try' will succeed.

The division by zero will raise an exception (ZeroDivisionError)

Because of the raised exception,

the except block will execute and print 'except'

Like always the finally block gets executed and will print 'finally'

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

Domain

08 – Error Handling

Question 30Skipped

Q406 – Data Aggregates

What is the expected output of the following code?

  1. x = {(1, 2): 1, (2, 3): 2}
  2. print(x[1, 2])

Correct answer

1

Explanation

The expected output of the code is 1 because the key (1, 2) is present in the dictionary x and its corresponding value is 1.

{(2, 3): 2}

Explanation

This choice is incorrect because the output of the code is not a dictionary with the key-value pair {(2, 3): 2}. The code is trying to access the value associated with the key (1, 2), not (2, 3).

{(1, 2): 1}

Explanation

This choice is incorrect because the output of the code is not a dictionary with the key-value pair {(1, 2): 1}. Instead, the output is the value associated with the key (1, 2) in the dictionary x, which is 1.

The code is erroneous.

Explanation

This choice is incorrect because the code is not erroneous. It is accessing the value associated with the key (1, 2) in the dictionary x, which is a valid operation.

Overall explanation

Topics: dictionary indexing

Try it yourself:

  1. x = {(1, 2): 1, (2, 3): 2}
  2. print(x[1, 2]) # 1
  3. print(x[(1, 2)]) # 1

Explanation:

Yes, a tuple can be the index of a dictionary

And calling it you can (like often) leave out the parentheses.

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

Domain

04 – Data Aggregates

Question 31Skipped

Q454 – Error Handling

An assertion can be used to:

Make the Programmer more assertive.

Explanation

An assertion in Python is not used to make the programmer more assertive. Instead, it is a programming construct that helps ensure the correctness of the code by checking conditions and stopping the program if those conditions are not met.

Correct answer

Stop the programm when some data have improper values.

Explanation

An assertion in Python is used to stop the program’s execution when certain conditions are not met, such as when data have improper values. It helps the programmer identify and address issues in the code by halting the program when unexpected situations occur.

Import a module.

Explanation

Importing a module in Python is a separate concept from using assertions. While importing modules allows access to external functionality and resources, assertions are specifically used for error handling and debugging purposes within the code itself.

Overall explanation

Topic: assertion assert

Try it yourself:

  1. def remove_min(s):

  2. assert type(s) == list
    
  3. assert len(s) > 0
    
  4. m = min(s)
    
  5. s.remove(m)
    
  6. return s
    
  7. print(remove_min([1, 2, 3])) # [2, 3]

  8. print(remove_min(‘Hello’)) # … AssertionError

  9. print(remove_min([])) # … AssertionError

Explanation:

The function remove_min() removes the minimal value from a list.

First the function checks, whether the argument is a list

and second the function checks, whether that list has elements.

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

Domain

08 – Error Handling

Question 32Skipped

Q440 – Basics

The pyc file contains …

Python source code.

Explanation

A pyc file does not contain Python source code. Instead, it contains the compiled Python bytecode that is generated from the source code. The source code is the human-readable version of the program, while the pyc file contains the optimized bytecode for execution.

a Python interpreter.

Explanation

A pyc file does not contain a Python interpreter. The Python interpreter is the program that reads and executes Python bytecode stored in the pyc file, translating it into machine code that the computer can understand and execute.

a Python compiler.

Explanation

A pyc file does not contain a Python compiler. The Python compiler is responsible for converting Python source code into Python bytecode, which is then stored in the pyc file for future use by the interpreter.

Correct answer

compiled Python bytecode.

Explanation

The pyc file contains compiled Python bytecode, which is generated by the Python interpreter when a Python source file is imported or executed. This bytecode is platform-independent and can be executed faster than interpreting the source code directly.

Overall explanation

Topic: pyc

Try it yourself:

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

  2. functions = ”’

  3. def func():

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

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

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

  9. import functions

  10. functions.func()

  11. ”’

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

  13. f.write(index)
    

Explanation:

First please check, if the files index.py

and functions.py are created as expected.

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

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

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

This file contains compiled Python bytecode.

Next time you run index.py Python will use

the compiled bytecode for faster execution.

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

Domain

01 – Basics

Question 33Skipped

Q428 – Data Types

You want the name, the user puts in to be written back to the monitor.

What snippet would you insert in the line indicated below:

  1. print(‘Enter Your Name: ‘)
  2. insert your code here

  3. print(name)

input(name)

Explanation

The input(name) function is incorrect because it tries to use the variable ‘name’ as a prompt for the user input, which is not the intended functionality. This would result in an error as ‘name’ is not defined as a string prompt.

name = input

Explanation

The name = input() function is missing the prompt for the user to enter their name. Without a clear prompt, the user may not know what input is expected, leading to confusion. The correct approach is to include a prompt within the input() function.

input('name')

Explanation

The input(‘name’) function is incorrect because it prompts the user to enter their name but does not assign the input to any variable. This would result in the user input being lost and not displayed on the monitor as intended.

Correct answer

name = input()

Explanation

The correct choice is to use the input() function to capture the user’s input and assign it to the variable ‘name’. This allows the user to enter their name, which is then stored in the ‘name’ variable and can be printed back to the monitor.

Overall explanation

Topic: input()

Try it yourself:

  1. print(‘Enter Your Name: ‘)
  2. name = input()
  3. print(name)

Explanation:

The input() function allows user input.

Here you just ask for the name and directly print it.

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

Domain

02 – Data Types

Question 34Skipped

Q453 – Error Handling

Which of the approachable except: branches

is taken into consideration when an exception occurs?

Correct answer

The first matching branch.

Explanation

In Python, when an exception occurs, the interpreter goes through the except: branches in the order they are defined in the code. The first matching branch that can handle the specific exception is executed, and the interpreter does not continue to check the remaining branches. This is why the first matching branch is the one taken into consideration when an exception occurs.

The last matching branch.

Explanation

In Python, the except: branches are evaluated in the order they are defined in the code. If an exception occurs, the interpreter will go through each branch sequentially until it finds a matching branch that can handle the specific exception. Therefore, the last matching branch is not the one taken into consideration when an exception occurs.

Any of the matching branches.

Explanation

When an exception occurs in Python, the interpreter will go through the except: branches in the order they are defined in the code. Any of the matching branches that can handle the specific exception will be executed. However, it is important to note that once a matching branch is found and executed, the interpreter does not continue to check the remaining branches.

Overall explanation

Topic: except

Try it yourself:

  1. try:

  2. zahl = 100 / 0
    
  3. except ArithmeticError:

  4. print('ArithmeticError')  # ArithmeticError
    
  5. except ZeroDivisionError:

  6. print('ZeroDivisionError')
    
  7. try:

  8. zahl = 100 / 0
    
  9. except ZeroDivisionError:

  10. print('ZeroDivisionError')  # ZeroDivisionError
    
  11. except ArithmeticError:

  12. print('ArithmeticError')
    
  13. print(issubclass(ZeroDivisionError, ArithmeticError)) # True

Explanation:

The ZeroDivisionError is a subclass of the ArithmeticError

Therefore here they are both approachable except: branches.

And the first match is taken into consideration.

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

Domain

08 – Error Handling

Question 35Skipped

Q444 – Control Flow

How much will the delivery cost be,

if the order value is 1700 and the state is FL (Florida)?

  1. order = int(input(‘Please enter the order value: ‘))

  2. state = input(‘Please enter the state (as postal abbreviation): ‘)

  3. delivery = 0

  4. if state in [‘NC’, ‘SC’, ‘VA’]:

  5. if order <= 1000:
    
  6.     delivery = 70
    
  7. elif 1000 < order < 2000:
    
  8.     delivery = 80
    
  9. else:
    
  10.     delivery = 90
    
  11. else:

  12. delivery = 50
    
  13. if state in [‘GA’, ‘WV’, ‘FL’]:

  14. if order > 1000:
    
  15.     delivery += 30
    
  16. if order < 2000 and state in ['WV', 'FL']:
    
  17.     delivery += 40
    
  18. else:
    
  19.     delivery += 25
    
  20. print(delivery)

Correct answer

120

Explanation

The delivery cost will be 120 if the order value is 1700 and the state is FL (Florida). This is because the initial delivery cost is calculated based on the state being FL, which adds 50. Then, since the order value is greater than 1000, an additional 30 is added. Finally, since the order value is less than 2000 and the state is FL, an extra 40 is added, resulting in a total delivery cost of 120.

80

Explanation

The delivery cost will not be 80 if the order value is 1700 and the state is FL (Florida). The correct calculation based on the provided code results in a delivery cost of 120, not 80.

105

Explanation

The delivery cost will not be 105 if the order value is 1700 and the state is FL (Florida). The correct calculation based on the provided code results in a delivery cost of 120, not 105.

90

Explanation

The delivery cost will not be 90 if the order value is 1700 and the state is FL (Florida). The correct calculation based on the provided code results in a delivery cost of 120, not 90.

Overall explanation

Topics: if elif else list membership Operator less than operator

greater than operator less than or equal to operator

add and assign operator chained comparison

Try it yourself:

  1. order = int(input(‘Please enter the order value: ‘))

  2. state = input(‘Please enter the state (as postal abbreviation): ‘)

  3. order, state = int(‘1700’), ‘FL’ # Just for convenience

  4. delivery = 0

  5. if state in [‘NC’, ‘SC’, ‘VA’]:

  6. if order <= 1000:
    
  7.     delivery = 70
    
  8. elif 1000 < order < 2000:
    
  9.     delivery = 80
    
  10. else:
    
  11.     delivery = 90
    
  12. else:

  13. delivery = 50
    
  14. print('1. delivery', delivery)      # 50
    
  15. if state in [‘GA’, ‘WV’, ‘FL’]:

  16. if order > 1000:
    
  17.     delivery += 30
    
  18.     print('2. delivery', delivery)  # 80
    
  19. if order < 2000 and state in ['WV', 'FL']:
    
  20.     delivery += 40
    
  21.     print('3. delivery', delivery)  # 120
    
  22. else:
    
  23.     delivery += 25
    
  24. print(delivery) # 120

Explanation:

FL is not in ['NC', 'SC', 'VA']

Therefore the else clause executes and the delivery costs start at 50

FL is in ['GA', 'WV', 'FL']

The order value is greater than 1000

That adds another 30 delivery costs.

The order value is less than 2000 and FL is in ['WV', 'FL']

That adds another 40 to the delivery costs.

50 + 30 + 40 -> 120

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

Domain

05 – Control Flow

Question 36Skipped

Q420 – Control Flow

Consider the following code.

  1. room = input(‘Enter the room number: ‘)
  2. rooms = {101: ‘Gathering Place’, 102: ‘Meeting Room’}
  3. if not room in rooms:
  4. print('The room doesn\'t exist.')
    
  5. else:
  6. print('The room name is: ' + rooms[room])
    

Why is it not working?

Invalid Syntax

Explanation

There is no syntax error in the code provided. The syntax is correct, but the issue lies in the data type mismatch between the input from the user and the keys in the dictionary.

Correct answer

Mismatched data type(s)

Explanation

The issue in the code is related to data types. The input function returns a string, while the keys in the rooms dictionary are integers. This causes a mismatch in data types, leading to the condition not being satisfied.

None of the above.

Explanation

The issue in the code is not due to any of the options listed. The problem lies in the mismatched data types between the input from the user (which is a string) and the keys in the dictionary (which are integers).

Misnamed variable(s)

Explanation

There are no misnamed variables in the code. The variables ‘room’ and ‘rooms’ are correctly named and used in the code. The problem is not related to variable names.

Overall explanation

Topics: if else dictionary membership operator

Try it yourself:

  1. room = input(‘Enter the room number: ‘)

  2. room = ‘101’ # Just for convenience
  3. rooms = {101: ‘Gathering Place’, 102: ‘Meeting Room’}
  4. if not room in rooms:
  5. # if room not in rooms:
    
  6. print('The room does not exist.')
    
  7. else:
  8. print('The room name is: ' + rooms[room])
    

Explanation:

The reason, why the code will never find a room is,

that input() always returns a string

and the indexes of the dictionary are all an integer

not room in rooms is not very good code.

Better is room not in rooms

But it is not a syntax error (like it would be in other languages).

In Python it is "only" a violation against the Python coding conventions

(In this case PEP8 E713).

Look also here: https://stackoverflow.com/questions/17659303/what-is-more-pythonic-for-not

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

Domain

05 – Control Flow

Question 37Skipped

Q427 – Data Types

The user enters 123

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

Choose three.

Correct selection

  1. num = eval(input(‘Please enter your number: ‘))
  2. print(num + 1)

Explanation

The code snippet uses the eval() function to evaluate the input as a Python expression. Since the input is ‘123’, it will be evaluated as the integer 123. Adding 1 to 123 will result in 124, which will be printed to the monitor.

Correct selection

  1. num = int(input(‘Please enter your number: ‘))
  2. print(num + 1)

Explanation

The code snippet uses the int() function to convert the input to an integer. Since the input is ‘123’, it will be converted to the integer 123. Adding 1 to 123 will result in 124, which will be printed to the monitor.

Correct selection

  1. num = input(‘Please enter your number: ‘)
  2. print(int(num) + 1)

Explanation

The code snippet uses the input() function to get the input as a string. Then, it converts the string input to an integer using int(). Since the input is ‘123’, it will be converted to the integer 123. Adding 1 to 123 will result in 124, which will be printed to the monitor.

  1. num = input(‘Please enter your number: ‘)
  2. print(num + 1)

Explanation

The code snippet uses the input() function to get the input as a string. However, it does not convert the string input to an integer before adding 1. Therefore, it will concatenate ‘1’ to ‘123’, resulting in ‘1231’ being printed to the monitor instead of 124.

Overall explanation

Topics: input() eval() int()

Try it yourself:

  1. num = eval(input(‘Please enter your number: ‘))

  2. num = eval(‘123’)

  3. print(num + 1) # 124

  4. num = int(input(‘Please enter your number: ‘))

  5. num = int(‘123’)

  6. print(num + 1) # 124

  7. num = input(‘Please enter your number: ‘)

  8. num = ‘123’

  9. print(int(num) + 1) # 124

  10. num = input(‘Please enter your number: ‘)

  11. print(num + 1) # TypeError: …

Explanation:

Like always input() returns a string

eval() runs the Python code which is passed as the argument.

The string '123' will become the integer 123

int() does the same job here.

And you can cast to an integer directly after the input or before the printing.

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

Domain

02 – Data Types

Question 38Skipped

Q401 – Functions

What does the following code do?

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

Defines an empty class.

Explanation

The code does not define a class; it defines a function. The presence of the ‘def’ keyword indicates that a function is being defined, not a class.

Defines a list and initializes it.

Explanation

The code does not define a list or initialize it; it defines a function. There is no list creation or initialization happening in the provided code snippet.

Correct answer

Defines a function, which does nothing.

Explanation

The code defines a function named ‘a’ with parameters ‘b’, ‘c’, and ‘d’, but the function body contains only the ‘pass’ statement, which means the function does nothing when called.

None of the above.

Explanation

The correct choice is A because the code snippet defines a function that does nothing. The other choices are not applicable as they do not accurately describe the functionality of the provided code.

Defines a function, which passes its parameters through.

Explanation

While the function ‘a’ does pass its parameters ‘b’, ‘c’, and ‘d’, it does not perform any specific action with them. The function simply contains the ‘pass’ statement, indicating no action is taken within the function.

Overall explanation

Topics: def pass

Try it yourself:

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

Explanation:

def a(b, c, d): defines the function

and pass just does nothing.

You can use that, when you know, that you will need a function,

but want to write the function body later on.

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

Domain

06 – Functions

Question 39Skipped

Q432 – Data Types

What is the expected output of the following code?

  1. print(not 0)

  2. print(not 23)

  3. print(not ”)

  4. print(not ‘Peter’)

  5. print(not None)

  6. False

  7. False

  8. True

  9. False

  10. True

Explanation

The ‘not’ operator in Python returns the boolean opposite of the operand. In this code snippet, the ‘not 0’ will evaluate to True because 0 is considered False in Python. However, ‘not 23’ will evaluate to False because any non-zero integer is considered True. ‘not ” ‘ will evaluate to True because an empty string is considered False. ‘not ‘Peter” will evaluate to False because a non-empty string is considered True. ‘not None’ will evaluate to True because None is considered False in Python.

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

Explanation

The ‘not’ operator in Python returns the boolean opposite of the operand. In this code snippet, the ‘not 0’ will evaluate to True because 0 is considered False in Python. Similarly, ‘not 23’ will evaluate to False because any non-zero integer is considered True. ‘not ” ‘ will evaluate to True because an empty string is considered False. ‘not ‘Peter” will evaluate to False because a non-empty string is considered True. ‘not None’ will evaluate to False because None is considered False in Python.

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

Explanation

The ‘not’ operator in Python returns the boolean opposite of the operand. In this code snippet, the ‘not 0’ will evaluate to True because 0 is considered False in Python. However, ‘not 23’ will evaluate to False because any non-zero integer is considered True. ‘not ” ‘ will evaluate to False because an empty string is considered False. ‘not ‘Peter” will evaluate to False because a non-empty string is considered True. ‘not None’ will evaluate to True because None is considered False in Python.

Correct answer

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

Explanation

The ‘not’ operator in Python returns the boolean opposite of the operand. In this code snippet, the ‘not 0’ will evaluate to True because 0 is considered False in Python. Similarly, ‘not 23’ will evaluate to False because any non-zero integer is considered True. ‘not ” ‘ will evaluate to True because an empty string is considered False. ‘not ‘Peter” will evaluate to False because a non-empty string is considered True. ‘not None’ will evaluate to True because None is considered False in Python.

Overall explanation

Topics: not boolean

Try it yourself:

  1. print(not 0) # True
  2. print(not 23) # False
  3. print(not ”) # True
  4. print(not ‘Peter’) # False
  5. print(not None) # True

Explanation:

The values 23 and 'Peter' will evaluate to True

and the rest will evaluate to False

The not turns everything around.

The values that become False in Python are the following:

  1. print(bool(”)) # False
  2. print(bool(0)) # False
  3. print(bool(0.0)) # False
  4. print(bool(0j)) # False
  5. print(bool(None)) # False
  6. print(bool([])) # False
  7. print(bool(())) # False
  8. print(bool({})) # False
  9. print(bool(set())) # False
  10. print(bool(range(0))) # False

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

Domain

02 – Data Types

Question 40Skipped

Q410 – Data Aggregates

Consider the following list.

data = [1, 5, 10, 19, 55, 30, 55, 99]

Which of the code snippets below would produce a new list like the following?

[1, 5, 10, 99]

  1. data.pop(5)
  2. data.pop(19)
  3. data.pop(55)

Explanation

The pop() method removes an element from the list based on the index provided. However, using data.pop(19) and data.pop(55) in this context is incorrect as the indices are out of range for the given list. This combination will not produce the desired new list [1, 5, 10, 99].

None of the above.

Explanation

None of the above choices provide the correct sequence of operations to produce the new list [1, 5, 10, 99] from the given list.

Correct answer

  1. data.pop(5)
  2. data.remove(19)
  3. data.remove(55)
  4. data.remove(55)

Explanation

Using the pop() method with the index of the elements to be removed will remove the elements from the list. In this case, data.pop(5) will remove the element at index 5 (30), data.remove(19) will remove the element 19, and data.remove(55) will remove the first occurrence of 55. This combination will result in a new list [1, 5, 10, 99].

  1. data.pop(1)
  2. data.pop(3)
  3. data.pop(4)
  4. data.pop(6)

Explanation

Using the pop() method with specific indices to remove elements from the list is not the correct approach in this scenario. Additionally, the indices provided in data.pop(1), data.pop(3), data.pop(4), and data.pop(6) are incorrect for the given list. This combination will not result in the new list [1, 5, 10, 99].

  1. data.remove(5)
  2. data.remove(19)
  3. data.remove(55)

Explanation

The remove() method removes the first occurrence of a specified value from the list. In this case, data.remove(5) will remove the element 5, data.remove(19) will remove the element 19, and data.remove(55) will remove the first occurrence of 55. This combination will not produce the desired new list [1, 5, 10, 99] as multiple occurrences of 55 are present.

Overall explanation

Topics: list pop() remove()

Try it yourself:

  1. data = [1, 5, 10, 19, 55, 30, 55, 99]

  2. data.pop(5)

  3. data.remove(19)

  4. data.remove(55)

  5. data.remove(55)

  6. print(data) # [1, 5, 10, 99]

  7. data = [1, 5, 10, 19, 55, 30, 55, 99]

  8. data.remove(5)

  9. data.remove(19)

  10. data.remove(55)

  11. print(data) # [1, 10, 30, 55, 99]

  12. data = [1, 5, 10, 19, 55, 30, 55, 99]

  13. data.pop(5)

  14. data.pop(19) # IndexError: pop index out of range

  15. data.pop(55) # IndexError: pop index out of range

  16. data = [1, 5, 10, 19, 55, 30, 55, 99]

  17. data.pop(1)

  18. data.pop(3)

  19. data.pop(4)

  20. data.pop(6) # IndexError: pop index out of range

Explanation:

list.pop([i])

The index is optional.

If the index is given pop()

removes and returns the element at the given index.

The default index is -1

Meaning that the last index is removed and returned.

data.pop(5) removes the value 30

The remove() method removes the first occurrence

of the element with the specified value.

data.remove(19)

data.remove(55)

data.remove(55)

is exactly what is needed.

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

Domain

04 – Data Aggregates

Question 41Skipped

Q404 – Functions

What is the expected output of the following code?

  1. def func1(param):

  2. return param
    
  3. def func2(param):

  4. return param * 2
    
  5. def func3(param):

  6. return param + 3
    
  7. print(func1(func2(func3(1))))

1

Explanation

This choice is incorrect because it does not consider the sequential order of function calls and their return values. The code first calls func3(1), which returns 1 + 3 = 4. Then, the result of func3(1) is passed to func2, which returns 4 * 2 = 8. Finally, the result of func2(4) is passed to func1, which returns 8, not 1.

6

Explanation

This choice is incorrect because it does not consider the sequential order of function calls and their return values. The code first calls func3(1), which returns 1 + 3 = 4. Then, the result of func3(1) is passed to func2, which returns 4 * 2 = 8. Finally, the result of func2(4) is passed to func1, which returns 8, not 6.

Correct answer

8

Explanation

The code first calls func3(1), which returns 1 + 3 = 4. Then, the result of func3(1) is passed to func2, which returns 4 * 2 = 8. Finally, the result of func2(4) is passed to func1, which simply returns the value passed to it. Therefore, the expected output is 8.

3

Explanation

This choice is incorrect because it does not consider the sequential order of function calls and their return values. The code first calls func3(1), which returns 1 + 3 = 4. Then, the result of func3(1) is passed to func2, which returns 4 * 2 = 8. Finally, the result of func2(4) is passed to func1, which returns 8, not 3.

Overall explanation

Topics: def return

Try it yourself:

  1. def func1(param):

  2. return param      # 8 -> 8
    
  3. def func2(param):

  4. return param * 2  # 4 * 2 -> 8
    
  5. def func3(param):

  6. return param + 3  # 1 + 3 -> 4
    
  7. print(func1(func2(func3(1)))) # 8

Explanation:

func3() gets called with 1 and returns 4

func2() gets called with 4 and returns 8

func1() gets called with 8 and returns 8

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

Domain

06 – Functions

Question 42Skipped

Q422 – Data Types

Which of the following operators can be used with strings?

1) +

2) *

3) -

4) in

1, 2

Explanation

The + operator can be used to concatenate two strings, and the * operator can be used to repeat a string multiple times. The – operator is not valid for use with strings. Therefore, choices 1 and 2 are correct.

Correct answer

1, 2, 4

Explanation

The + operator can be used to concatenate two strings, the * operator can be used to repeat a string multiple times, and the ‘in’ operator can be used to check if a substring exists within a string. Therefore, choices 1, 2, and 4 are correct.

1, 2, 3

Explanation

The + operator can be used to concatenate two strings, the * operator can be used to repeat a string multiple times. However, the – operator is not valid for use with strings. Therefore, choices 1 and 2 are correct, but choice 3 is incorrect.

1, 2, 3, 4

Explanation

The + operator can be used to concatenate two strings, the * operator can be used to repeat a string multiple times, and the ‘in’ operator can be used to check if a substring exists within a string. Therefore, choices 1, 2, 3, and 4 are all correct.

Overall explanation

Topics: string operators

Try it yourself:

  1. print(‘Hello’ + ‘ ‘ + ‘world’) # Hello world
  2. print(‘Hello’ * 3) # HelloHelloHello
  3. print(‘e’ in ‘Hello’ * 3) # True
  4. print(‘Hello’ – ‘Hell’) # TypeError: …

Explanation:

You can not subtract a string from a string

The rest works just fine.

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

Domain

02 – Data Types

Question 43Skipped

Q457 – Operators

What is the expected output of the following code?

  1. x = 0
  2. y = 1
  3. x = x ^ y
  4. y = x ^ y
  5. y = x ^ y
  6. print(x, y)

0 1

Explanation

The code uses the XOR (^) operator to swap the values of x and y without using a temporary variable. After the operations, x will have the value of 1, and y will have the value of 0, resulting in the output of 1 0, not 0 1.

1 0

Explanation

The code uses the XOR (^) operator to swap the values of x and y without using a temporary variable. After the operations, x will have the value of 1, and y will have the value of 0, resulting in the output of 1 0.

0 0

Explanation

The code uses the XOR (^) operator to swap the values of x and y without using a temporary variable. However, due to the order of operations, both x and y end up with the value of 1, resulting in the output of 1 1, not 0 0.

Correct answer

1 1

Explanation

The code uses the XOR (^) operator to swap the values of x and y without using a temporary variable. After the operations, both x and y will have the value of 1, resulting in the output of 1 1.

Overall explanation

Topics: bitwise xor operator

Try it yourself:

  1. x = 0

  2. y = 1

  3. print(x, y) # 0 1

  4. x = x ^ y

  5. print(x, y) # 1 1

  6. y = x ^ y

  7. print(x, y) # 1 0

  8. y = x ^ y

  9. print(x, y) # 1 1

  10. print(1 ^ 1) # 0

  11. print(1 ^ 0) # 1

  12. print(0 ^ 1) # 1

  13. print(0 ^ 0) # 0

Explanation:

The bitwise xor operator returns 1 when one operand is 1 and the other is 0

When both operands are 0 or both operands are 1 it returns 0

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

Domain

03 – Operators

Question 44Skipped

Q438 – Modules

Consider the following code.

  1. import random
  2. print(int(random.random() * 7))

Which of the following statements is correct?

It will print a random integer value from 0 to 7

Explanation

This statement is incorrect because the code multiplies the random float value by 7, which means the maximum integer value that can be printed is 6, not 7. Therefore, it will print a random integer value from 0 to 6, not 0 to 7.

It will print a random integer value from 1 to 7

Explanation

This statement is incorrect because the code uses int(random.random() * 7), which means the minimum integer value that can be printed is 0. Therefore, it will print a random integer value from 0 to 6, not from 1 to 7.

It will print 7

Explanation

This statement is incorrect because the code multiplies the random float value by 7 and then converts it to an integer. As a result, the maximum integer value that can be printed is 6, not 7. Therefore, it will not print 7.

Correct answer

It will print a random integer value from 0 to 6

Explanation

The code imports the random module and uses the random() function to generate a random float value between 0 and 1. By multiplying this value by 7 and converting it to an integer using int(), the code will print a random integer value from 0 to 6.

Overall explanation

Topics: import int() random.random()

Try it yourself:

  1. from random import random

  2. print(int(random() * 7)) # e.g. 4

  3. print(random()) # e.g. 0.5653393171868492

  4. print(random() * 7) # e.g. 4.0610157611213675

  5. print(int(random() * 7)) # e.g. 3

Explanation:

The random() method returns a float between 0.0 (inclusive)

and 1 (exclusive): 0.0 to 0.9999999999999999

Multiplied by 7 you get a float like: 0.0 to 6.9999999999999999

You cast that to an integer and you end up with an float like: 0 to 6

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

Domain

09 – Modules

Question 45Skipped

Q418 – Operators

You are writing a Python program that evaluates an arithmetic formular.

The formular is described as b equals a multiplied by negative one,

then raised to the second power,

where a is the value that will be input and b is the result.

a = eval(input('Enter a number for the equation: '))

Which of the following is a valid expression for the given requirement?

b = (a) ** -2

Explanation

This expression incorrectly raises ‘a’ to the power of -2, which is not the same as raising the negative of ‘a’ to the second power. This would not produce the correct result as described in the question.

b = (a-) ** 2

Explanation

This expression incorrectly places the negative sign after ‘a’ without enclosing it in parentheses. This would result in a syntax error as the interpreter would not be able to understand the operation intended.

Correct answer

b = (-a) ** 2

Explanation

This expression correctly follows the description of the formula provided in the question. It first multiplies ‘a’ by -1, then raises the result to the second power, which is represented as (-a) ** 2.

b = -(a) ** 2

Explanation

This expression incorrectly applies the negative sign after raising ‘a’ to the second power. It does not follow the formula described in the question, where the negative sign should be applied before squaring ‘a’.

Overall explanation

Topics: eval() input() exponentiation operator

operator precedence unary minus operator

Try it yourself:

  1. a = eval(input(‘Enter a number for the equation: ‘))

  2. a = eval(‘7’) # Just for convenience
  3. print((-a) ** 2) # 49
  4. print(-(a) ** 2) # -49
  5. print(-a ** 2) # -49
  6. print(-(a ** 2)) # -49

Explanation:

In the end this is mainly about operator precedence

The exponentiation operator has a higher precedence

than the unary minus operator

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

Domain

03 – Operators

Question 46Skipped

Q456 – Operators

The expression:

'mike' > 'Mike'

is

Correct answer

true

Explanation

In Python, string comparison is case-sensitive. Therefore, when comparing the strings ‘mike’ and ‘Mike’, the lowercase ‘m’ in ‘mike’ has a higher ASCII value than the uppercase ‘M’ in ‘Mike’. As a result, the expression ‘mike’ > ‘Mike’ evaluates to true.

false

Explanation

In Python, string comparison is case-sensitive. Since the lowercase ‘m’ in ‘mike’ has a higher ASCII value than the uppercase ‘M’ in ‘Mike’, the expression ‘mike’ > ‘Mike’ is not false. Therefore, the correct evaluation of this expression is true.

erroneous

Explanation

The expression ‘mike’ > ‘Mike’ is not erroneous in Python. It is a valid comparison between two strings based on their ASCII values. The lowercase ‘m’ in ‘mike’ has a higher ASCII value than the uppercase ‘M’ in ‘Mike’, resulting in the expression evaluating to true.

Overall explanation

Topic: greater than operator string comparison

Try it yourself:

  1. print(‘mike’ > ‘Mike’) # True
  2. print(ord(‘m’)) # 109
  3. print(ord(‘M’)) # 77

Explanation:

The ASCII code of m is greater than the ASCII code of M

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

Domain

03 – Operators

Question 47Skipped

Q434 – I/O

You want to write Hello world to the file data.txt

Which of the following code snippets do you need?

  1. f = open(‘data.txt’, ‘r’)
  2. f.write(‘Hello world’)
  3. f.close()

Explanation

This code snippet opens the file ‘data.txt’ in read mode (‘r’), which does not allow writing to the file. Attempting to write ‘Hello world’ to the file will result in an error.

  1. f = open(‘data.txt’)
  2. f.write(‘Hello world’)
  3. f.close()

Explanation

This code snippet opens the file ‘data.txt’ without specifying a mode, which defaults to read mode (‘r’). Since the intention is to write to the file, this code snippet will result in an error.

Correct answer

  1. f = open(‘data.txt’, ‘w’)
  2. f.write(‘Hello world’)
  3. f.close()

Explanation

This code snippet correctly opens the file ‘data.txt’ in write mode (‘w’), writes the string ‘Hello world’ to the file, and then closes the file. This is the correct way to write to a file in Python.

  1. f = open(‘data.txt’, ‘b’)
  2. f.write(‘Hello world’)
  3. f.close()

Explanation

This code snippet attempts to open the file ‘data.txt’ in binary mode (‘b’), which is not necessary for writing a simple text string like ‘Hello world’. This mode is used for binary files, not text files. This code snippet will result in an error when trying to write to the file.

Overall explanation

Topics: open() and its modes write() close()

Try it yourself:

  1. """

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

  3. f.write(‘Hello world’)

  4. f.close()

  5. """

  6. """

  7. f = open(‘data.txt’)

  8. f.write(‘Hello world’) # io.UnsupportedOperation: …

  9. f.close()

  10. """

  11. """

  12. f = open(‘data.txt’, ‘r’)

  13. f.write(‘Hello world’) # io.UnsupportedOperation: …

  14. f.close()

  15. """

  16. """

  17. f = open(‘data.txt’, ‘b’)

  18. f.write(‘Hello world’) # ValueError: …

  19. f.close()

  20. """

Explanation:

This question is about open() and its modes.

Here you want to write something to a file and need w as the mode.

The default mode is r

Therefore no given mode and the mode r are the same thing.

Both do not work here, because they only open the file for reading.

The mode b on its own does not exist at all.

The only possible modes are r  w  a  x

The b stands for binary and can only be an addition to one of the modes.

For example wb opens a file for writing in binary mode.

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

Domain

07 – I/O

Question 48Skipped

Q431 – Control Flow

What would you insert instead of ???

so that the program prints TRUE to the monitor?

  1. w = 7

  2. x = 3

  3. y = 4

  4. z = True

  5. a = w + x * y

  6. b = w + x / z

  7. if ???:

  8. print('TRUE')
    
  9. else:

  10. print('FALSE')
    

Correct answer

a > b

Explanation

In this scenario, the condition ‘a > b’ needs to be inserted in the if statement to ensure that the program prints ‘TRUE’ to the monitor. This condition compares the value of ‘a’ (result of w + x * y) with the value of ‘b’ (result of w + x / z) and checks if ‘a’ is greater than ‘b’.

a == b

Explanation

The condition ‘a == b’ compares the values of ‘a’ and ‘b’ to check if they are equal. However, in this case, the program should print ‘TRUE’ to the monitor, which requires the condition to be ‘a > b’ instead of ‘a == b’.

a <= b

Explanation

The condition ‘a <= b’ checks if the value of ‘a’ is less than or equal to the value of ‘b’. This condition is not suitable for ensuring that the program prints ‘TRUE’ to the monitor in this specific scenario where ‘a’ needs to be greater than ‘b’.

a < b

Explanation

The condition ‘a < b’ compares the value of ‘a’ with the value of ‘b’ to check if ‘a’ is less than ‘b’. However, in this case, the program should print ‘TRUE’ to the monitor, which requires the condition to be ‘a > b’ instead of ‘a < b’.

Overall explanation

Topics: if else addition operator multiplication operator

division operator  operator precedence boolean

Try it yourself:

  1. w = 7
  2. x = 3
  3. y = 4
  4. z = True
  5. a = w + x * y
  6. b = w + x / z
  7. print(7 + 3 * 4) # 19
  8. print(7 + (3 * 4)) # 19
  9. print(7 + 12) # 19
  10. print(a) # 19
  11. print(7 + 3 / True) # 10.0
  12. print(7 + 3 / 1) # 10.0
  13. print(7 + (3 / 1)) # 10.0
  14. print(7 + 3.0) # 10.0
  15. print(b) # 10.0
  16. print(a > b) # True
  17. print(a == b) # False
  18. print(a <= b) # False
  19. print(a < b) # False
  20. if a > b:
  21. print('TRUE')    # TRUE
    
  22. else:
  23. print('FALSE')
    

Explanation:

The operators here come from two different groups:

The group "Multiplication, Division, Floor division, Modulus"

has a higher precedence than the group

"Addition, Subtraction".

Meaning multiplication or division come before addition.

The other topic here is calculating with a boolean

If you calculate with a boolean then True will become 1 and False will become 0

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

Domain

05 – Control Flow

Question 49Skipped

Q407 – Data Aggregates

What is the expected output of the following code?

  1. data = {}

  2. data[1] = 1

  3. data[‘1’] = 2

  4. data[1.0] = 4

  5. res = 0

  6. for d in data:

  7. res += data[d]
    
  8. print(res)

The code is erroneous.

Explanation

The code is not erroneous. It correctly assigns values to keys of different types (integer, string, float) in the dictionary ‘data’ and calculates the sum of these values. The expected output of the code is 6, not an error.

Correct answer

6

Explanation

The expected output of the code is 6 because the dictionary ‘data’ has three key-value pairs: {1: 1, ‘1’: 2, 1.0: 4}. When iterating over the keys in the dictionary and summing up the corresponding values, the total sum is 6.

7

Explanation

The output of 7 is incorrect. The sum of values corresponding to keys 1, ‘1’, and 1.0 in the dictionary ‘data’ is 1 + 2 + 4 = 7. Therefore, the expected output of the code is 7, not 6.

3

Explanation

The output of 3 is incorrect. The key ‘1’ and the integer 1 are considered different keys in the dictionary ‘data’. Therefore, the sum of values corresponding to keys 1, ‘1’, and 1.0 is 1 + 2 + 4 = 7, not 3.

Overall explanation

Topics: dictionary indexes for add and assign operator

Try it yourself:

  1. data = {}

  2. data[1] = 1

  3. data[‘1’] = 2

  4. data[1.0] = 4

  5. res = 0

  6. for d in data:

  7. res += data[d]
    
  8. print(res) # 6

  9. print(data) # {1: 4, ‘1’: 2}

Explanation:

Dictionary can have different data types as a key.

BUT if an integer and a float have the same value,

the second value overrides the first values.

And the first index is still name giving.

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

Domain

04 – Data Aggregates

Question 50Skipped

Q416 – Operators

Consider the following code.

  1. x = [0, 1, 2]
  2. x[0], x[2] = x[2], x[0]

What does the second assignment do?

Correct answer

It reverses the list.

Explanation

This assignment swaps the values of the first and last elements in the list, effectively reversing the order of elements in the list. It does not extend or shorten the list, but simply rearranges the existing elements.

It shortens the list.

Explanation

This assignment does not shorten the list. It swaps the positions of the first and last elements in the list, but it does not remove any elements from the list.

It doesn’t change the list.

Explanation

This assignment does change the list by swapping the positions of the first and last elements. It effectively reverses the order of elements in the list, so it is incorrect to say that it doesn’t change the list.

It extends the list.

Explanation

This assignment does not extend the list. It simply swaps the positions of the first and last elements in the list, without adding any new elements to the list.

Overall explanation

Topics: list multiple assignments

Try it yourself:

  1. x = [0, 1, 2]

  2. x[0], x[2] = x[2], x[0]

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

  4. An even simpler one line swap:

  5. y, z = 3, 7

  6. y, z = z, y

  7. print(y, z) # 7 3

Explanation:

In Python you can change the values of two variables in one line.

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

Domain

03 – Operators

Question 51Skipped

Q411 – Data Aggregates

What is the expected output of the following code?

  1. x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  2. x[::2] = 10, 20, 30, 40, 50, 60
  3. print(x)

Correct answer

The code is erroneous.

Explanation

The code is erroneous because the number of elements assigned to the slice on the left side of the assignment operator does not match the number of elements in the sequence on the right side. This will result in a "ValueError" as the assignment is not possible due to the mismatch in the number of elements.

[1, 2, 10, 20, 30, 40, 50, 60]

Explanation

This choice is incorrect because the number of elements assigned to the slice on the left side of the assignment operator is greater than the number of elements in the original list. As a result, the assignment will not be possible, and the output will be an error.

[10, 2, 20, 4, 30, 6, 40, 8, 50, 60]

Explanation

This choice is incorrect because the elements assigned to the slice on the left side of the assignment operator are not correctly aligned with the original list elements. The output will not be as expected, and the assignment will not be successful due to the mismatch in the number of elements.

[1, 10, 3, 20, 5, 30, 7, 40, 9, 50, 60]

Explanation

This choice is incorrect because the elements assigned to the slice on the left side of the assignment operator are not correctly aligned with the original list elements. The output will not be as expected, and the assignment will not be successful due to the mismatch in the number of elements.

Overall explanation

Topic: list slicing slice assignment

Try it yourself:

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

  2. x[::2] = 10, 20, 30, 40, 50, 60 # ValueError …

  3. print(x)

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

  5. y[::2] = 10, 20, 30, 40, 50

  6. print(y) # [10, 2, 20, 4, 30, 6, 40, 8, 50]

Explanation:

It is just one value too much.

The list slicing [::2] takes every second index

and assigns one value 1->10, 3->20, 5->30, 7->40, 9->50

In the end there is no index for 60

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

Domain

04 – Data Aggregates

Question 52Skipped

Q403 – Functions

What is the expected output of the following code?

  1. def func1(a):

  2. return a ** a
    
  3. def func2(a):

  4. return func1(a) * func1(a)
    
  5. print(func2(2))

The code is erroneous.

Explanation

The code defines the functions func1 and func2 correctly and does not contain any errors. It correctly calculates the output based on the input argument provided to func2. The expected output of the code is 16.

2

Explanation

The code does not directly return the input ‘a’ in either func1 or func2. Instead, it performs exponentiation operations on ‘a’. When func2 is called with 2 as the argument, it calculates 2^2 * 2^2 = 4 * 4 = 16, not 2.

Correct answer

16

Explanation

The code defines two functions, func1 and func2. func1 takes a parameter ‘a’ and returns ‘a’ raised to the power of ‘a’. func2 takes a parameter ‘a’, calls func1 twice with ‘a’ as the argument, and returns the product of the results. When func2 is called with 2 as the argument, it calculates func1(2) * func1(2), which is equivalent to 2^2 * 2^2 = 4 * 4 = 16.

4

Explanation

The code does not directly return the input ‘a’ in either func1 or func2. Instead, it performs exponentiation operations on ‘a’. When func2 is called with 2 as the argument, it calculates 2^2 * 2^2 = 4 * 4 = 16, not 4.

Overall explanation

Topics: def return

Try it yourself:

  1. def func1(a):

  2. return a ** a
    
  3. def func2(a):

  4. # return func1(a) * func1(a)
    
  5. # return (a ** a) * (a ** a)
    
  6. # return (2 ** 2) * (2 ** 2)
    
  7. # return 4 * 4
    
  8. return 16
    
  9. print(func2(2)) # 16

Explanation:

The value 2 that is given to func2() gets forwarded to func1()

In func1() the 2 ** 2 takes place and evaluates to 4

which is returned to func2()

And 4 * 4 is 16

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

Domain

06 – Functions

Question 53Skipped

Q437 – Modules

A function returning a list of all entities available in a module is called:

entities()

Explanation

The entities() function is not a standard Python function for returning a list of all entities available in a module. It is not a recognized function in Python’s standard library for module introspection.

Correct answer

dir()

Explanation

The dir() function in Python is used to return a list of all entities available in a module. It provides a list of names defined in the module, including functions, classes, variables, and modules imported.

content()

Explanation

The content() function is not a standard Python function for returning a list of all entities available in a module. It is not a recognized function in Python’s standard library for module introspection.

listmodule()

Explanation

The listmodule() function is not a standard Python function for returning a list of all entities available in a module. It is not a recognized function in Python’s standard library for module introspection.

Overall explanation

Topic: dir()

Try it yourself:

  1. import math

  2. print(dir(math))

  3. """

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

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

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

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

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

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

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

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

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

  13. """

  14. print(content(math)) # NameError: …

  15. print(entities(math)) # NameError: …

  16. print(listmodule(math)) # NameError: …

Explanation:

The dir() function returns the names of all entities

(properties and methods) of the passed module (or object).

The others do not exist.

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

Domain

09 – Modules

Question 54Skipped

Q402 – Functions

Which of the literals below is not a valid function name?

_function1

Explanation

"_function1" is a valid function name in Python. It starts with an underscore, which is allowed, and follows the naming convention for functions.

Correct answer

1function

Explanation

Function names cannot start with a number in Python, so "1function" is not a valid function name. It violates the naming convention for functions in Python.

Function_1

Explanation

"Function_1" is a valid function name in Python. It follows the naming convention for functions and does not violate any rules regarding function naming.

Func_1_tion

Explanation

"Func_1_tion" is a valid function name in Python. It follows the naming convention for functions and does not violate any rules regarding function naming.

Function1

Explanation

"Function1" is a valid function name in Python. It follows the naming convention for functions and does not violate any rules regarding function naming.

Overall explanation

Topic: naming functions

Try it yourself:

  1. def 1function(): pass # SyntaxError: invalid syntax

  2. def _function1(): pass
  3. def Function1(): pass
  4. def Function_1(): pass
  5. def Func_1_tion(): pass

Explanation:

A function name has to start with a letter or an underscore.

Then numbers, letters and underscores can follow.

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

Domain

06 – Functions

Question 55Skipped

Q408 – Data Aggregates

What is the expected output of the following code?

  1. box = {}

  2. jars = {}

  3. crates = {}

  4. box[‘biscuit’] = 1

  5. box[‘cake’] = 3

  6. jars[‘jam’] = 4

  7. crates[‘box’] = box

  8. crates[‘jars’] = jars

  9. print(len(crates[box]))

Correct answer

The code is erroneous.

Explanation

The code is erroneous because the key used to access the length of the dictionary is incorrect. The key should be a string or a valid dictionary key, but ‘box’ is a dictionary itself, not a valid key to access the length of the dictionary.

4

Explanation

The code will not output 4 because it is trying to access the length of the dictionary ‘box’ within the ‘crates’ dictionary, not the value associated with the key ‘box’. Therefore, the output will not be 4.

2

Explanation

The code will not output 2 because it is trying to access the length of the dictionary ‘box’ within the ‘crates’ dictionary, not the value associated with the key ‘box’. Therefore, the output will not be 2.

1

Explanation

The code will not output 1 because it is trying to access the length of the dictionary ‘box’ within the ‘crates’ dictionary, not the value associated with the key ‘box’. Therefore, the output will not be 1.

3

Explanation

The code will not output 3 because it is trying to access the length of the dictionary ‘box’ within the ‘crates’ dictionary, not the value associated with the key ‘box’. Therefore, the output will not be 3.

Overall explanation

Topics: dictionary len()

Try it yourself:

  1. box = {}

  2. jars = {}

  3. crates = {}

  4. box[‘biscuit’] = 1

  5. box[‘cake’] = 3

  6. jars[‘jam’] = 4

  7. crates[‘box’] = box

  8. crates[‘jars’] = jars

  9. print(len(crates[box])) # TypeError: unhashable type: ‘dict’

  10. print(len(crates[‘box’])) # 2

  11. print(crates[‘box’]) # {‘biscuit’: 1, ‘cake’: 3}

  12. print(crates)

  13. {‘box’: {‘biscuit’: 1, ‘cake’: 3}, ‘jars’: {‘jam’: 4}}

Explanation:

Much ado about nothing.

In the end there are just missing single quotes around box in the last line.

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

Domain

04 – Data Aggregates

Question 56Skipped

Q442 – Error Handling

What is the expected output of the following code?

  1. try:
  2. raise Exception
    
  3. except BaseException:
  4. print('1')
    
  5. except Exception:
  6. print('2')
    
  7. except:
  8. print('3')
    

3

Explanation

The output will not be ‘3’ because the Exception raised in the try block is caught by the first except block that handles all exceptions derived from BaseException, not by the generic except block.

Correct answer

1

Explanation

The output will be ‘1’ because the Exception raised in the try block is caught by the first except block, which handles all exceptions derived from BaseException.

2

Explanation

The output will not be ‘2’ because the Exception raised in the try block is caught by the first except block that handles all exceptions derived from BaseException, not specifically the Exception class.

The code is erroneous.

Explanation

The code is not erroneous; however, the output will be ‘1’ as the Exception raised in the try block is caught by the first except block that handles all exceptions derived from BaseException.

Overall explanation

Topics: try except Exception BaseException

Try it yourself:

  1. try:

  2. raise Exception
    
  3. except BaseException:

  4. print('1')  # 1
    
  5. except Exception:

  6. print('2')
    
  7. except:

  8. print('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.

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

Domain

08 – Error Handling

Question 57Skipped

Q450 – Error Handling

What is the expected output of the following code?

  1. class A:

  2. def __init__(self):
    
  3.     self.text = 'abc'
    
  4.     self.count = 0
    
  5. def __iter__(self):
    
  6.     return self
    
  7. def __next__(self):
    
  8.     if self.count == len(self.text):
    
  9.         raise StopIteration
    
  10.     value = self.text[self.count]
    
  11.     self.count += 1
    
  12.     return value
    
  13. for x in A():

  14. print(x, end='')
    

210

Explanation

The code iterates over the characters in the ‘abc’ string, incrementing the count variable to access the characters in reverse order. As a result, the output ‘210’ is not the expected output, as the characters are printed in the order they appear in the string.

012

Explanation

The code does not involve numbers or indexing operations. It simply iterates over the characters in the ‘abc’ string. Therefore, the output ‘012’ is not relevant to the code and is not the expected output.

cba

Explanation

The code iterates over the characters in the ‘abc’ string in the order they appear. The next method increments the count variable to access the next character in reverse order. Therefore, the output would be ‘cba’, which is not the expected output.

Correct answer

abc

Explanation

The code defines a class A with an iterator that iterates over the characters in the ‘abc’ string. The next method returns each character in the string sequentially. The for loop iterates over the instance of class A, printing each character in the ‘abc’ string, resulting in the output ‘abc’.

Overall explanation

Topics: class raise StopIteration for

__init__() __iter__() __next__()

Try it yourself:

  1. class A:

  2. def __init__(self):
    
  3.     self.text = 'abc'
    
  4.     self.count = 0
    
  5. def __iter__(self):
    
  6.     return self
    
  7. def __next__(self):
    
  8.     if self.count == len(self.text):
    
  9.         raise StopIteration
    
  10.     value = self.text[self.count]
    
  11.     self.count += 1
    
  12.     return value
    
  13. for x in A():

  14. print(x, end='')  # abc
    

Explanation:

The __iter__() method enables the objects of class A to be iterable.

In every iteration of the for loop the __next__() method is called

and every time its return value is assigned to x

In the first iteration the return value

is the letter of 'abc' with the index 0'a'

In the second iteration the return value

is the letter of 'abc' with the index 1'b'

In the third iteration the return value

is the letter of 'abc' with the index 2'c'

In the fourth iteration the if condition is True

and the StopIteration exception is raised which ends the for loop.

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

Domain

08 – Error Handling