Free resource / Python basics

Python if statement
cheat sheet.

Make decisions in your code. Learn the basic patterns, check the operators, and work through 12 examples you can copy and adapt.

Jump to the 12 examples ↓Download Python examples

01 / Start with the structure

The basic pattern

Python checks from top to bottom and runs the first matching branch. elif and else are optional. Use a colon and indent each body by four spaces.

score = 75
if score >= 80:
    print("High score")
elif score >= 50:
    print("Pass")
else:
    print("Try again")

A condition evaluates as true or false. After one branch runs, Python skips the rest of that chain and continues after the indented block. An else has no condition.

02 / Operators at a glance

Comparison and logical operators
OperatorMeaningExample
==Equal tox == 5
!=Not equal tox != 5
>Greater thanx > 5
<Less thanx < 5
>=Greater than or equal tox >= 5
<=Less than or equal tox <= 5
andBoth conditions must be trueage >= 13 and age <= 19
orAt least one condition must be trueday == "Sat" or day == "Sun"
notReverse the conditionnot is_ready
in / not inMembership / non-membershipchoice in ("yes", "y")

Python also supports chained comparisons: 0 <= grade <= 100 means grade >= 0 and grade <= 100. Use parentheses to make mixed and/or conditions clear; not binds before and, then or.

03 / Useful patterns

Separate ifs or one chain?

Separate if statements can both run. An if/elif chain chooses at most one branch.

score = 95
if score >= 50:
    print("Passed")
if score >= 90:
    print("Excellent")
# Both messages print.

Nested conditions

Put an if inside another if when the second decision depends on the first.

has_ticket = True
age = 16
if has_ticket:
    if age >= 12:
        print("Enter the show")
    else:
        print("An adult must accompany you")
else:
    print("You need a ticket")

Boolean values and membership

Use Boolean variables directly. in checks membership; not reverses a condition. Empty strings, zero, None, and empty collections are falsy.

is_ready = True
choice = "yes"
if is_ready and choice in ("yes", "y"):
    print("Start")
if not is_ready:
    print("Wait")

Short conditional expression

Useful for a simple choice between two values. Keep longer decisions in normal blocks.

age = 16
label = "adult" if age >= 18 else "child"
print(label)

Handle non-numeric input

input() returns a string. int() accepts whole numbers; float() also accepts decimals. Bad numeric text raises ValueError before an if can check its range. Use try/except when you need to handle it.

try:
    age = int(input("Enter your age: "))
except ValueError:
    print("Please enter a whole number.")
else:
    if age < 0:
        print("Age cannot be negative.")
    else:
        print("Valid age.")

04 / Twelve practical examples

Run each example separately in Python 3. Numeric examples assume valid numeric text unless they explicitly use try/except. They check ranges after conversion.

Example 01

Positive or not

Zero is not positive. Use > rather than >=.

number = int(input("Enter a number: "))
if number > 0:
    print("The number is positive.")
else:
    print("The number is not positive.")
Example 02

Pass or fail

Validate the range first, then check the pass mark. These examples use a pass mark of 50.

grade = int(input("Enter your grade: "))
if grade < 0 or grade > 100:
    print("Invalid grade. Enter 0 to 100.")
elif grade >= 50:
    print("You passed the class.")
else:
    print("You failed the class.")
Example 03

Even or odd

% gives the remainder. An integer is even when dividing by 2 leaves no remainder.

number = int(input("Enter a number: "))
if number % 2 == 0:
    print("The number is even.")
else:
    print("The number is odd.")
Example 04

Adult or child

For this exercise, adult means age 18 or above. Reject negative ages first.

age = int(input("Enter your age: "))
if age < 0:
    print("Invalid age.")
elif age >= 18:
    print("You are an adult.")
else:
    print("You are a child.")
Example 05

Larger of two numbers

After checking both greater-than cases, the only remaining possibility is equality.

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
if num1 > num2:
    print("The larger number is", num1)
elif num2 > num1:
    print("The larger number is", num2)
