Skip to content

Latest commit

 

History

History
206 lines (136 loc) · 2.59 KB

File metadata and controls

206 lines (136 loc) · 2.59 KB

Conditional Statements in Python

(if, if-else, if-elif-else)


1. Introduction

In programming, we often need to make decisions.

Examples:

  • If marks are greater than 40 → Pass
  • If age is greater than 18 → Eligible
  • If number is even → Print “Even”

To handle such situations, we use conditional statements.

Conditional statements allow the program to execute code based on conditions.


2. The if Statement

The if statement checks a condition. If the condition is True, the block of code runs.

Syntax:

if condition:
    statement

Example:

age = 20

if age > 18:
    print("Eligible to vote")

If the condition is false, nothing happens.


3. Indentation (Very Important)

Python uses indentation (spaces) to define blocks.

Correct:

if 5 > 3:
    print("Correct")

Wrong:

if 5 > 3:
print("Correct")   # Error

Always use proper indentation.


4. The if-else Statement

If the condition is True → first block runs If False → else block runs

Syntax:

if condition:
    statement
else:
    statement

Example:

num = 7

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

5. The if-elif-else Statement

Used when there are multiple conditions.

Syntax:

if condition1:
    statement
elif condition2:
    statement
else:
    statement

Example:

marks = 75

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

Python checks conditions from top to bottom.


6. Nested if

An if statement inside another if statement.

Example:

age = 22
citizen = True

if age > 18:
    if citizen:
        print("Eligible to vote")

7. Using Logical Operators in Conditions

You can combine conditions using:

  • and
  • or
  • not

Example:

age = 20
has_id = True

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

8. Common Beginner Mistakes

  1. Using = instead of ==
if age = 18:   # Wrong

Correct:

if age == 18:
  1. Wrong indentation

  2. Forgetting colon : after condition


9. Practice Exercises

  1. Take a number and check if it is positive or negative
  2. Take marks and print grade
  3. Check if a number is divisible by 5
  4. Take age and check if eligible to vote

Example:

num = int(input("Enter number: "))

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