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

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

Back to result overview

Attempt 2

All domains

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

Collapse all questions

Question 1Skipped

**Q150 – Basics

**The digraph written as #! is used to:

create a docstring.

Explanation

The digraph #! is not used to create a docstring in Python. Docstrings are used to provide documentation within Python code and are enclosed in triple quotes, but they are not related to the shebang syntax.

Correct answer

tell a Unix or Unix-like OS how to execute the contents of a Python file.

Explanation

The digraph #! is known as a shebang and is used in Unix or Unix-like operating systems to specify the interpreter that should be used to execute the contents of a Python file. This allows the script to be executed directly from the command line without explicitly calling the Python interpreter.

make a particular module entity a private one.

Explanation

The digraph #! is not used to make a particular module entity private in Python. In Python, the convention for making an entity private is to prefix its name with an underscore, but this is not related to the shebang syntax.

tell an MS Windows OS how to execute the contents of a Python file.

Explanation

The digraph #! is not used to tell an MS Windows OS how to execute the contents of a Python file. Windows does not use the shebang syntax for specifying the interpreter, so this choice is incorrect in the context of Python file execution on Windows.

Overall explanation

Topic: #! shebang

Explanation:

This is a general UNIX topic.

Best read about it here:

https://en.wikipedia.org/wiki/Shebang_(Unix)

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

Domain

01 – Basics

Question 2Skipped

Q103 – Basics

What will be the output of the following code snippet?

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

2 2

Explanation

This choice is incorrect because the value of x is reassigned to the value of y, and the value of y is reassigned to the original value of x. Therefore, the output will be 2 for x and 1 for y, not 2 for both x and y.

Correct answer

2 1

Explanation

The code snippet assigns the value of x to z, then assigns the value of y to x, and finally assigns the value of z (which is the original value of x) to y. Therefore, the output will be 2 for x and 1 for y.

1 1

Explanation

This choice is incorrect because the value of x is reassigned to the value of y, and the value of y is reassigned to the original value of x. As a result, both x and y will have the value of 1, not 2.

1 2

Explanation

This choice is incorrect because the value of x is reassigned to the value of y, and the value of y is reassigned to the original value of x. Therefore, the output will be 2 for x and 1 for y, not 1 for x and 2 for y.

Overall explanation

Topic: copying an immutable object by assigning

Try it yourself:

  1. x = 1
  2. y = 2
  3. z = x
  4. print(z) # 1
  5. x = y
  6. print(x) # 2
  7. y = z
  8. print(y) # 1
  9. print(x, y) # 2 1

Explanation:

Integer is an immutable data type.

The values get copied from one variable to another.

In the end x and y changed their values.

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

Domain

01 – Basics

Question 3Skipped

Q115 – Functions

What is the output of the following code snippet?

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

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

Correct answer

3 2

Explanation

The function test takes two arguments, x and y, with default values of 1 and 2, respectively. Inside the function, x is updated to be the sum of x and y, which results in x being 3. Then, y is incremented by 1. Finally, the function prints the values of x and y, which are 3 and 2, respectively.

3 3

Explanation

This choice is incorrect because the function test updates the value of x to be the sum of x and y, which results in x being 3. Then, y is incremented by 1. Therefore, the correct output is 3 for x and 2 for y, not 3 and 3.

1 3

Explanation

This choice is incorrect because the function test updates the value of x to be the sum of x and y, which results in x being 3. Then, y is incremented by 1. Therefore, the correct output is 3 for x and 2 for y, not 1 and 3.

2 3

Explanation

This choice is incorrect because the function test updates the value of x to be the sum of x and y, which results in x being 3. Then, y is incremented by 1. Therefore, the correct output is 3 for x and 2 for y, not 2 and 3.

The code is erroneous.

Explanation

This choice is incorrect because the code snippet provided is not erroneous. The function test is defined correctly and called with valid arguments, resulting in the output of 3 for x and 2 for y.

Overall explanation

Topics: def parameter

Try it yourself:

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

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

Explanation:

Okay, both parameters get the default value of the other one,

but for the rest it’s business as usual.

(There is a similar question Q331.)

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

Domain

06 – Functions

Question 4Skipped

Q133 – Modules

When a module is imported, its contents:

are executed as many times as they are imported.

Explanation

Contrary to this choice, when a module is imported in Python, its contents are executed only once, even if the module is imported multiple times in the same program. This behavior helps in maintaining the integrity of the module’s code and prevents redundant executions of the same code.

Correct answer

are executed once.

Explanation

When a module is imported in Python, its contents are executed only once, regardless of how many times the module is imported. This ensures that the module’s code is not repeatedly executed, improving efficiency and preventing potential issues with reinitialization of variables or functions.

are ignored.

Explanation

In Python, when a module is imported, its contents are not ignored. The purpose of importing a module is to make its functions, classes, and variables accessible in the current script or program. Ignoring the contents of the module would defeat the purpose of importing it.

are executed depending on the contents.

Explanation

The execution of a module’s contents is not dependent on the contents themselves. Regardless of what the module contains, its code will be executed only once when it is imported. This consistent behavior ensures that the module’s functionality is available throughout the program.

Overall explanation

Topic: import

Try it yourself:

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

  2. text = ”’

  3. print("I am a module, goo goo g’joob!")

  4. ”’

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

  6. f.write(text)
    
  7. import module # I am a module, goo goo g’joob!

  8. import module

Explanation:

An imported module is executed only once.

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

Domain

09 – Modules

Question 5Skipped

Q143 – Basics

What is the expected output of the following code?

  1. x = ”’
  2. print(len(x))

0

Explanation

The variable x is assigned the value of a single quotation mark, which is represented as ”’. The len() function in Python returns the length of a string, so the output of len(x) will not be 0.

2

Explanation

The variable x is assigned the value of a single quotation mark, which is represented as ”’. The len() function in Python returns the length of a string, so the output of len(x) will not be 2.

Correct answer

1

Explanation

The variable x is assigned the value of a single quotation mark, which is represented as ”’. The len() function in Python returns the length of a string, so the output of len(x) will be 1.

The code is erroneous.

Explanation

The code is not erroneous as it correctly assigns a value to the variable x and prints the length of the string. The output of the code will be 1.

Overall explanation

Topics: len() escaping

Try it yourself:

print(len('\''))  # 1

Explanation:

The backslash is the character to escape another character.

Here the backslash escapes the following single quote character.

Together they are one character.

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

Domain

01 – Basics

Question 6Skipped

Q105 – Data Aggregates

What is the expected output of the following code?

  1. data = [‘Peter’, 404, 3.03, ‘Wellert’, 33.3]
  2. print(data[1:3])

None of the above.

Explanation

This choice is incorrect because the output of the code is not None. The code data[1:3] will return a valid sublist of elements from the data list.

['Peter', 404, 3.03, 'Wellert', 33.3]

Explanation

This choice is incorrect because the code data[1:3] does not return the entire data list. It only returns a sublist of elements starting from index 1 up to index 3.

['Peter', 'Wellert']

Explanation

This choice is incorrect because the code data[1:3] does not return a sublist of elements based on their values (‘Peter’ and ‘Wellert’). Instead, it returns elements based on their index positions in the list.

Correct answer

[404, 3.03]

Explanation

The code data[1:3] will return a sublist of elements starting from index 1 (inclusive) up to index 3 (exclusive) in the data list. Therefore, the expected output is [404, 3.03].

Overall explanation

Topic: list indexing

Try it yourself:

  1. data = [‘Peter’, 404, 3.03, ‘Wellert’, 33.3]
  2. print(data[1:3]) # [404, 3.03]

Explanation:

You have a list of five elements of various data types.

[1:3] slices inclusive the first index and exclusive the third index.

Meaning it slices the first and second index.

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

Domain

04 – Data Aggregates

Question 7Skipped

Q135 – Operators

What is the expected output of the following code?

x = 1 // 5 + 1 / 5

print(x)

0.4

Explanation

The code calculates the result of the expression 1 // 5 + 1 / 5. The // operator performs integer division, resulting in 1 // 5 equaling 0. The / operator performs regular division, resulting in 1 / 5 equaling 0.2. Adding these two results together gives 0.2 as the final output, not 0.4.

Correct answer

0.2

Explanation

The code calculates the result of the expression 1 // 5 + 1 / 5. The // operator performs integer division, resulting in 1 // 5 equaling 0. The / operator performs regular division, resulting in 1 / 5 equaling 0.2. Adding these two results together gives 0.2 as the final output.

0

Explanation

The code uses the // operator for integer division, which results in 1 // 5 equaling 0. The + operator then adds this result to 1 / 5, which equals 0.2. Therefore, the output of the code is not 0 but 0.2.

0.0

Explanation

The code correctly calculates the result of the expression 1 // 5 + 1 / 5. The // operator performs integer division, resulting in 1 // 5 equaling 0. The / operator performs regular division, resulting in 1 / 5 equaling 0.2. Therefore, the output of the code is 0.2, not 0.0.

Overall explanation

Topics: arithmetic operators operator precedence

