What is the output of the following Python program?
print(type(print("hi")))
The inner print runs first and prints "hi"; it returns None, whose type is NoneType.
Tricky Python Output Questions · Exercise 2 of 4
Fifteen tricky predict-the-output questions on core Python: references, numbers, strings and slicing, truthiness, dictionaries and unpacking. Every program was run on Python 3, so the answers are the real output.
What is the output of the following Python program?
print(type(print("hi")))
The inner print runs first and prints "hi"; it returns None, whose type is NoneType.
What is the output of the following Python program?
x = [1, 2, 3]
y = x
x = x + [4]
x += [5]
print(y, x)
x + [4] builds a new list, so x and y part ways. The later += mutates only the new list.
What is the output of the following Python program?
print(repr("abc" * 0), [0] * 3, "-".join("abc"), "ab" * -1 == "")
Repeating zero (or a negative number of) times gives an empty sequence. join puts the separator between the characters of the string.
What is the output of the following Python program?
print(10 / 4, 10 // 4, -10 // 4, 10 % -4)
-10 // 4 floors -2.5 to -3. 10 % -4 takes the divisor's sign: 10 = -3 × -4 + (-2).
What is the output of the following Python program?
print(1 < 2 > 1.5 == 1.5, 5 > 3 > 1, 2 < 3 < 1, (2 < 3) < 1)
Each chain is joined with and. In the last one the brackets make (2 < 3) a bool, True, and True < 1 is False.
What is the output of the following Python program?
print([] == False, bool([]) == False, not [], [] is not None)
[] is falsy, but a list is never equal to a bool.
What is the output of the following Python program?
print("5" + "5", 5 + 5, "5" * 2, int("5") * 2, "5" < "10")
+ and * on strings concatenate and repeat. Comparison is character by character, and "5" > "1".
What is the output of the following Python program?
a = [1, 2, 3]
print(a[-1:], a[5:], a[::-2], a[1:1], a[-5:2])
Slices never raise IndexError; out-of-range bounds are clipped. a[1:1] is empty because start equals stop.
What is the output of the following Python program?
s = "Python"
print(s[1:4:2], s[-3:], s[:-3], s[::-1][::2])
s[1:4:2] takes indexes 1 and 3. s[::-1] is "nohtyP"; taking every second character gives "nhy".
What is the output of the following Python program?
d = {}
d[1] = "a"
d[1.0] = "b"
d[True] = "c"
print(d, len(d))
1, 1.0 and True are equal with equal hashes – one key. The first key object (1) stays; the value is overwritten each time.
Timed online tests with instant scores and explanations.