đź§  Blog 3: Mastering Control Structures in Python

Alisha MalhotraAlisha Malhotra
6 min read

Introduction

Control structures are the decision-making backbone of any programming language. They allow your code to follow different paths, repeat tasks, and react dynamically based on user input or conditions.

In Python, control structures are broadly categorized into:

  • Selection Statements (Decision-making)

  • Iteration Statements (Loops)

  • Control Flow Modifiers (like break, continue, and pass)

Let’s explore them one by one with examples and flow explanations.


Selection Control Statements

1. if Statement

Syntax:

if condition:
    # block of code

Example:

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

Flow:

  • The condition is evaluated.

  • If True, the indented block runs.

  • If False, nothing happens.


2. if-else Statement

Syntax:

if condition:
    # block if true
else:
    # block if false

Example:

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

Flow:

  • Executes one block depending on the result of the condition.

3. if-elif-else Statement

Syntax:

if condition1:
    # block1
elif condition2:
    # block2
else:
    # default block

Example:

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

Flow:

  • Checks conditions top-down.

  • Executes the block of the first True condition.


4. Nested if Statements

Syntax:

if condition1:
    if condition2:
        # block

Example:

x = 10
if x > 0:
    if x < 100:
        print("x is between 1 and 99")

Flow:

  • Inner if runs only if outer if is True.

Looping Statements

Loops let you repeat actions without rewriting code.

Types of Loops:

  • Definite Loop: Known number of iterations (for)

  • Indefinite Loop: Unknown number, stops based on condition (while)


1. while Loop (Indefinite Loop)

Syntax:

while condition:
    # block of code

Example:

count = 1
while count <= 3:
    print("Hello")
    count += 1

Flow:

  • Evaluates condition.

  • Executes block as long as condition is True.


2. for Loop (Definite Loop)

Syntax:

for variable in iterable:
    # block

Example:

for i in range(3):
    print(i)

Flow:

  • Runs loop for each item in a sequence.

range() Function

Used to generate a sequence of numbers. This function is important as it is majorly used in for loops.

Syntax:

range(start, stop, step)

Example:

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

Output:

1
3
5

Control Statements

1. break Statement

  • Ends the current loop immediately.

Example:

for i in range(5):
    if i == 3:
        break
    print(i)

Output:

0  
1  
2

2. continue Statement

  • Skips current iteration, goes to next.

Example:

for i in range(5):
    if i == 2:
        continue
    print(i)

Output:

0  
1  
3  
4

3. pass Statement

  • Does nothing; placeholder.

Example:

for i in range(5):
    if i == 2:
        pass
    print(i)

Output:

0  
1  
2  
3  
4

Loop Patterns

1. Interactive Loops

  • Repeat based on user interaction/input.

Example:

while True:
    num = int(input("Enter number (-1 to quit): "))
    if num == -1:
        break
    print("You entered:", num)

2. Sentinel Loops

  • End based on a special "sentinel" value.

Example:

data = [5, 4, -1, 3]
i = 0
while data[i] != -1:
    print(data[i])
    i += 1

3. Nested Loops

  • A loop inside another loop.

Example:

for i in range(1, 4):
    for j in range(1, 3):
        print(f"i={i}, j={j}")

Summary: Unlocking the Power of Control in Python

In this blog, we journeyed through one of the most crucial parts of programming: control structures—the tools that make your code intelligent, flexible, and interactive. Here's a breakdown of each topic we covered, along with concise explanations:


🔹 Selection Control Statements (Decision-Making)

  • if Statement – Executes a block only when a given condition is true. It’s the most basic form of decision-making.

  • if-else Statement – Allows choosing between two paths: one if the condition is true, and another if it’s false.

  • if-elif-else Chain – Provides multiple conditions to check, one after the other, until a match is found or a default action is taken.

  • Nested if Statements – Enables one decision to depend on another, creating a hierarchy of conditions.


🔹 Looping Statements (Repetition)

  • while Loop – Repeats a block as long as a condition is true. Ideal for unknown or changing iteration counts.

  • for Loop – Iterates over sequences like lists, strings, or ranges, making it perfect for known counts.

  • range() Function – Generates a sequence of numbers, commonly used with for loops to define start, stop, and step values.


🔹 Control Statements (Flow Modifiers)

  • break – Immediately exits the closest enclosing loop, useful when a goal is reached early.

  • continue – Skips the current loop iteration and proceeds to the next, often used for skipping specific cases.

  • pass – Acts as a placeholder when a statement is syntactically required but no action is needed.


🔹 Loop Patterns (Common Looping Scenarios)

  • Interactive Loops – Continue running based on real-time user input; often used in menus or repeat-until-quit tasks.

  • Sentinel Loops – Run until a predefined sentinel (end marker) is detected in the data stream.

  • Nested Loops – One loop inside another, often used for grids, tables, or multi-dimensional data handling.


These control structures turn Python from a linear set of instructions into a decision-making, data-handling powerhouse. Whether you're designing simple quizzes or building complex applications, these tools are the foundation of flow and logic.


đź’­ My Experience

When I first encountered control structures in Python, I found most concepts like if-else and loops pretty straightforward—until I came across interactive and sentinel loops. They both seemed to serve the same purpose: repeat something until a condition is met. That overlap really confused me.

I remember writing a program to collect user input, and I couldn’t figure out whether it was an interactive loop or a sentinel loop, because I felt that sentinel value is also input of the user and I kept wondering: “Aren’t they just the same thing with a different name?”

But here’s what finally made it click for me:

  • Interactive loops rely on live input from the user during execution. The control is external—you wait for the user’s response.

  • Sentinel loops, on the other hand, depend on a predefined end value in a sequence of data. They don’t need user interaction after the initial setup.

Once I understood this difference, everything else made more sense. I realized that recognizing the pattern of a loop is just as important as writing its code.

Now, whenever I see a loop, I naturally ask: Is the stopping point determined by the user or a special value? That one habit improved the clarity and structure of my code significantly.

So, if you're stuck like I was, don’t worry—once you grasp the intent behind each loop type, choosing the right one becomes second nature.


What’s Next?

Let’s build on this knowledge by creating reusable functions in Python.

Try this:

def greet(name):
    print("Hello,", name)

greet("Alice")

Stay tuned for Blog 4: "Functions in Python – Write Once, Use Many Times!

0
Subscribe to my newsletter

Read articles from Alisha Malhotra directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Alisha Malhotra
Alisha Malhotra