Try it yourself:

  1. x = 1 // 5 + 1 / 5
  2. x = (1 // 5) + (1 / 5)
  3. print(1 // 5) # 0
  4. x = 0 + (1 / 5)
  5. x = 0 + 0.2
  6. print(x) # 0.2

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

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

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

Domain

03 – Operators

Question 8Skipped

Q116 – Functions

What is the expected output of the following code?

  1. num = 1

  2. def func():

  3. num = num + 3
    
  4. print(num)
    
  5. func()

  6. print(num)

1 4

Explanation

This choice is incorrect because the code will raise a UnboundLocalError as the ‘num’ variable is being modified within the function ‘func()’ without being declared as a global variable. The code will not print any output and will result in an error.

Correct answer

The code is erroneous.

Explanation

The code is erroneous because the variable ‘num’ is being referenced and modified within the function ‘func()’ without being declared as a global variable. This results in a UnboundLocalError as ‘num’ is treated as a local variable within the function scope.

4 4

Explanation

This choice is incorrect because the code will raise a UnboundLocalError as the ‘num’ variable is being modified within the function ‘func()’ without being declared as a global variable. The code will not print any output and will result in an error.

4 1

Explanation

This choice is incorrect because the code will raise a UnboundLocalError due to the attempt to modify the ‘num’ variable within the function ‘func()’ without declaring it as a global variable. Therefore, the code will not print any output and will result in an error.

1 1

Explanation

This choice is incorrect because the code will raise a UnboundLocalError due to the attempt to modify the ‘num’ variable within the function ‘func()’ without declaring it as a global variable. Therefore, the code will not print any output and will result in an error.

Overall explanation

Topics: def shadowing

Try it yourself:

  1. num = 1

  2. def func():

  3. # num = num + 3  # UnboundLocalError: ...
    
  4. print(num)
    
  5. func()

  6. print(num)

  7. print(‘———-‘)

  8. num2 = 1

  9. def func2():

  10. x = num2 + 3
    
  11. print(x)  # 4
    
  12. func2()

  13. print(‘———-‘)

  14. num3 = 1

  15. def func3():

  16. num3 = 3     # Shadows num3 from outer scope
    
  17. print(num3)  # 3
    
  18. func3()

Explanation:

A variable name shadows into a function.

You can use it in an expression like in func2()

or you can assign a new value to it like in func3()

BUT you can not do both at the same time like in func()

There is going to be the new variable num

and you can not use it in an expression before its first assignment.

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

Domain

06 – Functions

Question 9Skipped

Q106 – Functions

What is the default return value for a function

that does not explicitly return any value?

int

Explanation

In Python, ‘int’ is a data type used to represent integers. However, it is not the default return value for a function that does not explicitly return any value. The default return value in this case is ‘None’.

Null

Explanation

‘Null’ is a value used in some programming languages to represent a null or empty value. In Python, the equivalent concept is ‘None’, which is the default return value for a function that does not explicitly return anything.

public

Explanation

‘public’ is a keyword used in some programming languages like Java to specify the visibility of a class member. It is not relevant to the default return value of a function in Python, which is ‘None’ if no return statement is provided.

void

Explanation

‘void’ is a type used in languages like C or C++ to indicate that a function does not return a value. However, in Python, the equivalent concept is represented by ‘None’ as the default return value for a function that does not explicitly return anything.

Correct answer

None

Explanation

In Python, if a function does not explicitly return any value, the default return value is ‘None’. This means that the function will return None if no return statement is specified.

Overall explanation

Topic: return

Try it yourself:

  1. def func1():

  2. pass
    
  3. print(func1()) # None

  4. def func2():

  5. return
    
  6. print(func2()) # None

Explanation:

If a function does not have the keyword return

the function will return the value None

The same happens if there is no value after the keyword return

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

Domain

06 – Functions

Question 10Skipped

Q157 – Modules

What is the expected output of the following code?

  1. from datetime import date

  2. date_1 = date(1992, 1, 16)

  3. date_2 = date(1991, 2, 5)

  4. print(date_1 – date_2)

Correct answer

345 days, 0:00:00

Explanation

The expected output is "345 days, 0:00:00" because the code calculates the difference between two date objects, date_1 and date_2, which results in a timedelta object representing the duration between the two dates in days, hours, and minutes.

345 days

Explanation

This choice is incorrect because it does not include the time component in the output. The correct output should include both the number of days and the time elapsed between the two dates.

345, 0:00:00

Explanation

This choice is incorrect because it lacks the necessary formatting to display the output correctly. The timedelta object returned by subtracting two date objects requires a specific format to represent the duration accurately.

345

Explanation

This choice is incorrect because it only provides the number of days in the output, omitting the time component. The timedelta object includes both the days and the time elapsed, which should be displayed in the output.

Overall explanation

Topics: import datetime date timedelta

Try it yourself:

  1. from datetime import date

  2. date_1 = date(1992, 1, 16)

  3. date_2 = date(1991, 2, 5)

  4. print(date_1 – date_2) # 345 days, 0:00:00

  5. print(type(date_1 – date_2)) # <class ‘datetime.timedelta’>

Explanation:

If you subtract one date object from another date object,

you get a timedelta object.

When you then print the timedelta object

you always get the output with days and hours.

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

Domain

09 – Modules

Question 11Skipped

Q146 – Control Flow

The ABC organics company needs a simple program

that their call center will use to enter survey data for a new coffee variety.

The program must accept input

and return the average rating based on a five-star scale.

The output must be rounded to two decimal places.

You need to complete the code to meet the requirements.

  1. sum = count = done = 0

  2. average = 0.0

  3. while done != -1:

  4. rating = XXX
    
  5. if rating == -1:
    
  6.     break
    
  7. sum += rating
    
  8. count += 1
    
  9. average = float(sum / count)

  10. YYY + ZZZ

What should you insert instead of XXXYYY and ZZZ?

  1. XXX -> input(‘Enter next rating (1-5), -1 for done’)
  2. YYY -> print(‘The average star rating for the new coffee is: ‘
  3. ZZZ -> format(average, ‘.2d’))

Explanation

XXX should be replaced with input(‘Enter next rating (1-5), -1 for done’) as it does not convert the input to a float. YYY should be replaced with print(‘The average star rating for the new coffee is: ‘ to display the output message. ZZZ should be replaced with format(average, ‘.2d’)) to round the average rating to two decimal places for proper formatting.

  1. XXX -> float(input(‘Enter next rating (1-5), -1 for done’))
  2. YYY -> printline(‘The average star rating for the new coffee is: ‘
  3. ZZZ -> format(average, ‘.2f’))

Explanation

XXX should be replaced with float(input(‘Enter next rating (1-5), -1 for done’)) to accept user input for ratings. YYY should not be replaced with printline as it is not a valid Python function. ZZZ should be replaced with format(average, ‘.2f’)) to round the average rating to two decimal places for proper formatting.

  1. XXX -> print(input(‘Enter next rating (1-5), -1 for done’))
  2. YYY -> print(‘The average star rating for the new coffee is: ‘
  3. ZZZ -> format(average, ‘.2f’))

Explanation

XXX should not be replaced with print(input(‘Enter next rating (1-5), -1 for done’)) as it will not capture the user input correctly. YYY should be replaced with print(‘The average star rating for the new coffee is: ‘ to display the output message. ZZZ should be replaced with format(average, ‘.2f’)) to round the average rating to two decimal places for proper formatting.

  1. XXX -> float(input(‘Enter next rating (1-5), -1 for done’))
  2. YYY -> output(‘The average star rating for the new coffee is: ‘
  3. ZZZ -> format(average, ‘.2d’))

Explanation

XXX should be replaced with float(input(‘Enter next rating (1-5), -1 for done’)) to accept user input for ratings. YYY should not be replaced with output as it is not a valid Python function. ZZZ should be replaced with format(average, ‘.2d’)) to round the average rating to two decimal places for proper formatting.

Correct answer

  1. XXX -> float(input(‘Enter next rating (1-5), -1 for done’))
  2. YYY -> print(‘The average star rating for the new coffee is: ‘
  3. ZZZ -> format(average, ‘.2f’))

Explanation

XXX should be replaced with float(input(‘Enter next rating (1-5), -1 for done’)) to accept user input for ratings. YYY should be replaced with print(‘The average star rating for the new coffee is: ‘ to display the output message. ZZZ should be replaced with format(average, ‘.2f’)) to round the average rating to two decimal places for proper formatting.

  1. XXX -> float(input(‘Enter next rating (1-5), -1 for done’))
  2. YYY -> print(‘The average star rating for the new coffee is: ‘
  3. ZZZ -> format(average, ‘.2d’))

Explanation

XXX should be replaced with float(input(‘Enter next rating (1-5), -1 for done’)) to accept user input for ratings. YYY should be replaced with print(‘The average star rating for the new coffee is: ‘ to display the output message. ZZZ should be replaced with format(average, ‘.2d’)) to round the average rating to two decimal places for proper formatting.

Overall explanation

Topics: while not equal to operator if

add and assign operator float()

division operator format()

plus operator string concatenation

Try it yourself:

  1. sum = count = done = 0

  2. average = 0.0

  3. while done != -1:

  4. rating = float(input('Enter next rating (1-5), -1 for done'))
    
  5. if rating == -1:
    
  6.     break
    
  7. sum += rating
    
  8. count += 1
    
  9. average = float(sum / count)

  10. print(‘The average star rating for the new coffee is: ‘

  11.   + format(average, '.2f'))
    
  12. format(average, ‘.2d’) -> ValueError: …

Explanation:

The input() function always returns a string

You need to cast that string to a float with the float() function.

The function to print something to the monitor is called print()

And if you want to round a float to two decimal places,

you need the format string '.2f'

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

Domain

05 – Control Flow

Question 12Skipped

Q149 – Modules

What is the expected output of the following code?

  1. import math

  2. result = math.e != math.pow(2, 4)

  3. print(int(result))

False

Explanation

The code imports the math module and compares the constant ‘e’ with the result of 2 raised to the power of 4. Since the comparison is true, the result variable will be assigned a boolean value of True. When this boolean value is converted to an integer using the int() function, it will result in 1, not the boolean value False.

True

Explanation

The code imports the math module and compares the constant ‘e’ with the result of 2 raised to the power of 4. Since the comparison is true, the result variable will be assigned a boolean value of True, not the string ‘True’. When this boolean value is converted to an integer using the int() function, it will result in 1.

0

Explanation

The code imports the math module and compares the constant ‘e’ with the result of 2 raised to the power of 4. Since the comparison is true, the result variable will be assigned a boolean value of True. However, when converting True to an integer using the int() function, it will result in 1, not 0.

Correct answer

1

Explanation

The code imports the math module and compares the constant ‘e’ with the result of 2 raised to the power of 4. Since the comparison is true, the result variable will be assigned a boolean value of True, which is then converted to an integer using the int() function, resulting in the output of 1.

Overall explanation

Topics: import math math.e math.pow() int()

Try it yourself:

  1. import math
  2. result = math.e != math.pow(2, 4)
  3. print(int(result)) # 1
  4. print(math.e) # 2.718281828459045
  5. print(math.pow(2, 4)) # 16.0
  6. print(pow(2, 4)). # 16

Explanation:

The mathematical constant e is 2.718281828459045

It is true, that is not 16.0 like math.pow(2, 4)

The integer value of True is 1

By the way, there is also a Python built-in function pow()

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

Domain

09 – Modules

Question 13Skipped

Q122 – Control Flow

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

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

one

Explanation

The code prints ‘‘ in each iteration of the loop. However, since i is incremented by 2 in each iteration and starts at 0, the loop will only run for two iterations, printing ‘‘ twice before the condition i <= 3 becomes false.

Correct answer

two

Explanation

The code starts with i=0 and enters the while loop. Inside the loop, i is incremented by 2 in each iteration. Therefore, the loop will run for two iterations, printing ‘*’ twice before the condition i <= 3 becomes false.

three

Explanation

The code does print ‘‘ in each iteration of the loop. However, since i is incremented by 2 in each iteration and starts at 0, the loop will only run for two iterations, printing ‘‘ twice before the condition i <= 3 becomes false.

zero

Explanation

The code does not print any stars before the condition i <= 3 becomes false. Since i is incremented by 2 in each iteration and starts at 0, the loop will not run long enough to print any stars.

Overall explanation

Topic: while

Try it yourself:

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

Explanation:

In the first iteration of the while loop i is 0

i becomes 2 and the first star is printed.

In the second iteration of the while loop i is 2

i becomes 4 and the second star is printed.

i is 4 and therefore 4 <= 3 is False what ends the while loop.

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

Domain

05 – Control Flow

Question 14Skipped

Q109 – Data Aggregates

What is the expected output of the following code?

  1. list1 = [1, 3]
  2. list2 = list1
  3. list1[0] = 4
  4. print(list2)

[1, 4]

Explanation

This choice is incorrect because the value at index 0 of list1 is changed to 4, not 1. As list2 is a reference to list1, the output will be [4, 3], not [1, 4].

Correct answer

[4, 3]

Explanation

The code creates a list list1 with elements [1, 3] and assigns it to list2. When the value at index 0 of list1 is changed to 4, it also affects list2 since they both refer to the same list object. Therefore, the expected output is [4, 3].

[1, 3]

Explanation

This choice is incorrect because the value at index 0 of list1 is modified to 4 before printing list2. Since list2 is a reference to list1, the output will be [4, 3], not [1, 3].

[1, 3, 4]

Explanation

This choice is incorrect because the code only modifies the value at index 0 of list1 to 4. It does not add an additional element to the list. Therefore, the expected output is [4, 3], not [1, 3, 4].

Overall explanation

Topics: list reference of a mutable data type

Try it yourself:

  1. list1 = [1, 3]
  2. list2 = list1
  3. list1[0] = 4
  4. print(list2) # [4, 3]
  5. print(id(list1)) # e.g. 140539383947452
  6. print(id(list2)) # e.g. 140539383947452 (the same number)

Explanation:

A list is mutable.

When you assign it to a different variable,

you create a reference of the same object.

If afterwards you change one of them, the other one is changed too.

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

Domain

