Paramclasses Academy - Blog

Tutorials Details

CONDITIONAL STATEMENTS IN PYTHON

CONDITIONAL STATEMENTS IN PYTHON

October 16, 2026

CONDITIONAL STATEMENTS IN PYTHON

## 1. What Are Conditional Statements?

Conditional statements allow a Python program to make decisions based on whether a condition is True or False.

In simple words, conditional statements help a program decide what action to perform in different situations.

Example:
- If a student scores 40 or more, the student passes.
- If the temperature is high, turn on the AC.
- If the bank balance is sufficient, allow a withdrawal.

## 2. Why Do We Use Conditional Statements?

We use conditional statements to:

1. Make decisions in programs.
2. Execute different code for different situations.
3. Validate user input.
4. Check eligibility and permissions.
5. Build real-world applications such as login systems, billing systems, and result calculators.

## 3. Types of Conditional Statements

Python supports these main conditional structures:

1. if statement
2. if-else statement
3. if-elif-else statement
4. Nested if statement
5. Conditional expression (ternary operator)

---

## 4. The `if` Statement

### What Is It?

The `if` statement executes a block of code only when a condition is True.

### Syntax

if condition:
    statement

Important:
- A colon (`:`) is required after the condition.
- The code inside the block must be indented.
- Python commonly uses four spaces for indentation.

### Example

age = 20

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

### Output

You are eligible to vote.

### Explanation

The condition `age >= 18` is True because age is 20. Therefore, Python executes the print statement.

### Real-Time Example

A website checks whether a user is old enough to access an age-restricted service.

---

## 5. The `if-else` Statement

### What Is It?

The `if-else` statement executes one block when the condition is True and another block when it is False.

### Syntax

if condition:
    statement_if_true
else:
    statement_if_false

### Example

age = 16

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

### Output

You are a minor.

### Explanation

The condition `age >= 18` is False. Therefore, Python executes the `else` block.

### Real-Time Example: Pass or Fail

marks = 35

if marks >= 40:
    print("Result: Pass")
else:
    print("Result: Fail")

Output:

Result: Fail

---

## 6. The `if-elif-else` Statement

### What Is It?

The `if-elif-else` structure checks multiple conditions in sequence.

- `if` checks the first condition.
- `elif` means "else if" and checks another condition.
- `else` runs when none of the preceding conditions is True.

Python executes the first matching block and skips the remaining branches.

### Syntax

if condition1:
    statement1
elif condition2:
    statement2
elif condition3:
    statement3
else:
    default_statement

### Example: Grade Calculator

marks = 85

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

### Output

Grade B

### Explanation

- `marks >= 90` is False.
- `marks >= 75` is True.
- Python prints "Grade B" and skips the remaining branches.

### Real-Time Example

A school management system calculates grades based on a student's marks.

---

## 7. Nested `if` Statements

### What Are They?

A nested `if` statement is an `if` statement placed inside another `if` statement.

It is useful when a second condition should be checked only after the first condition is satisfied.

### Syntax

if condition1:
    if condition2:
        statement
    else:
        another_statement
else:
    outer_statement

### Example: Login Validation

username = "admin"
password = "python123"

if username == "admin":
    if password == "python123":
        print("Login successful")
    else:
        print("Incorrect password")
else:
    print("Username not found")

### Output

Login successful

### Explanation

First, Python checks the username. Since it matches, Python checks the password. Both conditions are True, so the login success message is displayed.

### Real-Time Example

A login system verifies the username first and then checks the password.

Note: This is a learning example. Real applications should store passwords securely and use proper authentication methods.

---

## 8. Conditional Expression (Ternary Operator)

### What Is It?

A conditional expression allows us to choose between two values in a single line.

### Syntax

value_if_true if condition else value_if_false

### Example

age = 20

message = "Adult" if age >= 18 else "Minor"

print(message)

### Output

Adult

### Another Example: Even or Odd

number = 7

result = "Even" if number % 2 == 0 else "Odd"

print(result)

### Output

Odd

### Real-Time Example

A shopping application displays "Free Delivery" or "Delivery Charges Apply" based on the order amount.

