If-Else Statements in Python


Basic If Statement

The simplest form of decision making in Python. The if statement runs a block of code only when the given condition is true.

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

Output:

You are eligible to vote.

If-Else Statement

Use else to specify a block of code that runs when the condition is false.

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

Output:

You are not eligible to vote.

If-Elif-Else Chain

Use when you have multiple conditions to check in sequence.

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

Multiple Conditions using and, or

Use logical operators to combine multiple conditions.

marks = 75
attendance = 90

if marks >= 70 and attendance >= 85:
    print("Eligible for certificate.")
else:
    print("Not eligible.")

Output:

Eligible for certificate.

Nested If

An if block inside another if block. Used when decisions depend on another level of conditions.

x = 10
if x > 0:
    if x % 2 == 0:
        print("Positive even number.")
    else:
        print("Positive odd number.")

Output:

Positive even number.

Short-Hand If

A compact way to write simple if statements.

num = 5
if num > 0: print("Number is positive.")

Output:

Number is positive.

Short-Hand If-Else (Ternary Operator)

Condensed syntax for if-else in one line.

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

Output:

b is greater

Practical Example: User Input with If-Else

Check eligibility based on user input.

 name = input("Enter your name: ")
 age = int(input("Enter your age: "))

 if age >= 18:
     print(f"{name}, you are allowed to drive.")
 else:
     print(f"Sorry {name}, you are underage.")

Output:

Enter your name: John
Enter your age: 17
Sorry John, you are underage.

Use of pass in If

Use pass as a placeholder when you haven’t written the code yet but need syntactically correct structure.

x = 10
if x > 0:
    pass  # To be implemented later