04 – Data Aggregates

Question 15Skipped

Q129 – Data Types

The value thirty point eleven times ten raised to the power of nine

should be written as:

30.11*10^9

Explanation

The notation 30.11*10^9 is not the correct representation of the value thirty point eleven times ten raised to the power of nine in scientific notation. Scientific notation uses "E" to indicate the power of ten, not "*10^".

30E11.9

Explanation

The notation 30E11.9 is not the correct representation of the value thirty point eleven times ten raised to the power of nine in scientific notation. It does not follow the standard format for expressing numbers in scientific notation.

30.11E9.0

Explanation

The notation 30.11E9.0 is not the correct representation of the value thirty point eleven times ten raised to the power of nine in scientific notation. The ".0" at the end is unnecessary and does not conform to the standard format for scientific notation.

Correct answer

30.11E9

Explanation

The correct scientific notation for the value thirty point eleven times ten raised to the power of nine is 30.11E9. This notation represents the number in a concise and standard format for large numbers in scientific calculations.

Overall explanation

Topic: scientific notation

Try it yourself:

  1. print(30.11E9) # 30110000000.0

  2. print(30E11.9) # SyntaxError: invalid syntax

  3. print(30.11E9.0) # SyntaxError: invalid syntax

  4. print(30.11*10^9) # TypeError: unsupported operand …

  5. print(30.11 * 10 ** 9) # 30110000000.0

Explanation:

You could replace the E by * 10 **

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

Domain

02 – Data Types

Question 16Skipped

Q137 – Functions

What is the expected output of the following code?

  1. def func(p1, p2):

  2. p1 = 1
    
  3. p2[0] = 42
    
  4. x = 3

  5. y = [1, 2, 3]

  6. func(x, y)

  7. print(x, y[0])

3 1

Explanation

This choice is incorrect because the value of x (3) remains unchanged after the function call. Only the first element of the list y is modified to 42. Therefore, the output is not 3 1.

The code is erroneous.

Explanation

This choice is incorrect because the code is not erroneous. The function func is defined correctly and called with appropriate arguments. The output can be determined based on the function’s behavior.

1 42

Explanation

This choice is incorrect because the value of x (p1) is not modified inside the function. The first element of the list y (p2) is changed to 42, so the output is not 1 42.

1 1

Explanation

This choice is incorrect because the function does not modify the value of x (p1) inside the function. Only the first element of the list y (p2) is modified. Therefore, the output is not 1 1.

Correct answer

3 42

Explanation

The code defines a function func that takes two parameters p1 and p2. Inside the function, p1 is reassigned to 1, but the first element of p2 is modified to 42. When the function is called with x and y as arguments, x remains unchanged (3), but the first element of y is modified to 42. Therefore, the expected output is 3 42.

Overall explanation

Topics: def list argument passing mutable vs. immutable

Try it yourself:

  1. def func(p1, p2):

  2. p1 = 1
    
  3. p2[0] = 42
    
  4. x = 3

  5. y = [1, 2, 3]

  6. func(x, y)

  7. print(x, y[0]) # 3 42

Explanation:

This question is about argument passing.

It is a big difference, whether you pass a mutable or an immutable data type.

The immutable integer in x gets copied to p1

and the change of p1 does not effect x

The mutable list in y gets referenced to p2

and the change of p2 effect y

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

Domain

06 – Functions

Question 17Skipped

Q117 – Data Aggregates

What is the expected output of the following code?

print(list('hello'))

None of the above.

Explanation

This choice is incorrect because one of the previous choices must be correct based on the expected output of the code. Since choice A accurately represents the output of the code, it is the correct choice.

hello

Explanation

This choice is incorrect because it does not represent the output of the code correctly. The code will not print the string ‘hello’ as it is, but rather convert it into a list of characters.

[h, e, l, l, o]

Explanation

This choice is incorrect because the characters ‘h’, ‘e’, ‘l’, ‘l’, ‘o’ should be enclosed in quotation marks to indicate that they are strings. Without the quotation marks, they are considered as variables, which would result in a NameError.

Correct answer

['h', 'e', 'l', 'l', 'o']

Explanation

The list() function converts the string ‘hello’ into a list of individual characters, resulting in [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]. This is the correct syntax for creating a list of characters from a string.

['h' 'e' 'l' 'l' 'o']

Explanation

This choice is incorrect because the characters in the list should be separated by commas to indicate individual elements. The lack of commas between the characters would result in a syntax error.

Overall explanation

Topic: list()

Try it yourself:

print(list('hello'))  # ['h', 'e', 'l', 'l', 'o']

Explanation:

A string is a sequence of characters

and works very fine with the list() function.

The result is a list of strings, in which every character is a string of its own.

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

Domain

04 – Data Aggregates

Question 18Skipped

Q152 – Functions

isalnum() checks if a string contains only letters and digits, and this is:

Correct answer

A method

Explanation

The isalnum() method is a built-in method in Python that belongs to the string class. It is used to check if a string contains only alphanumeric characters (letters and digits). As a method, it is called on a specific string object using dot notation, such as "my_string.isalnum()".

A function

Explanation

While isalnum() performs a specific task and is called using dot notation like a function, it is technically a method because it is associated with a specific data type (string). Methods are functions that are associated with objects and are called using dot notation on instances of that object.

A module

Explanation

The isalnum() function is not a standalone function that can be called independently in Python. Instead, it is a method that is part of the built-in string class. Modules in Python are files containing Python code that can be imported and used in other Python programs, which is not the case for isalnum().

Overall explanation

Topic: isalnum()

Try it yourself:

  1. print(‘James007’.isalnum()) # True
  2. print(‘Hello world’.isalnum()) # False

Explanation:

isalnum() is a String-Method.

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

'Hello world' is not alphanumeric, because of the space character.

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

Domain

06 – Functions

Question 19Skipped

Q120 – Basics

What is the expected output of the following code?

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

2 1 2

Explanation

This choice is incorrect because the code assigns the values of x, x, and y to x, y, and z respectively, resulting in x=1, y=1, z=2. Then, it reassigns the values of x, y, and z to z, y, and z respectively, resulting in x=1, y=1, z=2. Therefore, the output of the code is not 2 1 2.

Correct answer

1 1 2

Explanation

The code assigns the values of x, x, and y to x, y, and z respectively, resulting in x=1, y=1, z=2. Then, it reassigns the values of x, y, and z to z, y, and z respectively, resulting in x=1, y=1, z=2. Therefore, the output of the code is 1 1 2.

1 2 1

Explanation

This choice is incorrect because the code assigns the values of x, x, and y to x, y, and z respectively, resulting in x=1, y=1, z=2. Then, it reassigns the values of x, y, and z to z, y, and z respectively, resulting in x=1, y=1, z=2. Therefore, the output of the code is not 1 2 1.

1 2 2

Explanation

This choice is incorrect because the code assigns the values of x, x, and y to x, y, and z respectively, resulting in x=1, y=1, z=2. Then, it reassigns the values of x, y, and z to z, y, and z respectively, resulting in x=1, y=1, z=2. Therefore, the output of the code is not 1 2 2.

Overall explanation

Topic: multiple assignments

Try it yourself:

  1. x = 1
  2. y = 2
  3. x, y, z = x, x, y

  4. x, y, z = 1, 1, 2 # -> x=1; y=1; z=2
  5. z, y, z = x, y, z

  6. z, y, z = 1, 1, 2 # -> y=1; z=2
  7. z will be 1 first and then become 2

  8. x is still 1

  9. print(x, y, z) # 1 1 2

Explanation:

We have multiple assignment in Python.

You can assign multiple values to multiple variables.

a, b = 3, 7

It is just shorter than

  1. a = 3
  2. b = 7

It does not have practical use, but what also works is

c, c = 23, 42

First c becomes 23 and then c becomes 42

You better write

c = 42

The same happens in this question in

z, y, z = 1, 1, 2

First z becomes 1 and then z becomes 2 You can also assign the same value to multiple variables:

  1. a = b = c = d = 1
  2. print(a, b, c, d) # 1 1 1 1

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

Domain

01 – Basics

Question 20Skipped

Q139 – Control Flow

What is the expected output of the following code?

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

  2. def func(data):

  3. res = data[0][0]
    
  4. for da in data:
    
  5.     for d in da:
    
  6.         if res < d:
    
  7.             res = d
    
  8. return res
    
  9. print(func(x[0]))

6

Explanation

The code does not return the maximum value of the entire input list ‘x’. Instead, it only considers the elements in the first sublist of ‘x[0]’. The maximum value in the second sublist [5, 6] is 6, so this choice is incorrect.

The code is erroneous.

Explanation

The code is not erroneous; it correctly iterates through the nested list ‘x’ and finds the maximum value in the first sublist of ‘x[0]’. The expected output is 4, so this choice is incorrect.

Correct answer

4

Explanation

The code initializes the variable ‘res’ with the first element of the first sublist of the input list ‘data’. It then iterates through each sublist in ‘data’ and each element in those sublists. If the current element is greater than ‘res’, ‘res’ is updated to that element. In this case, the maximum value in the first sublist [1, 2] is 2, and the maximum value in the second sublist [3, 4] is 4. Therefore, the expected output is 4.

8

Explanation

The code does not return the maximum value of the entire input list ‘x’. Instead, it only considers the elements in the first sublist of ‘x[0]’. The maximum value in the second sublist [7, 8] is 8, so this choice is incorrect.

2

Explanation

The code does not return the maximum value of the entire input list ‘x’. Instead, it only considers the elements in the first sublist of ‘x[0]’. The maximum value in the first sublist [1, 2] is 2, so this choice is incorrect.

Overall explanation

Topics: def for if list

Try it yourself:

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

  2. def func(data):

  3. print('data:', data)    # [[1, 2], [3, 4]]
    
  4. res = data[0][0]        # 1
    
  5. print('res:', res)
    
  6. for da in data:
    
  7.     print('da:', da)    # [1, 2] -> [3, 4]
    
  8.     for d in da:
    
  9.         print('d:', d)  # 1 -> 2 -> 3 -> 4
    
  10.         if res < d:
    
  11.             res = d
    
  12. return res
    
  13. print(func(x[0])) # 4

  14. print(func([[1, 7], [3, 4]])) # 7

Explanation:

This function looks for the highest element

in a two dimensional list (or another iterable).

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 higher it becomes the new possible result.

And in the end the result is the highest number.

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

Domain

05 – Control Flow

Question 21Skipped

Q118 – Control Flow

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

  1. i = 4

  2. while i > 0:

  3. i -= 2
    
  4. print('*')
    
  5. if i == 2:
    
  6.     break
    
  7. else:

  8. print('*')
    

0

Explanation

The snippet will not print 0 stars. The while loop will execute at least once since i is initially 4, and it will print a star before the condition check. Therefore, at least one star will be printed.

2

Explanation

The snippet will not print 2 stars. The loop will print a star each time it iterates, and it will break when i becomes 2. Therefore, only 1 star will be printed.

The snippet will enter an infinite loop.

Explanation

The snippet will not enter an infinite loop. The loop will terminate when i becomes 2 due to the break statement, preventing it from running indefinitely.

Correct answer

1

Explanation

The snippet will print 1 star to the monitor. The while loop will run as long as i is greater than 0. It will decrement i by 2 in each iteration and print a star. When i becomes 2, the loop will break, and the final star will be printed outside the loop.

Overall explanation

Topics: if while break else (nobreak)

Try it yourself:

  1. i = 4
  2. while i > 0: # i is 4
  3. i -= 2      # i is 2
    
  4. print('*')  # *
    
  5. if i == 2:  # Yip, i is 2
    
  6.     break   # Leave the loop directly
    
  7. else: # Does not apply, because the break got triggered
  8. print('*')
    

