Python
Control Structures
28 flashcards · answers and spaced-repetition review in the KnowCard app
Why does (n := len(lst)) usually need parentheses inside a bigger expression?
What does this print?
```
for n in [2, 4, 6]:
if n == 5:
break
else:
print("done")
```
A for/while loop's else branch runs in which case: when the loop hits break, or when it does NOT?
break vs continue inside a loop: what does each do?
What is printed?
```
n = 5
while n > 0:
n -= 1
if n == 2:
continue
print(n, end=" ")
```
What is the value of var?
```
x = 7
var = 20 if x == 1 else 30
```
In a if cond else b, which sub-expressions actually get evaluated?
Rewrite this to read input once per loop using the walrus operator:
```
while True:
attempt = int(input("Guess: "))
if attempt == secret:
break
```
What is the difference between two separate if statements and an if/elif chain?
When and why would you write pass in a block?
Does a while loop run while its condition is True, or until it becomes True?
What does this print?
```
for i in range(3):
for j in range(3):
if j == 1:
break
print(i, j)
```
How do you make a for loop count DOWN from 10 to 2 by twos?
What does this print?
```
for i in range(2, 6):
print(i, end=" ")
```
Which of these are 'falsy' in an if condition: 0, "", [], {}, None, "0"?
Why can if my_list: be a bug when you meant 'is the list None?'
In Python, what marks a statement's body (like an if block), and how do you know where the block ends — versus C or Java?
Is if x: print("a"); print("b") valid, and does print("b") run only when x is true?
Your code looks perfectly aligned in the editor, yet Python complains about indentation or runs the wrong lines. What invisible cause should you suspect?
What does range(1, 10, 2) produce, and is 10 included?
What does this print?
```
print(0 or "hi")
print("a" and "b")
print([] or "fallback")
```
Pitfall of name = value or default when value can be 0 or ""?
What does the walrus operator := do, and where is it used?
What error does this raise, and why?
i = 10
if i == 10:
print("hi")
What does this print?
for c in "Hi!":
print(c)
A C/Java programmer expects for to mean init/condition/increment. What is Python's for actually equivalent to?
How do you write an intentional infinite loop in Python, and how do you ever leave it?
What happens when you call range(2.0) or range(0, 10, 0.5)?
Start learning today
Free to start — download the app or use it in your browser.