else:
    print("The numbers are equal.")
Example 06

Numerical grade to letter grade

Check from highest to lowest. Earlier branches have already ruled out higher grades. This is a practice scale, not official Cambridge grade boundaries.

grade = int(input("Enter your grade: "))
if not 0 <= grade <= 100:
    print("Invalid grade. Enter 0 to 100.")
elif grade >= 90:
    print("You got an A.")
elif grade >= 80:
    print("You got a B.")
elif grade >= 70:
    print("You got a C.")
elif grade >= 60:
    print("You got a D.")
else:
    print("You got an F.")
Example 07

Hot, warm, or cold

With these chosen thresholds, 30°C is warm and 20°C is cold. float() also accepts decimal temperatures.

temperature = float(input("Temperature in Celsius: "))
if temperature > 30:
    print("It is hot.")
elif temperature > 20:
    print("It is warm.")
else:
    print("It is cold.")
Example 08

Compare two strings

This keeps the username/password comparison as a string exercise. Equality is case-sensitive. It does not authenticate a user; use made-up values, not a real password.

username = input("Enter a practice username: ")
password = input("Enter a practice password: ")
if username == password:
    print("The strings match.")
else:
    print("The strings do not match.")
Example 09

Leap year

For Gregorian calendar years: divisible by 400, or divisible by 4 but not by 100. 2000 is a leap year; 1900 is not.

year = int(input("Enter a year: "))
if year <= 0:
    print("Enter a positive year.")
elif year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
    print("This is a leap year.")
else:
    print("This is not a leap year.")
Example 10

Simple calculator

Check the operator and guard both division operations against zero. / divides; // performs floor division (rounds down, so -5 // 2 is -3).

number1 = float(input("First number: "))
number2 = float(input("Second number: "))
operator = input("Operator (+, -, *, /, //): ").strip()
if operator not in ("+", "-", "*", "/", "//"):
    print("Invalid operator.")
elif operator in ("/", "//") and number2 == 0:
    print("Cannot divide by zero.")
elif operator == "+":
    print(number1 + number2)
elif operator == "-":
    print(number1 - number2)
elif operator == "*":
    print(number1 * number2)
elif operator == "/":
    print(number1 / number2)
else:
    print(number1 // number2)
Example 11

Apply a 10% discount

Over 1000 means strictly greater than 1000. An amount of exactly 1000 gets no discount.

amount = float(input("Purchase amount: "))
if amount < 0:
    print("Invalid amount.")
elif amount > 1000:
    print("Total:", round(amount * 0.9, 2))
else:
    print("No discount. Total:", amount)
Example 12

Largest of three numbers

Using >= handles tied largest values too: 5, 5, 2 correctly gives 5. Strict > checks alone miss this case.

n1 = int(input("First number: "))
n2 = int(input("Second number: "))
n3 = int(input("Third number: "))
if n1 == n2 == n3:
    print("All numbers are equal:", n1)
elif n1 >= n2 and n1 >= n3:
    print("The largest number is", n1)
elif n2 >= n1 and n2 >= n3:
    print("The largest number is", n2)
else:
    print("The largest number is", n3)

05 / Common mistakes to catch

  • Using = instead of ==. = assigns a value; == compares two values.
  • Missing the colon or indentation. End each if, elif, and else header with :. Align elif and else with their if.
  • Writing “else if”. Python uses elif.
  • Writing x == 1 or 2. Use x == 1 or x == 2, or x in (1, 2). The value 2 by itself is truthy.
  • Checking a broad condition first. If you check grade >= 50 before grade >= 90 in the same chain, a score of 95 matches the first branch.
  • Forgetting boundaries and ties. Try 0, 18, 20, 30, 50, 100, and equal numbers where relevant. Test just below, exactly at, and just above a threshold.
  • Comparing input as text. "10" < "2" is true because strings compare lexicographically. Convert numeric input first.
  • Using is for equality. Use == for equal values. is checks object identity; value is None is a standard use.

Keep exploring with the official Python tutorial ↗.

← More free resources