Explanation:

In the first iteration the break gets directly triggered.

Therefore there will be only one star.

The else would only apply, if the break does NOT get triggered.

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

Domain

05 – Control Flow

Question 22Skipped

Q153 – Error Handling

Entering the try: block implies that:

the block will be omitted.

Explanation

The statement that the try block will be omitted is incorrect. The try block is an essential part of error handling in Python, allowing the programmer to anticipate and handle potential exceptions that may occur during the execution of the code. Omitting the try block would mean not handling any exceptions that may arise.

Correct answer

some of the instructions from this block may not be executed.

Explanation

When entering the try block in Python, it means that some of the instructions within the block may not be executed if an exception occurs during the execution of the block. The try block allows for the handling of potential errors or exceptions that may arise during the execution of the code.

none of the instructions from this block will be executed.

Explanation

It is not accurate to say that none of the instructions from the try block will be executed. The try block is designed to execute the code within it, and it will attempt to execute all instructions unless an exception occurs. In the event of an exception, the execution may be interrupted, but not all instructions will be skipped.

all of the instructions from this block will be executed.

Explanation

Entering the try block does not guarantee that all instructions within the block will be executed. If an exception occurs during the execution of the block, the remaining instructions may not be executed. The purpose of the try block is to catch and handle exceptions that may occur.

Overall explanation

Topic: try

Try it yourself:

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

Explanation:

In this case the multiplication and the printing

will not be executed,

because the type casting will already raise an exception.

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

Domain

08 – Error Handling

Question 23Skipped

Q145 – I/O

You want to write a code snippet to read the total data from a text file

and print it to the monitor.

What snippet would you insert in the line indicated below:

  1. try:
  2. file = open('data.txt', 'r')
    
  3. # insert your code here
    
  4. print(data)
    
  5. except:
  6. print('Something went wrong!')
    

data = file.readlines()

Explanation

The file.readlines() method reads all lines from the file and returns them as a list. While this method can be used to read the total data, it would require additional processing to concatenate the lines into a single string before printing to the monitor.

data = file.load()

Explanation

There is no file.load() method in Python’s file handling operations. Using this method would result in a syntax error or an exception, as it is not a valid method for reading file data. The correct method to read file data is file.read().

Correct answer

data = file.read()

Explanation

The correct choice is to use file.read() to read the total data from the text file. This method reads the entire file content as a single string and is suitable for printing the total data to the monitor in one go.

data = file.readline()

Explanation

The file.readline() method reads a single line from the file, not the total data. Using this method would only print one line of data to the monitor, which is not the desired outcome in this scenario.

Overall explanation

Topics: open() read() try except

Try it yourself:

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

  2. text = ”’Lorem ipsum dolor sit amet,

  3. consectetur adipisicing elit,

  4. sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

  5. ”’

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

  7. f.write(text)
    
  8. try:

  9. file = open('wellert.txt', 'r')
    
  10. data = file.read()         # works
    
  11. # data = file.readline()   # reads only one line
    
  12. # data = file.readlines()  # reads every line, but as a list
    
  13. # data = file.load()       # Something went wrong!
    
  14. print(data)
    
  15. except:

  16. print('Something went wrong!')
    

Explanation:

The read() method is the right choice here.

It reads the whole content of a file and returns it as a string.

The readline() method only reads one line.

The readlines() method also reads the whole content,

but returns it as a list of lines.

That is definitely not wanted here.

And load() is not a method of the file object.

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

Domain

07 – I/O

Question 24Skipped

Q104 – Data Aggregates

What will be the output of the following code snippet?

  1. a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  2. print(a[::2])

[1, 2]

Explanation

This choice is incorrect because the code snippet uses slicing with a step of 2 (a[::2]), which means it will select every second element in the list. Therefore, the output will not be [1, 2].

Correct answer

[1, 3, 5, 7, 9]

Explanation

The code snippet uses slicing with a step of 2 (a[::2]), which means it will start from the beginning of the list and select every second element. Therefore, the output will be [1, 3, 5, 7, 9].

[1, 2, 3]

Explanation

This choice is incorrect because the code snippet uses slicing with a step of 2 (a[::2]), which means it will select every second element in the list. Therefore, the output will not be [1, 2, 3].

[8, 9]

Explanation

This choice is incorrect because the code snippet uses slicing with a step of 2 (a[::2]), which means it will select every second element in the list. Therefore, the output will not be [8, 9].

Overall explanation

Topic: list slicing

Try it yourself:

  1. a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  2. print(a[::2]) # [1, 3, 5, 7, 9]

Explanation:

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

The start and end values are missing here.

If you leave them out, you will slice from the beginning to the end.

If you leave the end out it will also be inclusive.

The third value (the step) is 2 therefore every second element gets taken.

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

Domain

04 – Data Aggregates

Question 25Skipped

Q110 – Data Types

Consider the following code snippet:

  1. w = bool(23)
  2. x = bool(”)
  3. y = bool(‘ ‘)
  4. z = bool([False])

Which of the variables will contain False?

w

Explanation

The variable w will contain True because the bool(23) function will return True for any non-zero number.

y

Explanation

The variable y will contain True because the bool(‘ ‘) function will return True for a string with whitespace characters.

Correct answer

x

Explanation

The variable x will contain False because the bool(”) function will return False for an empty string.

z

Explanation

The variable z will contain True because the bool([False]) function will return True for a non-empty list, regardless of the values inside the list.

Overall explanation

Topic: type casting with bool()

Try it yourself:

  1. print(bool(23)) # True
  2. print(bool(”)) # False
  3. print(bool(‘ ‘)) # True
  4. print(bool([False])) # True

Explanation:

The list with the value False is not empty and therefore it becomes True

The string with the space also contain one character

and therefore it also becomes True

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

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

Domain

02 – Data Types

Question 26Skipped

Q102 – Operators

What will be the output of the following code snippet?

  1. x = 2
  2. y = 1
  3. x *= y + 1
  4. print(x)

Correct answer

4

Explanation

The code snippet calculates the value of x by multiplying x with y + 1. Since x is initially 2 and y is 1, the calculation becomes x * (1 + 1) = 2 * 2 = 4, resulting in the output of 4.

1

Explanation

This choice is incorrect because the code snippet involves multiplying x by y + 1, not just y. Therefore, the output will not be 1.

2

Explanation

This choice is incorrect because the code snippet involves multiplying x by y + 1, not just y. Therefore, the output will not be 2.

None

Explanation

This choice is incorrect because the code snippet calculates a value for x and prints it. The output will not be None as the code snippet performs a calculation and prints the result.

3

Explanation

This choice is incorrect because the code snippet involves multiplying x by y + 1, not just y. Therefore, the output will not be 3.

Overall explanation

Topics: addition operator multiply and assign operator

operator precedence

Try it yourself:

  1. x = 2
  2. y = 1
  3. x *= y + 1

  4. x = x * (y + 1)
  5. print(x) # 4

Explanation:

The operator precedence of the addition operator is higher than

the operator precedence of the multiply and assign operator

That means the addition takes place before the multiplication.

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

Domain

03 – Operators

Question 27Skipped

Q156 – Data Aggregates

A data structure described as LIFO is actually a:

heap

Explanation

A heap is a specialized tree-based data structure that satisfies the heap property. Heaps are commonly used to implement priority queues, where elements are removed based on their priority level. While a heap is a type of tree, it does not strictly adhere to the LIFO principle like a stack does.

Correct answer

stack

Explanation

A stack is a data structure that follows the Last In, First Out (LIFO) principle, meaning that the last element added to the stack is the first one to be removed. This makes it suitable for tasks such as managing function calls, undo mechanisms, and backtracking algorithms.

list

Explanation

A list is a data structure that does not necessarily follow the LIFO principle. Lists in Python are ordered collections of items, where elements can be added or removed at any position. Unlike a stack, a list does not have a specific order for adding or removing elements.

tree

Explanation

A tree is a hierarchical data structure that consists of nodes connected by edges. Trees are used to represent hierarchical relationships between data elements, such as in file systems or organizational structures. Unlike a stack, a tree does not operate based on the LIFO principle.

Overall explanation

Topic: LIFO stack

Explanation:

Read about it here:

https://en.wikipedia.org/wiki/Stack_(abstract_data_type)

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

Domain

04 – Data Aggregates

Question 28Skipped

Q126 – Error Handling

What is the expected output of the following code?

  1. def func(x):

  2. try:
    
  3.     x = x / x
    
  4. except:
    
  5.     print('a', end='')
    
  6. else:
    
  7.     print('b', end='')
    
  8. finally:
    
  9.     print('c', end='')
    
  10. func(1)

  11. func(0)

acac

Explanation

This choice is incorrect because it does not account for the ‘b’ that should be printed when func(1) is called and the division operation is successful.

bcbc

Explanation

This choice is incorrect because it does not account for the ‘a’ that should be printed when func(0) is called and the division operation raises an exception.

bca

Explanation

This choice is incorrect because it does not account for the ‘b’ that should be printed when func(1) is called and the division operation is successful.

Correct answer

bcac

Explanation

The code defines a function func(x) that tries to perform a division operation x / x. When func(1) is called, the division is successful (1 / 1 = 1), so the else block is executed, printing ‘b’. The finally block is always executed, printing ‘c’. When func(0) is called, the division by zero causes an exception to be raised, so the except block is executed, printing ‘a’. The finally block is still executed, printing ‘c’.

bac

Explanation

This choice is incorrect because it does not account for the ‘b’ that should be printed when func(1) is called and the division operation is successful, followed by ‘c’ in the finally block.

Overall explanation

Topics: def try except else finally ZeroDivisionError

Try it yourself:

  1. def func(x):

  2. try:
    
  3.     x = x / x
    
  4. except:
    
  5.     print('a', end='')
    
  6. else:
    
  7.     print('b', end='')
    
  8. finally:
    
  9.     print('c', end='')
    
  10. func(1) # bc

  11. x = 1 / 1 -> does not raise an exception

  12. Therefore the else block gets executed -> b

  13. and the finally block always gets executed -> c

  14. func(0) # ac

  15. x = 0 / 0 raises a ZeroDivisionError

  16. Therefore the except block gets executed -> a

  17. and the finally block always gets executed -> c

Explanation:

func(1) will try to execute 1 / 1

That will work fine and therefore not the except block,

but the else block will be executed -> b

The finally block always gets executed -> c

func(0) will try to execute 1 / 0

That can not work.

In Python (like in any programming language) you can not divide by zero.

In Python a ZeroDivisionError is raised

and the except block is executed -> a

Therefore the else block is not executed.

And again the finally block always gets executed -> c

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

Domain

08 – Error Handling

Question 29Skipped

Q125 – I/O

What is the expected output of the following code?

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

  2. print(‘Name of the file: ‘, file.name)

  3. s = ‘Peter Wellert\nHello everybody’

  4. file.write(s)

  5. file.seek(0)

  6. for line in file:

  7. print(line)
    
  8. file.close()

The code is erroneous.

Explanation

The code is not erroneous. It opens a file, writes to it, reads its contents, and then closes it. The code will execute without any errors and produce the expected output.

Correct answer

  1. Name of the file: data.txt

  2. Peter Wellert

  3. Hello everybody

Explanation

The code opens a file named ‘data.txt’ in write mode (‘w+’), prints the name of the file as ‘data.txt’, writes the string ‘Peter Wellert\nHello everybody’ to the file, moves the file cursor to the beginning (position 0), and then reads the contents of the file line by line. The output will be ‘Peter Wellert’ on the first line and ‘Hello everybody’ on the second line.

  1. Peter Wellert
  2. Hello everybody

