Conditions and loops
Programs become useful when they make decisions and repeat work. Python has if for decisions and for / while for repetition.
if, elif, else
Python checks each condition from top to bottom and runs only the first block that's true. Change the input and run again.
Combining conditions
The one-line conditional expression
match: checking one value against many patterns
Python 3.10 added match, which is cleaner than a long elif chain when you compare one value against several options:
_ is the wildcard ("anything else"). Notice ["go", direction] also captures the second word into a variable.
for loops
A for loop runs once for each item in a sequence:
range(): looping a number of times
enumerate and zip
Use enumerate instead of range(len(...)) when you need the index, and zip to walk several lists together.
while loops
A while loop repeats as long as its condition is true. Use it when you don't know in advance how many times to loop:
⚠️ Make sure the condition eventually becomes false, or the loop runs forever. (The editor stops runaway code after 10 seconds.)
break, continue and else
A loop's else block runs only if the loop finished without break, which is perfect for searches:
Nested loops
A small game: guess the number
The program picks a number; each guess comes from the Input box:
Change the guesses in the Input box, or use import random and random.randint(1, 100) to pick a different secret each time.
Practice
- FizzBuzz: print the numbers 1 to 30, but "Fizz" for multiples of 3, "Buzz" for multiples of 5, and "FizzBuzz" for multiples of both.
- Print a triangle of
*with 5 rows (hint:"*" * n). - Add up all the digits of a number such as
98765using awhileloop with% 10and// 10.
1.How many times does for i in range(2, 8, 2) run?
2.What does continue do inside a loop?
3.When does a for loop's else block run?