if

Control Flow

if

In this tutorial, we'll run code only when a condition is true.

An if statement runs code only when a condition is true.

temperature = 28

if temperature > 25:
    print("It is warm")

The message only prints if temperature > 25 is True.

The Shape of an if Statement

An if statement has:

  • The word if
  • A condition
  • A colon
  • An indented block of code
if condition:
    code_to_run

Indentation is not just style in Python. It tells Python which lines belong inside the if.

Example With a Score

score = 82

if score >= 50:
    print("You passed")

print("Program finished")

If the score is high enough, both messages print. If not, only "Program finished" prints.

Multiple Lines Inside if

You can put several lines in the block:

is_member = True

if is_member:
    print("Welcome back")
    print("You get free delivery")

Both indented lines belong to the if.

Common Mistake

Forgetting the colon causes an error:

if score >= 50
    print("Pass")

Correct version:

if score >= 50:
    print("Pass")

Code Outside the if

Only indented code belongs to the if:

score = 40

if score >= 50:
    print("Pass")

print("This always runs")

This is important. The final print() is not indented, so it runs whether the score passes or not.

Practice

Create a variable called battery. If it is below 20, print "Low battery".