Flow controls: Conditions · 1 / 22 Theory

The if statement

Until now your programs ran all their lines, one after the other. With conditions the program can decide: it runs a block of code only if something is true.

Structure of an if

age = int(input())

if age >= 18:
    print("You are an adult")

print("End of the program")

The condition is an expression that gives True or False (the kind you learned in comparisons). If it is True, the block runs; if it is False, it is skipped. The last line does not depend on the if, so it is always shown.

The colon and the indentation

Two details are mandatory in Python:

  • The if line ends with a colon :.
  • The lines that belong to the block are indented: 4 spaces is the usual choice. All the lines of the block must use the same indentation.

Indentation is not decoration: it tells Python which lines are inside the if.

x = 5
if x > 10:
    print("big")
    print("very big")   # also inside the if
print("always")          # outside the if

Several statements in the block

n = int(input())
if n < 0:
    n = -n
    print("Sign changed")
print(n)

With the input -7 it shows Sign changed and then 7. With 7 it only shows 7. This is the idea of the exercise ABS - Absolute value.

What can go in the condition

Any expression that gives a logical value: a comparison (x > 0), a boolean variable, the result of a method (text.isdigit()) or a combination with and, or and not (you will see it in a later article).

word = input()
if word.isdigit():
    print("Digits only")

Practice with Basic calculator using if.