Notes
Categories

Conditional Statements in Python [ English ]

< Prev Next >

1. Introduction

Conditional statements are used to control the flow of a program based on certain conditions. They allow the program to make decisions and execute different blocks of code depending on whether a condition is True or False.

2. if Statement

2.1 Definition

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

2.2 Syntax

if condition:
    # code block

2.3 Example

age = 18

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

Output

You are eligible to vote

2.4 Explanation

3. if-else Statement

3.1 Definition

The if-else statement provides an alternative block of code when the condition is False.

3.2 Syntax

if condition:
    # code if True
else:
    # code if False

3.3 Example

num = 5

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

Output

Odd number

3.4 Explanation

4. if-elif-else Statement

4.1 Definition

The if-elif-else statement is used when there are multiple conditions to check.

4.2 Syntax

if condition1:
    # code block 1
elif condition2:
    # code block 2
elif condition3:
    # code block 3
else:
    # default code

4.3 Example

marks = 75

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

Output

Grade B

4.4 Explanation

5. Nested if Statement

num = 10

if num > 0:
    if num % 2 == 0:
        print("Positive Even Number")

6. Important Points

7. Summary

< Prev Next >