Explanation

This choice does not accurately represent the expected output of the code. The code reads the contents of the file line by line, so the output will be ‘Peter Wellert’ on the first line and ‘Hello everybody’ on the second line.

  1. Peter Wellert Hello everybody

Explanation

This choice does not accurately represent the expected output of the code. The code reads the contents of the file line by line, so the output will be ‘Peter Wellert’ on the first line and ‘Hello everybody’ on the second line.

Overall explanation

Topics: open() writelines() seek() close() file.name for

Try it yourself:

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

  2. print(‘Name of the file: ‘, file.name) # Name of the file: data.txt

  3. s = ‘Peter Wellert\nHello everybody’

  4. file.write(s)

  5. """

  6. The contents of the file will look like that:

  7. Peter Wellert

  8. Hello everybody

  9. (with an unvisible newline character at the end of the first line)

  10. """

  11. The file position gets set back to the beginning of the file:

  12. file.seek(0)

  13. The for loop iterates through the file line by line:

  14. for line in file:

  15. print(line)
    
  16. """

  17. Output of the for loop:

  18. Peter Wellert

  19. Hello everybody

  20. """

  21. file.close()

Explanation:

open() with the mode w+ opens a file for writing and reading.

If the file doesn’t exist, it will be created.

First something gets written into the file.

Then the file pointer gets set back to the beginning.

And then the file gets iterated line by line by the for loop.

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

Domain

07 – I/O

Question 30Skipped

Q121 – Control Flow

What is the expected output of the following code?

  1. def func(x):

  2. return 1 if x % 2 != 0 else 2
    
  3. print(func(func(1)))

None

Explanation

This choice is incorrect because the code does not result in a None output. The function func() will always return either 1 or 2 based on the input provided.

2

Explanation

This choice is incorrect because the function func() returns 1 when the input is odd and 2 when the input is even. Since the input to the inner func() call is 1 (an odd number), the output will be 1, not 2.

The code is erroneous.

Explanation

This choice is incorrect because the code is not erroneous. The function func() is defined correctly, and the code will run without any errors. The expected output can be determined by evaluating the function calls.

Correct answer

1

Explanation

The function func() takes an input x and returns 1 if x is odd (i.e., x % 2 != 0), and returns 2 if x is even. When func(1) is called, it returns 1 since 1 is an odd number. Therefore, func(func(1)) is equivalent to func(1), which will output 1.

Overall explanation

Topics: def conditional expression (if else) modulus operator

not equal to operator

Try it yourself:

  1. def func(x):

  2. return 1 if x % 2 != 0 else 2
    
  3. print(func(func(1))) # 1

  4. print(1 % 2) # 1

  5. print(1 % 2 != 0) # True

Explanation:

This is a conditional expression.

1 % 2 is 1 and therefore not equal to 0

The condition is True and the inner func() function call returns 1

That 1 is passed to the outer function which will also return 1

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

Domain

05 – Control Flow

Question 31Skipped

Q130 – Data Types

The 0o prefix means that the number after it is denoted as:

decimal

Explanation

Decimal numbers are the standard numerical representation in Python and most programming languages. They do not require any special prefix to denote them, as they are assumed to be in base-10 by default.

hexadecimal

Explanation

Hexadecimal numbers in Python are represented with the 0x prefix, not the 0o prefix. Hexadecimal numbers are base-16 numbers, using digits from 0 to 9 and letters from A to F to represent values greater than 9. They are commonly used in programming for memory addresses and color codes.

binary

Explanation

Binary numbers are represented with the 0b prefix in Python, not the 0o prefix. Binary numbers are base-2 numbers, using only 0s and 1s, and are often used in computer science and digital electronics.

Correct answer

octal

Explanation

The 0o prefix in Python indicates that the number following it is in octal format. Octal numbers are base-8 numbers, using digits from 0 to 7, and are commonly used in programming for bitwise operations and permissions settings.

Overall explanation

Topic: octal notation

Try it yourself:

  1. print(0o10) # 8
  2. print(0o77) # 63

Explanation:

The octal numeral system, or oct for short,

is the base-8 number system, and uses the digits 0 to 7

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

Domain

02 – Data Types

Question 32Skipped

Q151 – Error Handling

The part of your code where you think an exception may occur should be placed inside:

Correct answer

the try: branch

Explanation

The try block is where you place the code that you think may raise an exception. By placing this code inside the try block, you are indicating to Python that it should attempt to execute this code, and if an exception occurs, it will be caught by the corresponding except block.

the except: branch

Explanation

The except block is used to handle exceptions that occur within the corresponding try block. By placing the code that may raise an exception inside the try block, you are preparing for the possibility of an exception and providing a specific block of code to handle it in the except block.

the exception: branch

Explanation

The exception block is not a valid Python construct for handling exceptions. The correct syntax for handling exceptions involves using the try and except blocks. The try block contains the code that may raise an exception, while the except block is where you handle the exception if it occurs.

Overall explanation

Topics: try except

Try it yourself:

  1. try:

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

  7. print('Something went wrong.')
    
  8. zahl = int(‘one’) # ValueError: …

Explanation:

Therefore the name try

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

Domain

08 – Error Handling

Question 33Skipped

Q101 – Operators

What will be the output of the following code snippet?

print(3 / 5)

6/10

Explanation

The expression 6/10 is not the correct output for the division operation between 3 and 5 in the given code snippet. The correct result is 0.6, not the fraction 6/10.

0

Explanation

The division operation between 3 and 5 in Python will not result in an integer value of 0. Instead, it will yield a floating-point number of 0.6 due to Python’s behavior of performing true division when dividing two integers.

Correct answer

0.6

Explanation

The output of the division operation between 3 and 5 in Python will result in a floating-point number, which is 0.6. This is because Python performs true division when dividing two integers, resulting in a float value if the division does not yield a whole number.

None of the above.

Explanation

The output of the division operation between 3 and 5 in the given code snippet is 0.6, which is one of the choices provided. Therefore, "None of the above" is not the correct option as there is a matching choice for the output.

Overall explanation

Topic: division operator

Try it yourself:

  1. print(3 / 5) # 0.6
  2. print(4 / 2) # 2.0

Explanation:

The division operator does its normal job.

And remember the division operator ALWAYS returns a float.

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

Domain

03 – Operators

Question 34Skipped

Q127 – Error Handling

What is the expected output of the following code?

  1. def func():

  2. try:
    
  3.     print(23)
    
  4. finally:
    
  5.     print(42)
    
  6. func()

42

Explanation

This choice is incorrect because it only includes the output of the print(42) statement inside the finally block and does not consider the initial print(23) statement, which is expected to be printed before 42.

  1. 42
  2. 23

Explanation

This choice is incorrect because it swaps the order of the expected output. The print(23) statement is expected to be executed before the print(42) statement inside the finally block.

23

Explanation

This choice is incorrect because it only includes the output of the print(23) statement and does not consider the execution of the print(42) statement inside the finally block, which is expected to be printed after 23.

None of the above.

Explanation

This choice is incorrect because one of the given choices (Choice A) is expected to be the correct output of the code.

Correct answer

  1. 23
  2. 42

Explanation

The expected output of the code is 23 followed by 42 because the print(23) statement is executed first inside the try block, and then the print(42) statement inside the finally block is executed regardless of whether an exception occurs or not.

Overall explanation

Topic: try finally

Try it yourself:

  1. def func():

  2. try:
    
  3.     print(23)  # 23
    
  4. finally:
    
  5.     print(42)  # 42
    
  6. func()

Explanation:

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

The finally block always gets execute.

(There are similar questions Q235 and Q351.)

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

Domain

08 – Error Handling

Question 35Skipped

Q112 – Operators

What would you insert instead of ???

so that the program checks for even numbers?

  1. if ???:
  2. print('x is an even number')
    

x % 1 == 2

Explanation

The expression x % 1 == 2 checks if the remainder of x divided by 1 is equal to 2, which is not a valid way to check for even numbers. This choice does not accurately determine if x is an even number.

x % 2 == 1

Explanation

The expression x % 2 == 1 checks if the remainder of x divided by 2 is equal to 1, which is not a valid way to check for even numbers. This choice does not accurately determine if x is an even number.

x % x == 0

Explanation

The expression x % x == 0 checks if the remainder of x divided by itself is equal to 0, which is not a valid way to check for even numbers. This choice does not accurately determine if x is an even number.

Correct answer

x % 2 == 0

Explanation

The expression x % 2 == 0 checks if the remainder of x divided by 2 is equal to 0, which is a common way to determine if a number is even in Python. This choice correctly evaluates whether x is an even number.

x % 'even' == True

Explanation

The expression x % ‘even’ == True is comparing x modulo ‘even’ to True, which is not a valid operation for checking if x is an even number. This choice does not accurately determine if x is an even number.

Overall explanation

Topics: if modulus operator equal to operator

Try it yourself:

  1. x = 4
  2. if x % 2 == 0:
  3. print('x is an even number')  # x is an even number
    

Explanation:

Every number that divided by two does not leave a rest is even.

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

Domain

03 – Operators

Question 36Skipped

Q108 – Data Aggregates

What will be the output of the following code snippet?

  1. d = {}

  2. d[1] = 1

  3. d[‘1’] = 2

  4. d[1] += 1

  5. sum = 0

  6. for k in d:

  7. sum += d[k]
    
  8. print(sum)

1

Explanation

The output will not be 1. The dictionary ‘d’ has two key-value pairs: {1: 2, ‘1’: 2}. When d[1] is incremented by 1, it becomes 3, not 1. Adding the values of the key-value pairs (2+1) gives a total of 3, not 1.

2

Explanation

The output will not be 2. The dictionary ‘d’ has two key-value pairs: {1: 2, ‘1’: 2}. When d[1] is incremented by 1, it becomes 3, not 2. Adding the values of the key-value pairs (2+1) gives a total of 3, not 2.

3

Explanation

The output will not be 3. The dictionary ‘d’ has two key-value pairs: {1: 2, ‘1’: 2}. When d[1] is incremented by 1, it becomes 3, not 2. Adding the values of the key-value pairs (2+1) gives a total of 3, not 2.

Correct answer

4

Explanation

The output will be 4 because the dictionary ‘d’ has two key-value pairs: {1: 2, ‘1’: 2}. When d[1] is incremented by 1, it becomes 2+1=3. Adding the values of the key-value pairs (2+1) gives a total of 4.

Overall explanation

Topics: for dictionary indexes add and assign operator

Try it yourself:

  1. d = {}

  2. print(d) # {}

  3. d[1] = 1

  4. print(d) # {1: 1}

  5. d[‘1’] = 2

  6. print(d) # {1: 1, ‘1’: 2}

  7. d[1] += 1

  8. print(d) # {1: 2, ‘1’: 2}

  9. sum = 0

  10. for k in d:

  11. sum += d[k]
    
  12. print("key: ", k, " - value: ", d[k])
    
  13. # key:  1  - value:  2
    
  14. print(sum) # 4

  15. sum = 0

  16. for k in d.keys():

  17. sum += d[k]
    
  18. print("key: ", k, " - value: ", d[k])
    
  19. # key:  1  - value:  2
    
  20. print(sum) # 4

Explanation:

The knowledge you need here is that a dictionary

can have indexes of different data types.

Therefore d[1] is a different index than d['1']

and they can both exist in the same dictionary.

To iterate through a dictionary is the same as

iterating through dict.keys()

