Lessons
Courses
Notes in current language not found. Defaulting to English.

Conditional Statements in Python [ English ]

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

  • If the condition is True, the code runs
  • If the condition is False, the code is skipped

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 Trueelse: # 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

  • If condition is True → if block runs
  • If condition is False → else block runs

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 1elif condition2: # code block 2elif condition3: # code block 3else: # 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

  • Conditions are checked one by one
  • The first True condition executes
  • Remaining conditions are skipped
  • If none are True → else block runs

5. Nested if Statement

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

6. Important Points

  • Conditions must return True or False
  • Indentation is mandatory in Python
  • Only one block executes in if-elif-else
  • else is optional

7. Summary

  • if → executes code if condition is True
  • if-else → provides two choices
  • if-elif-else → handles multiple conditions
  • Used for decision-making and control flow