Python Control Statements

Control statements regulate the flow of execution in a Python program. They determine how and when certain blocks of code execute.


๐Ÿ”น Types of Control Statements in Python

Python has three main types of control statements:

  1. Conditional Statements (if, if-else, if-elif-else) โ†’ Decision making
  2. Looping Statements (for, while) โ†’ Repetition
  3. Jump Statements (break, continue, pass) โ†’ Control flow modification

1๏ธโƒฃ Conditional Statements (Decision Making)

Conditional statements allow Python to execute a block of code only if a condition is met.

โœ… if Statement

Executes a block only if the condition is True.

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

Output:

You are eligible to vote.

โœ… if-else Statement

Executes one block if the condition is True, otherwise executes another block.

age = 16
if age >= 18:
    print("You can vote.")
else:
    print("You cannot vote.")

Output:

You cannot vote.

โœ… if-elif-else Statement

Used when there are multiple conditions to check.

marks = 85

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

Output:

Grade: B

2๏ธโƒฃ Looping Statements (Iteration)

Loops are used to execute a block of code multiple times.

โœ… for Loop (Definite Iteration)

Loops over an iterable (like a list, string, or range).

for i in range(1, 6):
    print(i)

Output:

1
2
3
4
5

โœ… while Loop (Indefinite Iteration)

Executes a block as long as a condition is True.

count = 1
while count <= 5:
    print(count)
    count += 1

Output:

1
2
3
4
5

3๏ธโƒฃ Jump Statements (Control Flow Modification)

Jump statements allow modification of normal flow inside loops.

โœ… break Statement

Stops the loop immediately.

for i in range(1, 6):
    if i == 3:
        break  # Stops the loop at 3
    print(i)

Output:

1
2

โœ… continue Statement

Skips the current iteration and continues to the next.

for i in range(1, 6):
    if i == 3:
        continue  # Skips 3
    print(i)

Output:

1
2
4
5

โœ… pass Statement

A placeholder statement that does nothing (useful for defining empty functions or loops).

for i in range(5):
    pass  # Does nothing but avoids an error

๐Ÿ”น Summary Table of Control Statements

Statement Purpose
if Executes code if the condition is True
if-else Executes one block if True, another if False
if-elif-else Checks multiple conditions
for loop Iterates over a sequence
while loop Loops while a condition is True
break Stops the loop immediately
continue Skips the current iteration
pass Does nothing, acts as a placeholder

Would you like real-world examples using these concepts? ๐Ÿš€


Leave a Reply

Your email address will not be published. Required fields are marked *