Python

Lesson 4 of 10

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 if or else ends 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 b is true when both are true.
  • a or b is true when at least one is true.
  • not a turns True into False, and False into True.

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

  1. Task 1, not checked yet. In describe_temperature, return 'Warm' when temperature is 20 or higher. Otherwise return 'Cool'. Use if and else.

  2. Task 2, not checked yet. In can_enter, return True only when age is 12 or more and has_ticket is True. Use the and operator.

  3. Task 3, not checked yet. In day_type, return 'Weekend' when day is 'Sat' or 'Sun'. Otherwise return 'Weekday'. Use the or operator.

  4. Task 4, not checked yet. In grade, return 'A' for 90 or more, 'B' for 80 or more, 'C' for 70 or more, and 'F' for anything lower. Use elif.

Task 1 of 4

In describe_temperature, return 'Warm' when temperature is 20 or higher. Otherwise return 'Cool'. Use if and else.

All tasks

main.py

Ctrl+Enter runs your code. Ctrl+Shift+Enter checks it. Press Esc, then Tab, to leave the editor.

Output

Press Run to see your result

Your output shows here. Press Run to try your code.