Which keyword is used to define a function?
def
print("6" + "9")
What data type stores key-value pairs?
print(True + False)
1
t = #code here
print(t) # (1)
What should go in #code here such that printing t returns a tuple with one element (1) in it?
(1,)
Which keyword is used to perform more checks after an initial if statement?
elif
How can
x = x + 2
be rewritten to be more concise?
x += 2
How to add something to the end of a list?
The .append() function
How to print the reverse of any string s?
print(s[::-1])
x = ["welcome", "to", "my", "house"]
y = list(map(str.upper, filter(lambda s: len(s) > 2, x)))
print(y)
["WELCOME", "HOUSE"]
Describe what a try-except block does in Python.
How to calculate 2 to the 30th power?
2 ** 30
x = [6, 9, 4, 2]
print(x[:2])
[6, 9]
Describe what a for-else statement does:
for ...:
...
else:
...
The else cause only triggers if the break keyword is not called in the for loop.
print(reversed("hi"))
<reversed object>
Describe what the continue keyword does in Python.
It is used in loops; it brings the control flow back to the beginning of the loop.
Integer division; it divides two values and rounds down to the nearest integer. (Note that this also applies for negative numbers.)
x = [6, 9, 4, 2]
y = x.pop(2)
print(y)
4
x = 20
print(f"{x} is greater than {x-1}: {x > 20}.")
"20 is greater than 19: False."
sentence = ["What", "the", "heck", "is", "this"]
a, *b, c = sentence
print(b)
["the", "heck", "is"]
Describe what the yield keyword does in Python
It is used in generators. Generators are functions, but instead of return, they use yield. Generators "lazily" yield information, only doing so when explicitly told to.
print(5 ^ 3)
6
what is the easiest way to find the number of distinct elements in a list x? (one-liner)
len(set(x))
Which of the following is incorrect?
a. [x for x in range(10)]
b. [x for x in range(10) if x > 6]
c. [x*x if x > 6 for x in range(10)]
c. [x*x if x > 6 else x for x in range(10)]
c
print(len(x))
1