Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Python If ... Else

Programs become useful when they can make decisions: give a discount only to members, print a grade that depends on the marks, stop a game when the lives run out. In Python a decision is written with if, optionally followed by elif ("else if") branches and an else branch.

if and else

if is followed by a condition and a colon. When the condition is true, the indented block below runs. Otherwise the else block runs, if there is one:

age = int(input("Your age: "))
if age >= 18:
    print("You can vote.")
else:
    print(f"You can vote in {18 - age} years.")
print("Thank you.")
You type
15
Output
Your age: You can vote in 3 years.
Thank you.

Remember the two rules from the Syntax topic: the line with if or else ends with a colon, and the lines of each block are indented by the same amount.

Several branches with elif

When there are more than two cases, add elif branches. Python checks the conditions from the top and runs only the first block whose condition is true:

marks = 82
if marks >= 90:
    grade = "A"
elif marks >= 75:
    grade = "B"
elif marks >= 60:
    grade = "C"
else:
    grade = "F"
print("Grade:", grade)
Output
Grade: B

Because the checks go from the top, marks >= 75 does not need and marks < 90: if the marks had been 90 or more, the first branch would already have been taken.

Nested conditions and combined conditions

A block can contain another if. Often, though, and and or express the same idea more simply:

temperature, raining = 24, True
if temperature > 20:
    if raining:
        print("Warm, but take an umbrella.")
    else:
        print("A lovely day.")
if temperature > 20 and not raining:
    print("Go to the park.")
Output
Warm, but take an umbrella.

The conditional expression

For a simple choice between two values, Python has a one-line form: value_if_true if condition else value_if_false.

n = 7
kind = "even" if n % 2 == 0 else "odd"
print(n, "is", kind)
Output
7 is odd

pass

A block cannot be empty. When you want to write the structure first and fill it in later, put pass in the block: it is a statement that does nothing.

Practice exercises

  1. Ask for a number and print whether it is positive, negative or zero.
  2. Ask for a year and print whether it is a leap year.
  3. Ask for the price of a purchase: give 10 percent off above 1000 and 20 percent off above 5000, and print the final price.
  4. Rewrite a short if ... else that assigns a variable as a conditional expression.