Lesson ยท 12 min
Making decisions
Code that decides
An if statement runs a block of code only when a condition is true.
score = 72
if score >= 50:
print("Pass")
else:
print("Try again")
Two details are important in Python:
- The line with
iforelseends with a colon:. - The block under it is indented, usually with four spaces. The indent is how Python knows which lines belong to the block.
Comparison operators
| Operator | Meaning |
|---|---|
== |
is equal to |
!= |
is not equal to |
> and < |
greater than, less than |
>= and <= |
greater than or equal to, less than or equal to |
Use two equal signs, ==, to compare. One equal sign, =, stores a value in a variable.
and, or, not
You can join conditions with words.
a and bis true when both are true.a or bis true when at least one is true.not aturnsTrueintoFalse, andFalseintoTrue.
More than two paths
Use elif (short for "else if") to add more conditions. Python checks them from top to bottom and runs the first block whose condition is true.
Functions in this lesson
The editor has four functions. A function is a named block of code. You can give it values, and it gives a value back with return. You will write your own functions in lesson 8. For now, replace the word pass in each function with your code. The checker calls each function with many values, so your code must work for all of them.
def double(n):
return n * 2
Your turn
Do the four tasks in order.
Tasks
4 to do
Task 1, not checked yet. In
describe_temperature, return'Warm'whentemperatureis20or higher. Otherwise return'Cool'. Useifandelse.Task 2, not checked yet. In
can_enter, returnTrueonly whenageis12or more andhas_ticketisTrue. Use theandoperator.Task 3, not checked yet. In
day_type, return'Weekend'whendayis'Sat'or'Sun'. Otherwise return'Weekday'. Use theoroperator.Task 4, not checked yet. In
grade, return'A'for90or more,'B'for80or more,'C'for70or more, and'F'for anything lower. Useelif.
Task 1 of 4
In describe_temperature, return 'Warm' when temperature is 20 or higher. Otherwise return 'Cool'. Use if and else.