Conditional Statements (Decision Making)

Python tutorial · PySpark.in

Control Flow Statements

Control Flow Statements are Python instructions that decide the order in which code is executed based on conditions, loops, and program logic. They allow your program to make decisions, repeat actions, or skip code blocks depending on specific conditions.

Conditional Statements (Decision Making)

if Statement

Executes a block of code if the condition is true.

PYTHON
1age = 18
2if age >= 18:
3 print("You are eligible to vote.")
▶ Output will appear here.

if...else Statement

Provides an alternative path if the condition is false.

PYTHON
1age = 16
2if age >= 18:
3 print("You can vote.")
4else:
5 print("You are not eligible to vote.")
▶ Output will appear here.

if...elif...else Statement

Used when you have multiple conditions to check.

PYTHON
1marks = 75
2if marks >= 90:
3 print("Grade A")
4elif marks >= 70:
5 print("Grade B")
6else:
7 print("Grade C")
▶ Output will appear here.

Nested if

You can place one if inside another.

PYTHON
1num = 10
2if num > 0:
3 if num % 2 == 0:
4 print("Positive Even Number")
▶ Output will appear here.

Short-Hand If…Else in Python (Ternary Expression)

In Python, you can write an if…else statement in a single line.This is called a short-hand if…else or ternary operator.It’s a compact way to perform conditional assignments or print statements.

Syntax

PLAINTEXT
1 if else
▶ Output will appear here.

Example

PYTHON
1age = 20
2print("Adult") if age >= 18 else print("Minor")
▶ Output will appear here.

Example: Assigning a Value Conditionally

PYTHON
1marks = 75
2result = "Pass" if marks >= 50 else "Fail"
3print(result)
▶ Output will appear here.

Use Case: Perfect for short, simple conditions where you don’t need multiple lines of code.

Multiple Levels of Nesting

Python allows nested if statements, meaning you can place one if statement inside another.
This is useful when multiple conditions must be met to execute a block of code.

Example

PYTHON
1marks = 80
2attendance = 85
3homework_done = True
4if marks >= 60:
5 if attendance >= 75:
6 if homework_done:
7 print("Pass with distinction")
8 else:
9 print("Pass but incomplete work")
10 else:
11 print("Pass but poor attendance")
12else:
13 print("Fail")
▶ Output will appear here.

Tip

If nesting becomes too deep, your code can get hard to read.In such cases, you can simplify it using logical operators (and, or):

PYTHON
1if marks >= 60 and attendance >= 75 and homework_done:
2 print("Pass with distinction")
▶ Output will appear here.

More Python tutorials

All tutorials · Try the free PySpark compiler · Practice challenges