Conditional Statements (if-else)

1. Introduction

Conditional statements allow a program to execute different blocks of code based on specific conditions. Python provides the following conditional statements:

  • if
  • if-else
  • if-elif-else
  • Nested if statements

2. The if Statement

The if statement executes a block of code only if the condition evaluates to True.

Syntax

if condition:
    # Code to execute if condition is True

Example

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

Output

You are eligible to vote!

If the condition is False, the code inside if is skipped.


3. The if-else Statement

The else block executes when the if condition is False.

Syntax

if condition:
    # Code to execute if condition is True
else:
    # Code to execute if condition is False

Example

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

Output

Even number

4. The if-elif-else Statement

Use elif (short for "else if") to check multiple conditions.

Syntax

if condition1:
    # Code if condition1 is True
elif condition2:
    # Code if condition2 is True
else:
    # Code if all conditions are False

Example

marks = 85

if marks >= 90:
    print("Grade: A")
elif marks >= 80:
    print("Grade: B")
elif marks >= 70:
    print("Grade: C")
else:
    print("Grade: F")

Output

Grade: B

5. Nested if Statements

You can place one if statement inside another.

Example

num = 15

if num > 10:
    print("Greater than 10")
    if num % 5 == 0:
        print("Divisible by 5")

Output

Greater than 10
Divisible by 5

6. Short-Hand (if Statement in One Line)

You can write simple if statements in a single line.

Example

x = 5
if x > 0: print("Positive number")

For if-else, use the ternary operator:

num = 7
result = "Even" if num % 2 == 0 else "Odd"
print(result)

Output

Odd

7. Logical Operators in Conditions

You can combine multiple conditions using:

  • and (both conditions must be True)
  • or (at least one condition must be True)
  • not (negates the condition)

Example

age = 20
has_id = True

if age >= 18 and has_id:
    print("Allowed to enter")

Output

Allowed to enter

8. Practical Example: Login System

username = "admin"
password = "1234"

user_input = input("Enter username: ")
pass_input = input("Enter password: ")

if user_input == username and pass_input == password:
    print("Login successful!")
else:
    print("Invalid credentials")

9. Summary

  • if executes a block if the condition is True.
  • if-else provides an alternative block if the condition is False.
  • if-elif-else checks multiple conditions.
  • Nested if allows conditions inside another if.
  • Logical operators (and, or, not) combine conditions.