Lesson 5: Conditional Statements

๐ŸŽฏ Lesson Objective

To learn how Python makes decisions using conditional statements (if, elif, else) and apply them in real-world programs.


๐Ÿง  1. What Are Conditional Statements?

Conditional statements help your program make decisions based on certain conditions.
They use boolean expressions (True or False) to decide which block of code to execute.

Example:

age = 18
if age >= 18:
    print("You are eligible to vote.")

โš™๏ธ 2. Basic if Statement

The simplest form checks a condition and executes the block if itโ€™s True.

x = 10
if x > 5:
    print("x is greater than 5")

Output:

x is greater than 5

๐Ÿ”„ 3. if...else Statement

Used when you want to perform one action if the condition is True, and another if itโ€™s False.

number = int(input("Enter a number: "))
if number % 2 == 0:
    print("Even number")
else:
    print("Odd number")

Output (if number = 7):

Odd number

๐Ÿงฉ 4. if...elif...else (Multiple Conditions)

Used when you need to check more than one condition.

marks = 85
if marks >= 90:
    print("Grade A")
elif marks >= 75:
    print("Grade B")
elif marks >= 50:
    print("Grade C")
else:
    print("Fail")

Output:

Grade B

๐Ÿ” 5. Nested if Statements

You can place one if inside another to test multiple levels of conditions.

age = 25
citizen = True

if age >= 18:
    if citizen:
        print("Eligible to vote")
    else:
        print("Not a citizen")
else:
    print("Underage")

Output:

Eligible to vote

๐Ÿงฎ 6. Short-Hand if (Single-Line Condition)

You can write simple conditions in one line:

a = 10
b = 5
print("a is greater") if a > b else print("b is greater")

Output:

a is greater

๐Ÿ’ก 7. Combining Conditions

You can combine multiple conditions using logical operators (and, or, not).

age = 20
has_id = True

if age >= 18 and has_id:
    print("Entry allowed")
else:
    print("Entry denied")

๐ŸŒ 8. Real-Life Example: Traffic Light Program

signal = input("Enter traffic signal color: ")

if signal.lower() == "red":
    print("Stop!")
elif signal.lower() == "yellow":
    print("Ready to go!")
elif signal.lower() == "green":
    print("Go!")
else:
    print("Invalid signal color")

๐Ÿง  9. Practice Ideas

Ask for a temperature and print โ€œColdโ€, โ€œWarmโ€, or โ€œHotโ€.

Write a program to check whether a number is positive, negative, or zero.

Take user marks as input and print the grade (A, B, C, or Fail).

Build a simple login system using username and password conditions.

Create a program that checks if a year is a leap year.

more examples


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *