Python Basics

If Else in Python

Conditions let a program choose what to do: Python checks each if or elif in order and runs the first block whose condition is True.

What is If Else?

Conditions let a program choose what to do: Python checks each if or elif in order and runs the first block whose condition is True.

Make decisions with if, elif and else, and combine conditions with and, or and not.

When should you use it?

  • Learn Python syntax through a practical example.
  • Build a foundation for larger programming problems.
  • Test an idea quickly without a local setup.

See how it works

Move the slider to change the score. The flowchart lights up the path the program takes, and the matching line of code is highlighted.

Example code

Run code →
main.py
temperature = 23

# if / elif / else picks the first branch whose condition is True.
if temperature >= 30:
    print("It's hot")
elif temperature >= 20:
    print("It's warm")
elif temperature >= 10:
    print("It's cool")
else:
    print("It's cold")

# and, or, not combine conditions.
age = 17
has_ticket = True
if age >= 18 and has_ticket:
    print("You can enter")
elif not has_ticket:
    print("Please buy a ticket")
else:
    print("You need an adult with you")

# A conditional expression chooses between two values on one line.
number = 7
kind = "even" if number % 2 == 0 else "odd"
print(number, "is", kind)

Expected output

It's warm
You need an adult with you
7 is odd

How it works

Indentation marks which lines belong to each branch. and, or and not build bigger conditions, and value_if_true if condition else value_if_false picks a value on one line.

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in Python IDE →

Practice with a challenge

Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.

All challenges