Loops and Conditionals
Last updated on 2026-10-19 | Edit this page
Estimated time: 25 minutes
Overview
Questions
- How can I do the same thing for many values?
- How can my program make decisions?
Objectives
- Use a
forloop to repeat an operation for each element of a list. - Use
if,elifandelseto run code only under certain conditions.
For loops
A for loop repeats an operation once for each element in
a collection. The general structure of a loop is:
- We can name the loop variable anything we like.
- There must be a colon at the end of the line that starts the loop.
- We must indent anything that we want to run inside the loop. Unlike
in many other programming languages, there is no command to signify the
end of the loop body. Anything indented after the
forstatement belongs to the loop.
PYTHON
names = ["Lovelace", "Hopper", "Noether", "Turing"]
for person in names:
print(person + " did awesome stuff.")
OUTPUT
Lovelace did awesome stuff.
Hopper did awesome stuff.
Noether did awesome stuff.
Turing did awesome stuff.
Loops are a robust way of dealing with collections such as lists. Even if the values in the list change, the loop will still work.
As with all variable names, it is helpful to give loop variables
meaningful names that you will understand as your code grows. For
example, for person in names is easier to understand than
for kitten in names.
Conditions and if statements
An if statement is a conditional statement that
determines whether a block of code is executed. The syntax of an
if statement is similar to that of a for
statement:
- The first line begins with
ifand ends with a colon. - The body is indented (usually by four spaces).
OUTPUT
It's warm
The condition itself is just a value of type bool:
OUTPUT
True
We can use an else statement following an
if statement to specify an alternative code block to
execute when the if branch is not taken.
OUTPUT
It's cold
You can use elif (short for “else if”) to provide
several alternative choices, each with its own test. An
elif statement must always follow an if
statement and come before the else statement (the
catch-all).
PYTHON
temp = 15
if temp >= 25:
print("It's hot")
elif temp >= 15:
print("It's warm")
else:
print("It's cold")
OUTPUT
It's warm
Conditions are tested in order and only once. Python steps through the branches of the conditional statement in order, testing each one in turn, so the order of your statements matters.
Comparison operators
-
==equal to (note the two equals signs!) -
!=not equal to -
>and<greater than, less than -
>=and<=greater than or equal to, less than or equal to
Combine loops and conditionals
Print only the names of the people in
authors_and_birth_years who were born before 1900.
- A
forloop runs its indented body once for each element of a collection. - Use
if,elifandelseto choose which code to run. - Conditions are tested in order; the first one that is
Truewins. - Indentation defines which lines belong to a loop or an
ifstatement.