easycodelearning.com
🐍 Learn Python Online
Back to All Tutorials

Conditional Statements

What are Conditional Statements?

Conditional statements allow your program to make decisions based on conditions. They control the flow of your program by executing different code blocks based on whether a condition is true or false.

The if Statement

Execute code only if a condition is true:

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

The if-else Statement

Execute one block if true, another if false:

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

The if-elif-else Statement

Check multiple conditions:

score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")
    
# Output: Grade: B

Comparison Operators

Used to compare values:

  • == - Equal to
  • != - Not equal to
  • > - Greater than
  • < - Less than
  • >= - Greater than or equal to
  • <= - Less than or equal to

Examples:

x = 10
print(x == 10)   # True
print(x != 5)    # True
print(x > 5)     # True
print(x < 15)    # True
print(x >= 10)   # True
print(x <= 10)   # True

Logical Operators

Combine multiple conditions:

and - Both conditions must be true

age = 25
has_license = True
if age >= 18 and has_license:
    print("You can drive")
    
# Output: You can drive

or - At least one condition must be true

day = "Saturday"
if day == "Saturday" or day == "Sunday":
    print("It's the weekend!")
    
# Output: It's the weekend!

not - Reverses the condition

is_raining = False
if not is_raining:
    print("Let's go outside!")
    
# Output: Let's go outside!

Nested Conditionals

Conditionals inside conditionals:

age = 20
has_money = True
if age >= 18:
    if has_money:
        print("You can buy a ticket")
    else:
        print("You need money")
else:
    print("You are too young")
    
# Output: You can buy a ticket

Practical Examples

Check if a number is positive, negative, or zero

number = -5
if number > 0:
    print("Positive")
elif number < 0:
    print("Negative")
else:
    print("Zero")

Check if a number is even or odd

number = 7
if number % 2 == 0:
    print("Even")
else:
    print("Odd")

Key Takeaways

  • Use if to execute code conditionally
  • Use else for alternative code
  • Use elif for multiple conditions
  • Comparison operators: ==, !=, >, <, >=, <=
  • Logical operators: and, or, not
  • Indent code blocks properly

Practice Time

Write programs that make decisions based on user input or variable values!

Open Code Editor
Back to All Tutorials