Python Basics: Your First Programs
Decisions and Loops
In this lesson you will
- Choose between paths with if, elif and else
- Combine comparisons with and, or and not
- Repeat code with for and while loops and range
Introduction
So far every program ran straight down, line by line. Real programs decide ("is the password correct?") and repeat ("do this for each item"). These two ideas, conditions and loops, are the heart of programming.
Comparisons give True or False
The operators are ==, !=, <, >, <= and >=. Remember that a single = stores a value, while == asks whether two values are equal.
if, elif, else
Indentation matters in Python. The lines indented under if belong to it, and Python uses the indentation, usually four spaces, to know where the block ends.
Python checks the conditions from top to bottom and runs the first one that is true. Change temperature and run it several times.
Quick quiz
What does Python use to know which lines belong inside an if block?
and, or, not
Combine conditions with the words and, or and not.
You can chain comparisons the way people write maths: 12 <= age < 18 is true for ages 12 to 17.
Truthy and falsy
Python treats some values as false in an if: 0, an empty string "", an empty list [] and None. Everything else counts as true.
for loops
A for loop does something once for each item in a sequence.
range() makes a sequence of numbers. range(5) is 0, 1, 2, 3, 4, and it stops before the end number.
You can loop over the letters of a string too:
while loops
A while loop repeats as long as its condition is true. Make sure something inside the loop changes, or it will never stop.
break and continue
breakleaves the loop immediately.continueskips to the next round.
Quick quiz
How many times does for i in range(3) run its body?
Putting it together: FizzBuzz
A classic exercise: for numbers 1 to 15, print Fizz if divisible by 3, Buzz if divisible by 5, FizzBuzz if both, otherwise the number.
Notice the order: we test for 15 first, because a number divisible by 15 is also divisible by 3 and 5.
Try it yourself
Write a loop that adds up the numbers from 1 to 100 and prints the total (the answer is 5050). Then change it to add up only the even numbers.
Summary
- Comparisons (
==,!=,<,>) give True or False. Combine them withand,or,not. if,elifandelsechoose a path, and indentation marks the block.forloops over a sequence, andrange(n)counts from 0 up to n - 1.whilerepeats while a condition holds.breakleaves a loop andcontinueskips to the next round.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading