The chapter in short
Control structures decide the order in which a program's statements run. Selection makes a program choose between paths; repetition makes it repeat steps.
The chapter covers if, if-else and if-elif-else statements, nested conditions, for and while loops, range(), and the break and continue statements.
Control structureSelectionConditionLoopInfinite loopNested loop
Key points
- if runs a block only when its condition is True; else gives the alternative.
- elif tests further conditions in order; only the first true branch runs.
- Blocks are marked by indentation, and if, elif, else, for and while lines end with a colon.
- A for loop repeats over a sequence, such as range(1, 11) for 1 to 10.
- A while loop repeats as long as its condition stays True; make sure it eventually becomes False.
- break leaves a loop at once; continue skips to the next pass.
Definitions
- 1
Control structure
A statement that controls the order in which other statements run.
- 2
Selection
Choosing between different paths in a program using a condition.
- 3
Condition
An expression that is either True or False.
- 4
Loop
A structure that repeats a block of code.
- 5
Infinite loop
A loop whose condition never becomes False, so it never ends.
- 6
Nested loop
A loop inside another loop.
Formulas
Selection
if x > 0: print("positive") elif x == 0: print("zero") else: print("negative")
for loop
for i in range(1, 6): print(i)
while loop
i = 1 while i <= 5: print(i) i += 1