In k will be the keys of the dictionary.

In this case 1 and '1'

The value of the first key will be 2

and the value of the other key will also be 2

and therefore (the) sum is 4

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

Domain

04 – Data Aggregates

Question 37Skipped

Q111 – Control Flow

What is the expected output of the following code?

  1. def func(text, num):

  2. while num > 0:
    
  3.     print(text)
    
  4. num = num - 1
    
  5. func(‘Hello’, 3)

Correct answer

An infinite loop.

Explanation

This code will result in an infinite loop because the condition num > 0 is never updated within the loop, causing it to continuously print the text variable without decrementing num.

  1. Hello
  2. Hello
  3. Hello

Explanation

This choice is incorrect because the code will not print the text variable three times as expected. Due to the missing decrement statement inside the loop, it will keep printing text indefinitely.

  1. Hello
  2. Hello
  3. Hello
  4. Hello

Explanation

This choice is incorrect because the code will not print the text variable three times as expected. Due to the missing decrement statement inside the loop, it will keep printing text indefinitely.

  1. Hello
  2. Hello

Explanation

This choice is incorrect because the code will not print the text variable two times as expected. Due to the missing decrement statement inside the loop, it will keep printing text indefinitely.

Overall explanation

Topics: def while indentation

Try it yourself:

  1. def func(text, num):
  2. while num > 0:
    
  3.     print(text)
    
  4. num = num - 1
    
  5. func(‘Hello’, 3) # An infinite loop

Explanation:

The incrementation of num needs to be inside of the while loop.

Otherwise the condition num > 0 will never be False

It should look like this:

  1. def func(text, num):
  2. while num > 0:
    
  3.     print(text)
    
  4.     num = num - 1
    
  5. func(‘Hello’, 3)
  6. """
  7. Hello
  8. Hello
  9. Hello
  10. """

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

Domain

05 – Control Flow

Question 38Skipped

Q119 – Operators

What value will be assigned to the x variable?

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

False

Explanation

The expression does not evaluate to False. The logical operators used in the expression will result in a True value based on the comparisons of y and z.

0

Explanation

The value assigned to the x variable is not 0. The expression evaluates to a boolean value (True or False) based on the comparisons of y and z, not an integer value.

1

Explanation

The value assigned to the x variable is not 1. The expression evaluates to a boolean value (True or False) based on the comparisons of y and z, not an integer value.

Correct answer

True

Explanation

The expression evaluates to True because the logical operators ‘and’ and ‘or’ are used to compare the values of y and z. Since the expression is a combination of multiple comparisons, the final result will be True if any of the conditions are met.

Overall explanation

Topic: greater than operator less than operator

logical and operators logical or operator

operator precedence

Try it yourself:

  1. z = 3

  2. y = 7

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

  4. print(x) # True

  5. print(y < z and z > y or y > z and z < y) # True

  6. print(7 < 3 and 3 > 7 or 7 > 3 and 3 < 7) # True

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

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

  9. print(False or True) # True

  10. print(True) # True

Explanation:

The operators here are from three different groups.

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

The two comparison operators

the greater than operator and the less than operator

have the highest precedence.

Then the logical and operator has a higher precedence

than the logical or operator

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

Domain

03 – Operators

Question 39Skipped

Q136 – Operators

What is the expected output of the following code?

x = 1 / 2 + 3 // 3 + 4 ** 2

print(x)

8.5

Explanation

