Lesson 2.2

If–Else Statements

Reminder: If statements

x = 10
if x > 5:
    print("x is greater than 5")
  • Runs the indented code only if condition is True

What if the condition is False?

  • Sometimes we want different code if the test is False
  • That’s where else comes in

Syntax of if–else

if condition:
    # runs if condition is True
else:
    # runs if condition is False

Example

age = int(input("Enter your age: "))
if age >= 18:
    print("You are an adult")
else:
    print("You are not an adult")

Indentation matters!

  • Both the if block and the else block must be indented
  • Each block starts on a new line
  • Outside code goes back to the left margin

Example with indentation

if True:
    print("Inside IF")
else:
    print("Inside ELSE")
print("Outside both")

Classroom Question

What will this print?

x = 3
if x > 10:
    print("Big number")
else:
    print("Small number")

Practice Challenge

Ask the user for a number:

  • If it’s even, print "Even number"
  • Else, print "Odd number"