This Python test normally takes around 15 min to complete. You can also take the test on your mobile browser. Please do not use a Python interpreter to answer the questions of the test. Use your mind and your knowledge.
What would the value of x be if we executed the following code?
a = 1 b = 2 x = a + b x = 10
10
The value of x would become 3 in Line 3, but then it would be overwritten by 10 in the last line.
Check ALL true statements.
Lists can contain any type of object.
Dictionaries represent pairs of keys and values.
List and tuple indexing start from zero.
The only wrong statement is the first one. That should not be checked. Tuples can contain any type of object. They are not homogenous.
What does the following code output?
the intensity = 125.11 print(the intensity)
SyntaxError: invalid syntax
There cannot be spaces in variables names. A solution would be to rename the variable to the_intensity.
What would the value of x be if we executed the following code?
x = str(int(float('2')))
'2'
There's a chain of type conversions in that code. First, there is float('2') = 2.0, then int(2.0) = 2, and then str(2) = '2'which is also the final value.
What does the code below output?
if not 1 in [10, 20] and 1 < 2:
print(1)
else:
print(2)1
The part if not 1 in [10, 20] evaluates to True because 1 is not in the list [10, 20]. Part 1 < 2 is also True. Therefore, print(1) will be executed.
What does list(range(2, 5)) output?
[2, 3, 4]
The code constructs a list starting from 2, and ending at 4. Item 5 is not included because ranges are upper-bound exclusive.
Consider this list:
animals = ['bear', 'rat', 'cow', 'shrimp', 'shark']
Which code would extract the slice ['cow', 'shrimp', 'shark'] out of the animals list?
animals[2:]
The code animals[2:] extracts all items starting from the item with index 2. The item with index 2 is 'cow'.
Consider this line of code:
numbers = ('a', 'b', 1, 2)
Check all that would output 2.
numbers[3]
numbers[-1]
numbers[3] extracts 2 since indexing starts from zero. So, 'a' has an index of 0. 'b' has an index of 1. 1 has an index of 2, and 2 has an index of 3.
numbers[-1] also extracts 2 since the last item has also an index of -1. The item before the last item has an index of -2, and so on.
What does the code below return?
air_temperature = [35, 28, 10] land_temperature = [18, 20, 15] air_temperature[1] + land_temperature[0]
46
air_temperature[1] extracts the second item (i.e. 28) of air_temperature and land_temperature[0] extracts the first item (i.e. 18) of land_temperature. The sum of 28 and 18 is 46.
What's the output of the code below?
mylist = [['abc'], ['def', 'ghi']] mylist[-1][-1][-1]
'i'
mylist has two items, item ['abc'] and item ['def', 'ghi']. The part mylist[-1] returns ['def', 'ghi']. Then, mylist[-1][-1] returns 'ghi', and lastly, mylist[-1][-1][-1] returns 'i'.
What does the following code output?
d = {
"food": {
"rice":
{
"weight": 30.1,
"taste": "good",
"forms": ["boiled"]
},
"banana":
{
"weight": 19,
"taste": "excellent",
}
}
}
print(d['food']['banana']['taste'])excellent
Dictionary d is a dictionary made out of other nested dictionaries. The last line tries to access the values of those nested dictionaries.
Which of the following is a list of tuples of dictionaries?
[({'a':1, 'b':2}, {'c':3, 'd':4}), ({'e':5}, {'d':6})]
The second option is the correct answer because that is a list. That list has two tuples as items. Each tuple has dictionaries as items. Therefore, we can say that it is a list of tuples of dictionaries.
Check all the syntactically correct.
(1, 2)
(('a', 1), ('b', 1))
{'a': 1, 'b': 2}
The syntax of ('a': 1, 'b': 2) is not right. It starts with parenthesis as a tuple but then continues with colons that are used in dictionaries. The correct syntax would be {'a': 1, 'b': 2}
What does the code below output?
def eur_to_usd(euros, rate=0.8):
return euros * rate
print(eur_to_usd(10))8.0
8.0 is returned because 10 * 0.8 is actually the float 8.0. Multiplying an integer with a float gives a float.
What would the following code output?
x = 10.0
if type(x) == float:
print(int(x))
else:
print(x)10
Since 10.0 is a float, type(x) == float will be evaluated to True. Therefore, print(int(x)) will be executed which will convert 10.0 to 10 and print it out.
What does the code output this time?
x = 10
y = 11
if x > 10 and y > 10:
print("Success!")
else:
print("Failed!")Failed!
The condition x > 10 and y > 10 evaluates to False because not both sides of and evaluate to True.
Check ALL that apply to the following code.
items = ['adapter', 'cable', 'keyboard']
choice = input("Item")
if choice in items:
print("Item is available!")The execution will be halted to wait for user input.
The code prompts the user to enter some input. The input is stored in the choice variable. Then, the program checks if the value of choice is in the items list. If it is, it prints out the string Item is available!
What would be the output of the following code if the user entered 10 as input?
weight = input("How many kg?")
price = weight * 2.5
print(price)TypeError: can't multiply sequence by non-int of type 'float'
Even if the user enters a number like 10, the input function converts that number into a string. For the code to behave correctly, the first line should be changed to weight = float(input("How many kg?")) so that the string "10" is converted to float 10.0.
Which code prints out Price is 25.0 when the user enters 10 as input?
weight = float(input("How many kg?"))
price = weight * 2.5
print(f"Price is {price}")The last answer is the correct one because f"Price is {price}" actually constructs the string Price is 25.0 by replacing the part {price} with the value of the variable price. Note that this only happens when there is an f before the string quotes.
What would the following code output?
for letter in 'abc':
print(letter.upper())A
B
C
The code goes to each item of the string abc and prints out each item capitalized and in a separate line.
What does the following code output?
for item in [[1, 2, 3], [4, 5, 6]]:
print(item[0])1
4
The for-loop iterates over the items of the big list, so, through [1, 2, 3] and [4, 5, 6]. In each iteration, it prints out the item with index 0 of each list. Such items are 1 and 4.
Select the correct output for the following code.
for i in [99, 102, 89]:
if i >= 100:
print(i - 1)101
The code goes through the list of numbers and checks if a number is greater or equal to 100. If it is, it subtracts 1 from that number and prints out the output. Only 102 is greater or equal to 100, so we get the output of 102 - 1 printed out.
What would the value of x be after running the code below?
x = [len(item) for item in ['abc', 'def', 'ghi']]
[3, 3, 3]
We're looking at a list comprehension. List comprehensions are expressions that construct lists. The constructed list here will contain three items. Each item is a number representing the length of each of the three strings. All of those strings have a length of 3, so we get [3, 3, 3] as output.
What would be the value of y given the following code?
y = [i * 2 if i > 0 else 0 for i in [1, -2, 10]]
[2, 0, 20]
This is a list comprehension with a nested conditional. It's the exact equivalent of the code below. They both accomplish the same thing.
y = []
for i in [1, -2, 10]:
if i > 0:
y.append(i * 2)
else:
y.append(0)What would the output of the following code be?
def foo(*args):
return len(args)
print(foo(1, 2, 4))3
*args is a special parameter. It means the function can practically take an infinite number of arguments. The arguments will be added to the args tuple. The above function returns the length of that tuple. The length is three since three arguments were passed in the function call.
def foo(x):
return x ** 2
print(foo("Hello"))What is true about the above code?
It will produce an error.
The code will produce an error because the function will try to raise the string Hello to the power of two. Such an operation doesn't make sense.
What does the code output?
def foo(a = 1, b = 'John'):
return a + b
foo()TypeError: unsupported operand type(s) for +: 'int' and 'str'
The function call will trigger the operation 1 + 'John' which doesn't make sense and it gives an error since Python cannot add an integer to a string.
What would be the value of price?
def foo(a = 1, b = 2):
return a + b
price = foo(b = 4)5
a and b are default parameters in the function definition. When the function is called, the value of a will still be its default value 1, while the value of b will be 4, and 4 + 1 gives 5.
Which of the code would successfully create a text file? Check all that apply.
with open('temp.txt', 'w') as file:
file.write('Hello')file = open('temp.txt', 'w')
file.write("Hello")
file.close()The code of the second opens the file in read-only mode and so does the code of the third option. Note that when the opening mode argument is not passed in open(), then 'r' is used by default.
What would be the content of articles.txt file after executing the following script?
with open('articles.txt', 'w') as file:
file.write('wiki_telephones')
with open('articles.txt', 'w') as file:
file.write('wikipedia_telephones')wikipedia_telephones
The first block of code creates the text file and writes wiki_telephones inside the text file, but the second block of code creates a new file with the same filename that overwrites the first file and its content. If we wanted to append wikipedia_telephones after wiki_telephones, we would want to use 'a' instead of 'w' in the second block.