Some text some message..
Back 5. ✅ Conditional Statements in Python 20 Jun, 2025

Conditional statements in Python are used to execute specific blocks of code based on certain conditions. These are decision-making constructs that check whether a condition is True or False.


🧠 Why use Conditional Statements?

To control the flow of the program depending on different conditions like:

  • Checking if a user is eligible to vote.

  • Determining whether a number is positive, negative, or zero.

  • Running different operations based on user input.


🔹 Types of Conditional Statements:

Python has the following types of conditional statements:

1. if Statement

Executes a block of code only if the condition is True.

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

2. if-else Statement

Executes one block if condition is True, another block if False.

age = 16
if age >= 18:
    print("You can vote.")
else:
    print("You cannot vote.")

3. if-elif-else Statement

Used when you have multiple conditions to check.

marks = 75

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

4. Nested if Statements

You can put an if statement inside another if.

age = 25
citizen = True

if age >= 18:
    if citizen:
        print("You can vote.")
    else:
        print("Only citizens can vote.")

📘 Syntax Summary

if condition:
    # code block
elif another_condition:
    # code block
else:
    # code block
  • Indentation (usually 4 spaces) is crucial.

  • Conditions use comparison (==, >, <, etc.) and logical (and, or, not) operators.


⚙️ Common Operators in Conditions

Type Operators Example
Comparison ==, !=, >, <, >=, <= x >= 18
Logical and, or, not x > 10 and x < 20
Membership in, not in 'a' in 'apple'
Identity is, is not x is None

🧪 Example with all conditions:

num = 7

if num % 2 == 0:
    print("Even")
elif num % 3 == 0:
    print("Divisible by 3")
else:
    print("Odd and not divisible by 3")

✅ Best Practices

  • Use meaningful variable names.

  • Keep conditions simple and readable.

  • Use parentheses () to group complex logical conditions.