Loops: while, for, range(), Modules & sys.exit()
What This Chapter Covers
These notes cover:
- while loops, and how they differ from if statements
- break and continue statements
- Truthy and falsey values, and the bool() function
- for loops and the range() function (including its two- and three-argument forms)
- Rewriting a for loop as an equivalent while loop
- Importing modules and calling their functions (e.g., random.randint())
- Ending a program early with sys.exit()
Key Vocabulary
| Term | Definition |
|---|---|
| Loop | A block of code that repeats while (or until) a condition is met. |
| Iteration | One single pass through a loop’s clause. |
| Infinite loop | A loop whose condition is always True. It must be exited with break or sys.exit(). |
| break | Immediately exits the innermost while or for loop. |
| continue | Immediately jumps back to the top of the loop and rechecks the condition. |
| Truthy / falsey | Non-Boolean values treated as True or False in a condition (0, 0.0, ‘’ are falsey). |
| range() | A function that generates a sequence of integers for a for loop to iterate over. |
| Module | A separate Python program containing related functions you can import into your own. |
| import statement | A statement that makes a module’s functions available in your program. |
| sys.exit() | A function (from the sys module) that immediately terminates the program. |
1. while Loop Statements
A while loop repeats its clause as long as its condition is True. Unlike an if statement, execution jumps back to the top of the loop at the end of the clause instead of continuing past it.
spam = 0 while spam < 5: print('Hello, world.') spam = spam + 1
The condition is checked at the start of every iteration. As soon as it evaluates to False, the loop’s clause is skipped and execution moves on.
2. break and continue Statements
break
Immediately exits the loop’s clause, skipping the rest of the iterations entirely.
while True: print('Please type your name.') name = input('>') if name == 'your name': break print('Thank you!')
continue
Immediately jumps back to the top of the loop and rechecks the condition, skipping the rest of the current iteration’s code.
while True: print('Who are you?') name = input('>') if name != 'Joe': continue print('Hello, Joe. What is the password?') password = input('>') if password == 'swordfish': break print('Access granted.')
break and continue can only be used inside while or for loops.
3. Truthy and Falsey Values
Conditions can use non-Boolean values directly. 0, 0.0, and ‘’ (empty string) are treated as False; every other value is treated as True.
`>>> bool(0) False
bool(42) True bool(‘Hello’) True bool(‘’) False`
while not name: is equivalent to while name == ‘’:
4. for Loops and the range() Function
A for loop repeats its clause a specific number of times, based on the sequence range() produces.
for i in range(5): print('On this iteration, i is set to ' + str(i))
range() has three forms:
| Call | Produces | Notes |
|---|---|---|
| range(5) | 0, 1, 2, 3, 4 | Starts at 0; stops before the given number. |
| range(12, 16) | 12, 13, 14, 15 | Custom start and stop (stop not included). |
| range(0, 10, 2) | 0, 2, 4, 6, 8 | The third argument is the step. |
| range(5, -1, -1) | 5, 4, 3, 2, 1, 0 | A negative step counts down. |
A for loop can always be rewritten as an equivalent while loop:
print('Hello!') i = 0 while i < 5: print('On this iteration, i is set to ' + str(i)) i = i + 1 print('Goodbye!')
5. Importing Modules
Python’s standard library provides modules, separate programs full of related functions. You must import a module before using its functions.
import random for i in range(5): print(random.randint(1, 10))
- Use module_name.function_name() to call a function from an imported module.
- You can import several modules on one line: import random, sys, os, math
- Never name your own program the same as a module you want to import (e.g., random.py).
6. Ending a Program Early with sys.exit()
sys.exit() immediately terminates the program, even if it’s inside an infinite loop with no break statement. It comes from the sys module, so sys must be imported first.
`import sys
while True: print(‘Type exit to exit.’) response = input(‘>’) if response == ‘exit’: sys.exit() print(’You typed ’ + response + ‘.’)`