In this lesson, we will learn about...
These allow us to selectively run parts of a program depending on if a condition is met. Let's look at the anatomy of an if statement.
if CONDITION:
do something
elif CONDITION:
do another thing
else:
do a third thing
This corresponds to the following actions in plain English:
NOTE: Only the if
is required. You can leave out elif
and else
entirely, and have as many elif
s as you want. You can only have one if
and one else
.
x = 5
if x % 2 == 0:
print(x, "is even!")
else:
print(x, "is odd!")
5 is odd!
Conditions are anything that resolve to either True
or False
. They can be...
Some values aren't the literal False
but still evaluate to be False
. These are called falsy. They are...
None
False
Any other values are considered truthy and evaluate to True
.
Recall from Lesson 3 that there are several operators used for comparisons. There are also operators to combine expressions, such as and
and or
called logical operators.
Loops let us run a section of code over and over again. There are two main types of loops in python...
These loops run while a condition is true. These conditions are the same as with if statements.
i = 1
while i < 6:
print(i)
i += 1
1 2 3 4 5
break
and continue
¶You can use these keywords in a loop to stop the loop (break
) or skip to the next iteration (continue
).
i = 1
while i < 6:
if i == 3:
i += 1
continue
elif i == 5:
break
print(i)
i += 1
1 2 4
For loops are used to iterate over a sequence or finite range (list, tuple, set, string, ...)
fruits = ["banana", "orange", "strawberry"]
for fruit in fruits:
print(fruit)
banana orange strawberry
range()
¶The range()
function generates a sequence of numbers from 0 (by default) to a number with a step of 1 (by default).
for x in range(3):
print(x)
0 1 2
for y in range (1,4):
print(y)
1 2 3
for z in range (2,10,2):
print(z)
2 4 6 8
NOTE: break
and continue
also work here in the same way as for
loops.