The expected output of the code is not 8.5 because the expression is evaluated following the operator precedence rules in Python. The division operator (/) and floor division operator (//) have the same precedence, so they are evaluated from left to right. Then, the exponentiation operator (**) is evaluated. Finally, the addition operators are evaluated, resulting in a different value than 8.5.

17

Explanation

The expected output of the code is not 17 because the expression is evaluated following the operator precedence rules in Python. The division operator (/) and floor division operator (//) have the same precedence, so they are evaluated from left to right. Then, the exponentiation operator (**) is evaluated. Finally, the addition operators are evaluated, resulting in a different value than 17.

Correct answer

17.5

Explanation

The expected output of the code is 17.5 because the expression is evaluated from left to right following the operator precedence rules in Python. The division operator (/) and floor division operator (//) have the same precedence, so they are evaluated from left to right. Then, the exponentiation operator (**) is evaluated. Finally, the addition operators are evaluated.

8

Explanation

The expected output of the code is not 8 because the expression is evaluated following the operator precedence rules in Python. The division operator (/) and floor division operator (//) have the same precedence, so they are evaluated from left to right. Then, the exponentiation operator (**) is evaluated. Finally, the addition operators are evaluated, resulting in a different value than 8.

Overall explanation

Topics: arithmetic operators operator precedence

Try it yourself:

  1. x = 1 / 2 + 3 // 3 + 4 ** 2

  2. print(x) # 17.5

  3. print(1 / 2 + 3 // 3 + 4 ** 2) # 17.5

  4. print(1 / 2 + 3 // 3 + (4 ** 2)) # 17.5

  5. print(1 / 2 + 3 // 3 + 16) # 17.5

  6. print((1 / 2) + 3 // 3 + 16) # 17.5

  7. print(0.5 + 3 // 3 + 16) # 17.5

  8. print(0.5 + (3 // 3) + 16) # 17.5

  9. print(0.5 + 1 + 16) # 17.5

  10. print((0.5 + 1) + 16) # 17.5

  11. print(1.5 + 16) # 17.5

  12. print(17.5) # 17.5

Explanation:

The operators here come from three different groups:

"Exponent" has the highest precedence.

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

"Addition, Subtraction" has the lowest precedence.

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

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

Domain

03 – Operators

Question 40Skipped

Q138 – Modules

What is the correct command to shuffle the following list?

  1. import random
  2. people = [‘Peter’, ‘Paul’, ‘Mary’, ‘Jane’]

shuffle(people)

Explanation

The command ‘shuffle(people)’ is incorrect because the shuffle function is part of the random module in Python. Therefore, the correct syntax should include the module name ‘random’ before calling the shuffle function.

people.shuffle()

Explanation

The command ‘people.shuffle()’ is incorrect because the shuffle method is not a built-in method of the list object in Python. Instead, the shuffle function is part of the random module and should be called using ‘random.shuffle(people)’.

random.shuffleList(people)

Explanation

The command ‘random.shuffleList(people)’ is incorrect because there is no function named ‘shuffleList’ in the random module. The correct syntax to shuffle a list using the random module is ‘random.shuffle(people)’.

Correct answer

random.shuffle(people)

Explanation

The correct command to shuffle a list using the random module is ‘random.shuffle(people)’. This function shuffles the elements of the list ‘people’ in place, meaning it directly modifies the original list.

Overall explanation

Topics: from import random shuffle() list

Try it yourself:

  1. import random

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

  3. random.shuffle(people)

  4. print(people) # e.g. [‘Mary’, ‘Jane’, ‘Peter’, ‘Paul’]

  5. people.shuffle() # AttributeError: …

  6. random.shuffleList(people) # AttributeError: …

  7. shuffle(people) only works with the following import:

  8. from random import shuffle

  9. shuffle(people)

  10. print(people) # e.g. [‘Paul’, ‘Peter’, ‘Jane’, ‘Mary’]

Explanation:

import random imports the whole module.

If you want to use one of its methods, you have to add it by dot notation.

The shuffle() method will change the original list in-place.

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

Domain

09 – Modules

Question 41Skipped

Q114 – Control Flow

Which of the following for loops would output the below number pattern?

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

Correct answer

  1. for i in range(1, 6):
  2. print(str(i) * 5)
    

Explanation

This for loop iterates over the range from 1 to 5 (exclusive) and prints the string representation of the loop variable i multiplied by 5. This results in the desired number pattern where each row consists of the same number repeated 5 times.

  1. for i in range(1, 5):
  2. print(str(i) * 5)
    

Explanation

This for loop iterates over the range from 1 to 5 (exclusive) and prints the string representation of the loop variable i multiplied by 5. However, the range should go up to 6 to include the number 5 in the pattern, so this loop will not output the correct number pattern.

  1. for i in range(0, 5):
  2. print(str(i) * 5)
    

Explanation

This for loop iterates over the range from 0 to 4 (exclusive) and prints the string representation of the loop variable i multiplied by 5. However, this will not produce the desired number pattern as it starts from 0 instead of 1.

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

Explanation

This for loop iterates over the range from 1 to 6 (exclusive) and prints the loop variable i repeated 5 times separated by spaces. This will not produce the desired number pattern as it prints the number i five times in a row instead of repeating the same number.

Overall explanation

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

Try it yourself:

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

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

  4. 11111

  5. 22222

  6. 33333

  7. 44444

  8. 55555

  9. """

  10. print(‘———-‘)

  11. for i in range(0, 5):

  12. print(str(i) * 5)
    
  13. """

  14. 00000

  15. 11111

  16. 22222

  17. 33333

  18. 44444

  19. """

  20. print(‘———-‘)

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

  22. print(i, i, i, i, i)
    
  23. """

  24. 1 1 1 1 1

  25. 2 2 2 2 2

  26. 3 3 3 3 3

  27. 4 4 4 4 4

  28. 5 5 5 5 5

  29. """

  30. print(‘———-‘)

  31. for i in range(1, 5):

  32. print(str(i) * 5)
    
  33. """

  34. 11111

  35. 22222

  36. 33333

  37. 44444

  38. """

Explanation:

You need range(1, 6)

because the start value 1 is inclusive and the end value 6 is exclusive.

To get the same numbers next to each other

(without a space between them) you need to make a string

and then use the multiply operator string concatenation

The standard separator of the print() function is one space.

print(i, i, i, i, i) gives you one space between each number.

It would work with print(i, i, i, i, i, sep='')

but that answer is not offered here.

(There are similar questions Q218 and Q652.)

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

Domain

05 – Control Flow

Question 42Skipped

Q155 – I/O

Assuming that the open() invocation has gone successfully, the following snippet will:

  1. for x in open(‘file’, ‘rt’):
  2. print(x)
    

read the file character by character.

Explanation

The code snippet will not read the file character by character. Since the ‘for x in open(‘file’, ‘rt’)’ loop iterates over the file line by line, each iteration will read and print a single line from the file, rather than reading the file character by character.

cause an exception.

Explanation

There is no reason for the code snippet to cause an exception, assuming that the file ‘file’ exists and can be successfully opened in read text mode (‘rt’). As long as the file can be opened, the loop will iterate over its contents line by line.

Correct answer

read the file line by line.

Explanation

The ‘for x in open(‘file’, ‘rt’)’ statement will read the file line by line, as the ‘rt’ mode specifies that the file should be opened in text mode for reading. This means that each iteration of the loop will read a single line from the file and assign it to the variable ‘x’.

read the whole file at once.

Explanation

The code snippet will not read the whole file at once. Since the ‘for x in open(‘file’, ‘rt’)’ loop iterates over the file line by line, each iteration will read and print a single line from the file, rather than reading the entire file content at once.

Overall explanation

Topic: open()

Try it yourself:

  1. First execute the following to create a file with already existing lines

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

  3. for i in range(1, 6):
    
  4.     f.write(str(i) + '. Line\n')
    
  5. for x in open(‘file’, ‘rt’):

  6. print(x)
    

Explanation:

The for loop will iterate through the file line by line.
The mode 'rt' stands for read & text.

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

Domain

07 – I/O

Question 43Skipped

Q134 – Error Handling

What is the expected output of the following code?

  1. num = ‘7’ * ‘7’
  2. print(num)

77

Explanation

This choice is incorrect because the code will not output 77. Multiplying two strings in Python is not valid, so the code will raise a TypeError instead of performing numerical multiplication.

7777777

Explanation

This choice is incorrect because the code will not output 7777777. Multiplying two strings in Python is not valid, so the code will raise a TypeError instead of performing numerical multiplication.

49

Explanation

This choice is incorrect because the code will not output 49. Multiplying two strings in Python is not valid, so the code will raise a TypeError instead of performing numerical multiplication.

Correct answer

The code is erroneous.

Explanation

The code is erroneous because you cannot multiply two strings together in Python. The multiplication operator (*) is not defined for string multiplication, so the code will raise a TypeError.

Overall explanation

Topic: TypeError multiplication operator

Try it yourself:

  1. num = ‘7’ * ‘7’ # TypeError: …

  2. print(‘7’ * 4) # 7777

Explanation:

As the error message above states,

you can only multiply a string by an integer.

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

Domain

08 – Error Handling

Question 44Skipped

Q128 – Modules

Knowing that a function named randint()

resides in the module named random

choose the proper way to import it:

from randint import random

Explanation

The syntax "from randint import random" is incorrect because it tries to import the function random from a module named randint, which is not the case. In this scenario, the function randint() is in the random module, so the correct syntax should specify "from random import randint".

Correct answer

from random import randint

Explanation

The correct way to import a specific function from a module in Python is using the "from module_name import function_name" syntax. In this case, the function randint() resides in the random module, so the correct syntax is "from random import randint".

import randint from random

Explanation

The syntax "import randint from random" is incorrect because the "from" keyword should come before the module name, not after the function name. The correct order is "from module_name import function_name", so "import randint from random" is not a valid way to import the randint() function from the random module.

import randint

Explanation

When importing a specific function from a module, you cannot simply use the "import function_name" syntax. You need to specify the module name as well. Therefore, "import randint" is not the correct way to import the randint() function from the random module.

Overall explanation

Topic: from import random randint

Try it yourself:

  1. from random import randint

  2. print(randint(1, 6)) # e.g. 3

  3. import randint # ModuleNotFoundError: …

  4. from randint import random # ModuleNotFoundError: …

  5. import randint from random # SyntaxError: …

Explanation:

The module name is random

You have to write the module first.

And you import from a module.

from the module random you want to import the method randint

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

Domain

09 – Modules

Question 45Skipped

Q124 – Basics

Which of the following variable names is illegal?

In

Explanation

Variable names in Python are case-sensitive, so "In" is a valid variable name. However, it is not recommended to use uppercase letters at the beginning of variable names to avoid confusion with class names.

in_

Explanation

The variable name "in_" is a legal variable name in Python. It is a common practice to append an underscore to variable names to distinguish them from reserved keywords or built-in functions.

IN

Explanation

Similarly, "IN" is a valid variable name in Python due to case sensitivity. However, using all uppercase letters for variable names is not a common convention and may make the code less readable.

Correct answer

in

Explanation

The variable name "in" is a reserved keyword in Python and cannot be used as an identifier for a variable. Using reserved keywords as variable names is illegal in Python.

Overall explanation

Topic: naming variables

Try it yourself:

  1. in = ‘Hello’ # SyntaxError: invalid syntax

  2. Does not work because "in" is a python keyword

  3. for the membership operator:

  4. print(7 in [1, 4, 7, 11]) # True

  5. Those work because python is case sensitiv

  6. In = ‘Hello’

  7. IN = ‘Hello’

  8. This one works because the underscore

  9. is a valid character for naming variables:

  10. in_ = ‘Hello’

Explanation:

You can not name a variable like a Python keyword.

Here is a list of all the Python keywords:

  1. import keyword
  2. print(keyword.kwlist)
  3. """
  4. [‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’,
  5. ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’,
  6. ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’,
  7. ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’,
  8. ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’]
  9. """

Here are the other rules for naming variables in Python:

A variable name must start with a letter or the underscore character.

A variable name can not start with a number.

A variable name can only contain alpha-numeric characters

and underscores (a-z0-9, and _)

Variable names are case-sensitive

(ageAge and AGE are three different variables)

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

Domain

01 – Basics

Question 46Skipped

Q154 – Modules

What is the expected output of the following code?

  1. from datetime import datetime

  2. datetime = datetime(2019, 11, 27, 11, 27, 22)

  3. print(datetime.strftime(‘%y/%B/%d %H:%M:%S’))

2019/11/27 11:27:22

Explanation

This choice is incorrect because the format string ‘%y/%B/%d %H:%M:%S’ does not match the output format ‘2019/11/27 11:27:22’. The year is expected to be in two digits, and the month should be the full month name.

19/11/27 11:27:22

Explanation

This choice is incorrect because the format string ‘%y/%B/%d %H:%M:%S’ does not match the output format ’19/11/27 11:27:22′. The year is expected to be in two digits, and the month should be the full month name.

Correct answer

19/November/27 11:27:22

Explanation

The code creates a datetime object with the specified date and time values. The strftime method is then used to format the datetime object according to the specified format string ‘%y/%B/%d %H:%M:%S’. This format string will output the year in two digits, the full month name, the day, and the time in hours, minutes, and seconds.

2019/Nov/27 11:27:22

Explanation

This choice is incorrect because the format string ‘%y/%B/%d %H:%M:%S’ does not match the output format ‘2019/Nov/27 11:27:22’. The year is expected to be in two digits, the month should be the full month name, and the day should be in two digits.

Overall explanation

Topics: import datetime strftime()

Try it yourself:

  1. from datetime import datetime
  2. datetime = datetime(2019, 11, 27, 11, 27, 22)
  3. print(datetime.strftime(‘%y/%B/%d %H:%M:%S’))
  4. 19/November/27 11:27:22

  5. print(datetime.strftime(‘%Y/%b/%d %H:%M:%S’)) # 2019/Nov/27 11:27:22
  6. print(datetime.strftime(‘%y/%m/%d %H:%M:%S’)) # 19/11/27 11:27:22
  7. print(datetime.strftime(‘%Y/%m/%d %H:%M:%S’)) # 2019/11/27 11:27:22

Explanation:

You "just" have to learn these:

https://strftime.org

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

Domain

09 – Modules

Question 47Skipped

Q123 – Functions

What is the expected output of the following code?

  1. def func(num):

  2. res = '*'
    
  3. for _ in range(num):
    
  4.     res += res
    
  5. return res
    
  6. for x in func(2):

  7. print(x, end='')
    

Correct answer

****

Explanation

The code defines a function ‘func’ that takes a number as input and initializes a string ‘res’ with a single ‘‘. It then iterates ‘num’ times and doubles the length of ‘res’ by concatenating it with itself. In this case, ‘num’ is 2, so the final value of ‘res’ will be ‘**’, which results in the output of ‘***’ when printed.

The code is erroneous.

Explanation

The code is not erroneous as it defines a function and successfully prints the output. The error lies in understanding the logic of the code and predicting the final output based on the given input.

**

Explanation

This choice represents two ‘‘ characters. However, the code doubles the length of the ‘res’ string in each iteration of the loop. Therefore, the output will not be just two ‘‘ characters.

*

Explanation

This choice represents a single ‘‘ character. However, the code doubles the length of the ‘res’ string in each iteration of the loop. Therefore, the output will not be just a single ‘‘ character.

Overall explanation

Topics: def return for

Try it yourself:

  1. def func(num):

  2. res = '*'
    
  3. for _ in range(num):
    
  4.     res += res
    
  5. return res
    
  6. for x in func(2):

  7. print(x, end='')     # ****
    
  8. # print(x, end='-')  # *-*-*-*-
    
  9. print()

  10. print(func(2)) # ****

Explanation:

The for loop inside of the function will iterate twice.

Before the loop res has one star.

In the first iteration a second star is added.

res then has two stars.

In the second iteration two more stars are added to those two star

and res will end up with four stars.

The for loop outside of the function will just iterate through the string

and print every single star.

You could get that easier by just printing the whole return value.

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

Domain

06 – Functions

Question 48Skipped

Q142 – Control Flow

What is the expected output of the following code?

  1. x = True

  2. y = False

  3. z = False

  4. if not x or y:

  5. print(1)
    
  6. elif not x or not y and z:

  7. print(2)
    
  8. elif not x or y or not y and x:

  9. print(3)
    
  10. else:

  11. print(4)
    

4

Correct answer

3

1

2

Overall explanation

Topics: if elif else not and or operator precedence

Try it yourself:

  1. x = True

  2. y = False

  3. z = False

  4. if not x or y:

  5. if (not True) or False:

  6. if False or False:

  7. if False:

  8. print(1)
    
  9. elif not x or not y and z:

  10. elif (not True) or (not False) and False:

  11. elif False or True and False:

  12. elif False or (True and False):

  13. elif False or False:

  14. elif False:

  15. print(2)
    
  16. elif not x or y or not y and x:

  17. elif (not True) or False or (not False) and True:

  18. elif False or False or True and True:

  19. elif False or False or (True and True):

  20. elif False or False or True:

  21. elif (False or False) or True:

  22. elif False or True:

  23. elif True:

  24. print(3)  # 3
    
  25. else:

  26. print(4)
    

Explanation:

There are three operators at work here.

Of them the not operator has the highest precedence,

followed by the and operator.

The or operator has the lowest precedence.

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

Domain

05 – Control Flow

Question 49Skipped

Q131 – Data Types

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

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

4

Explanation

This choice is incorrect because the code does not convert the user input to integers before performing the addition operation. Therefore, the output will be a string concatenation of the inputs, resulting in ’24’ instead of the individual numbers entered by the user.

6

Explanation

This choice is incorrect because the code does not convert the user input to integers before performing the addition operation. Therefore, the output will be a string concatenation of the inputs, resulting in ’24’ instead of the sum of the numbers.

Correct answer

24

Explanation

The expected output of the code is ’24’ because the input() function in Python reads user input as strings. When the user enters ‘2’ and ‘4’, the variables x and y will store these inputs as strings. When the print statement concatenates x and y using the ‘+’ operator, it will concatenate the strings ‘2’ and ‘4’ to form ’24’.

2

Explanation

This choice is incorrect because the code does not convert the user input to integers before performing the addition operation. Therefore, the output will be a string concatenation of the inputs, resulting in ’24’ instead of the sum of the numbers.

Overall explanation

Topics: input() plus operator string concatenation

Try it yourself:

  1. x = input()

  2. y = input()

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

Explanation:

As always the input() function return a string.

Therefore string concatenation takes place and the result is the string 24

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

Domain

02 – Data Types

Question 50Skipped

Q140 – Data Aggregates

What is the expected output of the following code?

  1. nums = [3, 4, 5, 20, 5, 25, 1, 3]
  2. nums.pop(1)
  3. print(nums)

[3, 1, 25, 5, 20, 5, 4]

Explanation

This choice is incorrect because the code removes the element at index 1 (which is 4) from the list ‘nums’ using the pop() method. The resulting list is [3, 5, 20, 5, 25, 1, 3], not [3, 1, 25, 5, 20, 5, 4].

[3, 4, 5, 20, 5, 25, 1, 3]

Explanation

This choice is incorrect because the code removes the element at index 1 (which is 4) from the list ‘nums’ using the pop() method. The resulting list is [3, 5, 20, 5, 25, 1, 3], not the original list [3, 4, 5, 20, 5, 25, 1, 3].

[1, 3, 3, 4, 5, 5, 20, 25]

Explanation

This choice is incorrect because the code removes the element at index 1 (which is 4) from the list ‘nums’ using the pop() method. The resulting list is [3, 5, 20, 5, 25, 1, 3], not [1, 3, 3, 4, 5, 5, 20, 25].

Correct answer

[3, 5, 20, 5, 25, 1, 3]

Explanation

The code removes the element at index 1 from the list ‘nums’ using the pop() method. After removing the element at index 1 (which is 4), the resulting list is [3, 5, 20, 5, 25, 1, 3].

[1, 3, 4, 5, 20, 5, 25]

Explanation

This choice is incorrect because the code removes the element at index 1 (which is 4) from the list ‘nums’ using the pop() method. The resulting list is [3, 5, 20, 5, 25, 1, 3], not [1, 3, 4, 5, 20, 5, 25].

Overall explanation

Topics: pop() list

Try it yourself:

  1. nums = [3, 4, 5, 20, 5, 25, 1, 3]
  2. nums.pop(1)
  3. print(nums) # [3, 5, 20, 5, 25, 1, 3]

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.

Here the index 1 gets removed: the number 4

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

Domain

04 – Data Aggregates

Question 51Skipped

Q141 – Data Aggregates

What is the expected output of the following code?

  1. x = [0, 1, 2]
  2. x.insert(0, 1)
  3. del x[1]
  4. print(sum(x))

2

Explanation

This choice is incorrect because the sum of the elements in the list x after the insert and delete operations is not 2. The correct sum is 4, as the elements are [1, 1, 2].

Correct answer

4

Explanation

The code first inserts the value 1 at index 0 of the list x, resulting in x = [1, 0, 1, 2]. Then, it deletes the element at index 1, which is the value 0, leaving x = [1, 1, 2]. Finally, the sum of all elements in the list x is calculated and printed, which results in 4.

3

Explanation

This choice is incorrect because the sum of the elements in the list x after the insert and delete operations is not 3. The correct sum is 4, as the elements are [1, 1, 2].

5

Explanation

This choice is incorrect because the sum of the elements in the list x after the insert and delete operations is not 5. The correct sum is 4, as the elements are [1, 1, 2].

Overall explanation

Topics: insert() del sum() list

Try it yourself:

  1. x = [0, 1, 2]
  2. x.insert(0, 1)
  3. print(x) # [1, 0, 1, 2]
  4. del x[1]
  5. print(x) # [1, 1, 2]
  6. print(sum(x)) # 4

Explanation:

list.insert(i, x)

insert() inserts an item at a given position.

The first argument is the index of the element before which to insert.

insert(0, 1) inserts 1 before index 0 (at the front of the list).

The del keyword deletes the given object.

In this case x[1]

The sum() function adds the items of a list (or a different iterable)

and returns the sum.

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

Domain

04 – Data Aggregates

Question 52Skipped

Q113 – Operators

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

=/=

Explanation

The operator "=/=" is not a valid operator in Python for checking non-equality between two values. Python does not recognize this syntax for inequality comparison, so it is not a correct choice for the given question.

Correct answer

!=

Explanation

The operator "!=" in Python is used to check whether two values are not equal to each other. It is the standard way to express inequality in Python and is the correct choice for checking non-equality between two values.

<>

Explanation

The operator "<>" used to be an alternative way to express inequality in Python 2.x, but it has been removed in Python 3.x. Therefore, it is not a valid operator for checking non-equality in modern Python code.

not ==

Explanation

The expression "not ==" is not a valid operator for checking non-equality in Python. The "not" keyword is used for negation, but it cannot be directly combined with the equality operator "==". Therefore, it is not the correct choice for checking non-equality between two values in Python.

Overall explanation

Topic: not equal to operator

Try it yourself:

  1. print(1 != 2) # True
  2. print(1 <> 2) # SyntaxError: …

  3. print(1 =/= 2) # SyntaxError: …

  4. print(1 not == 2) # SyntaxError: …

Explanation:

Other languages have <> or =/= as not equal to operators

In Python the not equal to operator is !=

not == does not work like this,

because you can not have two operators next to each other.

It would work like that:

print(not(1 == 2)) # True

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

Domain

03 – Operators

Question 53Skipped

Q144 – I/O

Which of the following commands can be used to read n characters from a file?

Correct answer

file.read(n)

Explanation

The command file.read(n) is the correct choice as it allows you to read n characters from a file. This method reads and returns the specified number of characters from the file, making it suitable for reading a specific number of characters at a time.

file.readline(n)

Explanation

The command file.readline(n) is incorrect as it is used to read a single line from a file, not a specific number of characters. This method reads a line from the file up to the specified number of characters, but it does not read a specific number of characters from the file.

n = file.readline()

Explanation

The command n = file.readline() is incorrect as it reads a single line from the file and stores it in the variable n. This command does not allow you to specify the number of characters to read from the file, making it unsuitable for reading a specific number of characters.

n = file.read()

Explanation

The command n = file.read() is incorrect as it does not specify the number of characters to read from the file. This command will read the entire contents of the file and store it in the variable n, which may not be what is required when trying to read a specific number of characters.

Overall explanation

Topics: read() readline()

Try it yourself:

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

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

  3. f.write('Peter\n')
    
  4. f.write('Paul\n')
    
  5. f.write('Mary\n')
    
  6. file = open(‘index.txt’, ‘r’)

  7. print(file.read(10))

  8. Peter

  9. Paul

Explanation:

file.read([size])

The read() method has one optional parameter.

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

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

file.readline([size])

The readline() method has also one optional parameter

to specify the number of characters to be read.

But it would only read that number of characters from

the first line.

If you want to read more characters,

only the read() method will work.

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

Domain

07 – I/O

Question 54Skipped

Q132 – Data Types

What is the expected output of the following code?

  1. z = y = x = 1
  2. print(x, y, z, sep=’*’)

Correct answer

1*1*1

Explanation

The code assigns the value of 1 to variables x, y, and z in a single line. When printing these variables with ‘‘ as the separator, the expected output is ‘11*1′.

x*y*z

Explanation

This choice does not match the expected output of the code. The variables x, y, and z are printed with ‘*’ as the separator, not multiplied together.

The code is erroneous.

Explanation

This choice is incorrect as the code is not erroneous. It correctly assigns the value of 1 to variables x, y, and z, and prints them with ‘*’ as the separator.

x y z

Explanation

This choice does not match the expected output of the code. The variables x, y, and z are printed with ‘*’ as the separator, not their variable names.

111*

Explanation

This choice does not match the expected output of the code. The variables x, y, and z are printed with ‘*’ as the separator, not concatenated together.

1 1 1

Explanation

This choice does not match the expected output of the code. The variables x, y, and z are printed with ‘*’ as the separator, not spaces.

Overall explanation

Topic: multiple assignment print() with sep parameter

Try it yourself:

  1. z = y = x = 1
  2. print(x, y, z, sep=’‘) # 11*1
  3. print(x, y, z, sep=’ ‘) # 1 1 1
  4. print(x, y, z) # 1 1 1

Explanation:

The print() function has a sep parameter which stands for separator.

The default value of the sep parameter is a space character.

You can change it to anything you want.

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

Domain

02 – Data Types

Question 55Skipped

Q107 – Functions

The function body is missing.

What snippet would you insert in the line indicated below:

  1. def func(number):

  2. # insert your code here
    
  3. print(func(7))

print(number)

Explanation

This choice would print the value of the ‘number’ parameter to the console when the function is called. However, the question asks for the snippet to be inserted in the function body, not outside of it. Therefore, this choice is incorrect in this context.

return 'number'

Explanation

This choice would return the string ‘number’ when the function is called, which is not the value of the ‘number’ parameter passed to the function. The function is expected to return the actual value of the ‘number’ parameter, not a string representation of it. Therefore, this choice is incorrect in this context.

Correct answer

return number

Explanation

The correct choice is to use the ‘return’ keyword followed by the variable ‘number’ to return the value of the ‘number’ parameter passed to the function. This will ensure that the function returns the value of the ‘number’ parameter when called.

print('number')

Explanation

This choice would print the string ‘number’ to the console when the function is called, which is not the value of the ‘number’ parameter passed to the function. Therefore, this choice is incorrect in this context.

Overall explanation

Topics: def return

Try it yourself:

  1. def func(number):
  2. return number      # works and only 7 would be printed
    
  3. # print(number)    # works, but 7 & None would be printed
    
  4. # print('number')  # works, but number & None would be printed
    
  5. # return 'number'  # works, but number would be printed
    
  6. print(func(7))

Explanation:

The parameter name is number therefore it can not be in quotes.

If you only print something in the function,

the function will return None and that is not wanted here,

because the return values gets already printed outside of the function.

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

Domain

06 – Functions

Question 56Skipped

Q148 – Operators

You develop a Python application for your company.

You have the following code.

  1. def main(a, b, c, d):
  2. value = a + b * c - d
    
  3. return value
    

Which of the following expressions is equivalent to the expression in the function?

(a + b) * (c - d)

Explanation

This expression is not equivalent to the original expression in the function. It first adds a and b, then multiplies the sum by c, and finally subtracts d, which changes the order of operations and the result of the expression.

None of the above.

Explanation

This choice is incorrect because choice A is equivalent to the original expression in the function, making it the correct choice among the options provided.

a + ((b * c) - d)

Explanation

This expression is not equivalent to the original expression in the function. It first multiplies b and c, then subtracts d, and finally adds a to the result, which changes the order of operations and the result of the expression.

Correct answer

(a + (b * c)) - d

Explanation

This expression is equivalent to the original expression in the function because it first multiplies b and c, then adds a to the result, and finally subtracts d from the sum, following the same order of operations as the original code.

Overall explanation

Topics: addition operator multiplication operator

subtraction operator operator precedence

Try it yourself:

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

  2. value = a + b * c - d        # 3
    
  3. # value = (a + (b * c)) - d  # 3
    
  4. # value = (a + b) * (c - d)  # -3
    
  5. # value = a + ((b * c) - d)  # 3
    
  6. return value
    
  7. print(main(1, 2, 3, 4)) # 3

Explanation:

This question is about operator precedence

The multiplication operator has the highest precedence

and is therefore executed first.

That leaves the addition operator and the subtraction operator

They both are from the same group and therefore have the same precedence.

That group has a left-to-right associativity.

The addition operator is on the left and is therefore executed next.

And the last one to be executed is the subtraction operator

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

Domain

03 – Operators

Question 57Skipped

Q147 – Error Handling

The Exception class contains a property named args and it is a:

Correct answer

tuple

Explanation

The args property in the Exception class is a tuple. It stores the arguments passed to the exception constructor and can be accessed using the args attribute. This allows for detailed information about the exception to be retrieved and displayed.

list

Explanation

The args property in the Exception class is not a list. It is actually a tuple that stores the arguments passed to the exception constructor. Using a list instead of a tuple for args would not be consistent with the standard behavior of the Exception class.

string

Explanation

The args property in the Exception class is not a string. It is actually a tuple that holds the arguments passed to the exception constructor. Storing the arguments as a string would limit the flexibility and functionality of the args property.

dictionary

Explanation

The args property in the Exception class is not a dictionary. It is a tuple that contains the arguments passed to the exception constructor. Using a dictionary for args would not be in line with the standard implementation of the Exception class.

Overall explanation

Topics: Exception args tuple

Try it yourself:

  1. try:
  2. raise Exception('Hello', 'World')
    
  3. except Exception as e:
  4. print(e.args)        # ('Hello', 'World')
    
  5. print(type(e.args))  # <class 'tuple'>
    

Explanation:

Makes sense.

Integers as indexes is enough, therefore no dictionary

You might need more than one elements, therefore no string

You do not want it to be writeable later on, therefore no list

That leaves the tuple

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

Domain

08 – Error Handling