order_amount = 1200

delivery = "Free Delivery" if order_amount >= 1000 else "Delivery Charges Apply"

print(delivery)

Output:

Free Delivery

Use a conditional expression for simple choices. For complex logic, use regular `if-else` statements.

---

## 9. Comparison Operators in Conditions

Comparison operators compare values and return either True or False.

| Operator | Meaning | Example |
|----------|---------|---------|
| `==` | Equal to | `5 == 5` → True |
| `!=` | Not equal to | `5 != 3` → True |
| `>` | Greater than | `8 > 5` → True |
| `<` | Less than | `2 < 7` → True |
| `>=` | Greater than or equal to | `5 >= 5` → True |
| `<=` | Less than or equal to | `4 <= 6` → True |

### Example

a = 10
b = 20

if a < b:
    print("a is smaller than b")

Output:

a is smaller than b

Important:
- `=` assigns a value to a variable.
- `==` compares two values.

Example:

age = 18       # Assignment

if age == 18:  # Comparison
    print("Age is exactly 18")

---

## 10. Logical Operators in Conditions

Logical operators combine or reverse conditions.

### A. `and`

Returns True when both conditions are True.

age = 25
has_id = True

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

Output:

Entry allowed

### B. `or`

Returns True when at least one condition is True.

day = "Sunday"

if day == "Saturday" or day == "Sunday":
    print("It is the weekend")
else:
    print("It is a weekday")

Output:

It is the weekend

### C. `not`

Reverses a Boolean value.

is_raining = False

if not is_raining:
    print("You can go outside")

Output:

You can go outside

### Real-Time Example

An online shopping system may offer a discount if the customer is a premium member OR the order amount exceeds a specified threshold.

---

## 11. Checking Multiple Conditions Correctly

### Example: Age Eligibility

age = 22

if age >= 18 and age <= 60:
    print("Eligible")
else:
    print("Not eligible")

Output:

Eligible

Python also supports chained comparisons:

if 18 <= age <= 60:
    print("Eligible")

Both approaches check whether age is between 18 and 60, inclusive.

### Example: Validate a Number

number = 15

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

Output:

Positive number

---

## 12. Truthy and Falsy Values

Python conditions do not always need explicit comparison operators. Values themselves can be evaluated as True or False.

Common falsy values include:
- `False`
- `None`
- `0`
- `0.0`
- `""` (empty string)
- `[]` (empty list)
- `{}` (empty dictionary)
- `set()` (empty set)

Most other values are truthy.

### Example

name = ""

if name:
    print("Name is provided")
else:
    print("Name is empty")

Output:

Name is empty

### Real-Time Example: Checking User Input

username = input("Enter username: ")

if username:
    print("Username entered")
else:
    print("Username cannot be empty")

Note: This checks whether the string is empty. If the user types only spaces, the string is still truthy. Use `username.strip()` when you also want to reject whitespace-only input.

---

## 13. Common Mistakes in Conditional Statements

### Mistake 1: Missing Colon

Incorrect:

if age >= 18
    print("Adult")

Correct:

if age >= 18:
    print("Adult")

### Mistake 2: Incorrect Indentation

Incorrect:

if age >= 18:
print("Adult")

Correct:

if age >= 18:
    print("Adult")

### Mistake 3: Using `=` Instead of `==`

Incorrect:

if age = 18:
    print("Age is 18")

Correct:

if age == 18:
    print("Age is 18")

### Mistake 4: Incorrect Condition Order

Incorrect:

marks = 95

if marks >= 40:
    print("Pass")
elif marks >= 90:
    print("Excellent")

Output:

Pass

The second condition is never reached for marks of 95 because the first condition already matches.

Correct:

marks = 95

if marks >= 90:
    print("Excellent")
elif marks >= 40:
    print("Pass")
else:
    print("Fail")

Output:

Excellent

### Mistake 5: Using Separate `if` Statements When Only One Branch Is Needed

Example:

number = 5

if number > 0:
    print("Positive")
if number > 3:
    print("Greater than 3")

Output:

Positive
Greater than 3

Both conditions are checked independently. If only one branch should run, consider using `if-elif-else`.

