Python Level 3: Conditions (if / elif / else)

Goal of this Level

Today you will learn to:

By the end, you will be able to write programs that respond to input.

Step 1: Why Conditions are Important

Programs often need to make decisions.

Examples:

For that, we use conditions.

Step 2: The if Condition

if means:

If a condition is true, then execute the code.


age = 20

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

Explanation:

Step 3: if and else

Sometimes something should happen if the condition is false.

For that, there is else.


age = 16

if age >= 18:
    print("You are an adult")
else:
    print("You are still a minor")

Explanation:

Step 4: if, elif, and else

Sometimes there are multiple possibilities.

For that, we use elif.


points = 80

if points >= 90:
    print("Grade A")
elif points >= 75:
    print("Grade B")
elif points >= 60:
    print("Grade C")
else:
    print("Failed")

Explanation:

Step 5: Comparison Operators

These operators are used to compare values.

Examples:


number = 10

if number == 10:
    print("The number is 10")

if number != 5:
    print("The number is not 5")

Step 6: Logical Operators

Sometimes multiple conditions need to be checked at the same time.

and

Both conditions must be true.


age = 20
has_ticket = True

if age >= 18 and has_ticket == True:
    print("You may enter")

or

Only one condition must be true.


day = "Saturday"

if day == "Saturday" or day == "Sunday":
    print("It is the weekend")

not

Reverses a condition.


rain = False

if not rain:
    print("It is not raining")

Practice Example


name = input("What is your name? ")
age = int(input("How old are you? "))

if age >= 18:
    print("Hello", name)
    print("You are an adult")
else:
    print("Hello", name)
    print("You are still a minor")

Step 7: The Modulo Operator (%)

The % operator returns the remainder of a division.

Example:


10 % 2 = 0
9 % 2 = 1

This is often used to check if a number is even or odd.

Practice Task

Write a program that checks whether a number is even or odd.

Steps:


number = int(input("Enter a number: "))

if number % 2 == 0:
    print("The number is even")
else:
    print("The number is odd")