---

## 14. Real-Time Project: ATM Withdrawal System

### Project Description

Create a simple program that:
1. Checks the account balance.
2. Accepts a withdrawal amount.
3. Rejects zero or negative amounts.
4. Checks whether sufficient balance is available.
5. Updates the balance when the withdrawal succeeds.

### Code

balance = 5000

amount = float(input("Enter withdrawal amount: "))

if amount <= 0:
    print("Please enter a valid amount.")
elif amount > balance:
    print("Insufficient balance.")
else:
    balance = balance - amount
    print("Withdrawal successful.")
    print(f"Remaining balance: ₹{balance:.2f}")

### Sample Input

Enter withdrawal amount: 1500

### Output

Withdrawal successful.
Remaining balance: ₹3500.00

### Explanation

- If the amount is zero or negative, the program rejects it.
- If the amount is greater than the balance, it displays an error.
- Otherwise, it subtracts the amount from the balance.

Note: This is a basic educational example. Real banking software needs secure authentication, transaction handling, and additional validations.

---

## 15. Real-Time Project: Electricity Bill Category

### Project Description

Create a program that categorizes electricity consumption.

For this example:
- Up to 100 units: Low consumption
- 101 to 300 units: Medium consumption
- More than 300 units: High consumption

### Code

units = int(input("Enter electricity units: "))

if units < 0:
    print("Invalid units")
elif units <= 100:
    print("Low consumption")
elif units <= 300:
    print("Medium consumption")
else:
    print("High consumption")

### Sample Input

Enter electricity units: 250

### Output

Medium consumption

Note: These categories are illustrative and are not an official electricity tariff.

---

## 16. Practice Exercises

Try solving these exercises without looking at the answers.

### Exercise 1: Positive, Negative, or Zero

Ask the user for a number and display whether it is positive, negative, or zero.

### Exercise 2: Even or Odd

Ask the user for an integer and check whether it is even or odd.

Hint: Use the modulus operator `%`.

### Exercise 3: Largest of Two Numbers

Ask the user for two numbers and display the larger one. Also handle the case where both numbers are equal.

### Exercise 4: Voting Eligibility

Ask the user for their age. Display "Eligible to vote" if the age is at least 18; otherwise display "Not eligible to vote".

### Exercise 5: Grade Calculator

Accept marks from 0 to 100 and display:
- 90–100: Grade A
- 75–89: Grade B
- 60–74: Grade C
- 40–59: Grade D
- Below 40: Fail

Reject marks outside the range of 0 to 100.

### Exercise 6: Login System

Ask the user to enter a username and password. Compare them with predefined learning-example values and display whether the login is successful.

### Exercise 7: Discount Calculator

Ask the user for the purchase amount:
- Amount of ₹5000 or more: 20% discount
- Amount of ₹2000 or more: 10% discount
- Otherwise: No discount

Display the discount amount and final payable amount. Reject negative purchase amounts.

---

## 17. Quick Quiz

### Q1. Which keyword checks another condition after `if`?

A. `otherwise`
B. `elif`
C. `then`
D. `check`

### Q2. What is the output?

x = 10

if x > 5:
    print("A")
else:
    print("B")

A. A
B. B
C. A and B
D. Error

### Q3. Which operator means "equal to"?

A. `=`
B. `==`
C. `!=`
D. `>=`

### Q4. What is the output?

x = 0

if x:
    print("True")
else:
    print("False")

A. True
B. False
C. 0
D. Error

### Q5. What does `and` require?

A. Both conditions must be True
B. At least one condition must be True
C. Both conditions must be False
D. Neither condition is checked

### Answers

1. B — `elif`
2. A — A
3. B — `==`
4. B — False
5. A — Both conditions must be True

---

## 18. Module 5 Summary

In this module, you learned:

- What conditional statements are and why they are useful.
- How to use `if`, `if-else`, and `if-elif-else`.
- How to write nested `if` statements.
- How to use conditional expressions.
- How comparison and logical operators work in conditions.
- How truthy and falsy values are evaluated.
- How to build basic real-world decision-making programs.
- How to avoid common syntax and logic errors.