Python Basics October 23 ,2025

 

Control Flow in Python

In Python, control flow is about deciding the path your program takes. When a program runs, Python executes instructions line by line, from top to bottom. But real-world programs are rarely linear. Often, you need to make decisions, repeat actions, or skip certain steps depending on the data your program is processing. This is where Python’s control flow constructs come into play. By mastering these constructs, you can write programs that react dynamically to input, handle repeated tasks efficiently, and execute complex logic without confusion.

Making Decisions with if, elif, and else

In Python, decision-making is one of the most important features of control flow. Programs rarely execute in a straight line; they often need to perform different actions based on conditions. Conditional statements allow you to control the path your program takes depending on the truth value of certain expressions.

1. The if statement

The if statement evaluates a Boolean expression — that is, an expression that results in either True or False. If the expression evaluates to True, the block of code indented under the if executes. Otherwise, Python skips that block entirely.

Example:

temperature = 35

if temperature > 30:
    print("It's a hot day.")

Here, Python checks whether temperature > 30. Since 35 > 30 is True, the print statement runs. If temperature were 25, Python would skip the print statement entirely.

Why indentation matters: Unlike some languages that use curly braces {}, Python uses indentation to define blocks. The number of spaces (usually 4) must be consistent within the block; otherwise, Python will raise an IndentationError.

2. The if-else statement

Sometimes, you want your program to take one action if a condition is true and another if it’s false. This is where else comes in:

temperature = 25

if temperature > 30:
    print("It's a hot day.")
else:
    print("It's a pleasant day.")

Here, since temperature > 30 is False, Python skips the if block and executes the else block instead.

Key point: else does not require a condition; it’s executed automatically if all previous conditions were False. This ensures that your program always has a defined path, preventing unexpected behavior.

3. The elif statement

Sometimes multiple conditions must be checked sequentially. The elif (short for “else if”) allows you to test additional conditions after the initial if:

score = 82

if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "D"

print(f"Your grade is {grade}")
  • Python evaluates each condition in order.
  • The first True condition executes, and all remaining elif statements are skipped.
  • If none of the conditions are True, the else block runs.

Why use elif instead of nested if? Using elif keeps code flat and readable, reducing unnecessary indentation. Deep nesting makes code harder to understand and maintain.

4. Boolean evaluation in Python

Python has a unique feature: any expression can be evaluated as a Boolean. This is called truthy and falsy evaluation. Examples:

  • Falsy values (treated as False):
    • 0 (integer zero)
    • 0.0 (float zero)
    • "" (empty string)
    • [] (empty list)
    • {} (empty dictionary)
    • None
  • Truthy values (treated as True):
    • Any non-zero number
    • Non-empty strings or sequences
    • Non-empty collections
    • Any object that is not explicitly None or False

Example:

items = []

if items:
    print("Processing items...")
else:
    print("No items to process.")

Here, items is an empty list. Python automatically evaluates if items: as False because empty lists are falsy, so the else block runs.

This allows Python programmers to write concise and readable conditions without explicitly comparing values to True or False.

# Less Pythonic
if len(items) > 0:
    print("Processing items...")

# More Pythonic
if items:
    print("Processing items...")

5. Nested conditions

You can place if statements inside other if statements. This is useful when a decision depends on multiple layers of conditions:

temperature = 28
humidity = 80

if temperature > 25:
    if humidity > 70:
        print("It's hot and humid today.")
    else:
        print("It's hot but dry today.")
else:
    print("The temperature is comfortable.")

Here, Python first checks the temperature. Only if it’s above 25 does it check humidity. Nested conditions are powerful but should be used carefully, as too much nesting can reduce readability.

6. Common pitfalls

  1. Incorrect indentation: Python relies on indentation to define blocks. Mixing spaces and tabs or inconsistent indentation will raise errors.
  2. Using = instead of ==: In conditions, you must use == to test equality. Using a single = is assignment, not comparison.
  3. Over-nesting: Excessive nested if statements can make code hard to read. Combine conditions using and/or whenever possible.
  4. Misunderstanding truthy/falsy values: Remember that 0, empty sequences, and None are False.

7. Best practices

  • Use elif instead of multiple nested if statements.
  • Leverage Python’s truthy/falsy evaluation for cleaner conditions.
  • Keep conditions simple and readable. If a condition becomes complex, consider assigning it to a descriptive variable.

Example:

temperature = 32
humidity = 85

is_hot = temperature > 30
is_humid = humidity > 70

if is_hot and is_humid:
    print("Hot and humid today.")

Nested Conditionals and Logical Operators

In programming, decisions are often based on multiple factors. Python allows you to nest if statements inside other if statements, meaning a condition can depend on the result of another condition. While this is powerful, deep nesting can quickly make your code hard to read and maintain. Python offers a more elegant solution: logical operators — and, or, and not — which allow combining multiple conditions in a single statement.

1. Nested Conditionals

A nested conditional occurs when one if statement is placed inside another. This is useful when you need to make a decision that depends on another condition being true first.

Example:

temperature = 30
humidity = 80

if temperature > 25:
    if humidity > 70:
        print("It's hot and humid today.")
    else:
        print("It's hot but dry today.")
else:
    print("The temperature is comfortable.")

Explanation:

  • Python first checks if temperature > 25.
  • Only if that is true does it evaluate the inner if humidity > 70.
  • If temperature <= 25, Python skips the inner condition entirely and executes the outer else.

Nested conditionals give precise control but can quickly become verbose if many conditions are involved. For example, handling multiple weather factors with deep nesting would be hard to read.

2. Using Logical Operators

Logical operators allow combining multiple conditions in a single if statement, reducing nesting and improving readability.

Python supports three main logical operators:

  1. and – True if both conditions are true
  2. or – True if at least one condition is true
  3. not – Reverses the Boolean value of a condition

Example using and:

age = 20
citizen = True

if age >= 18 and citizen:
    print("Eligible to vote")

Here:

  • age >= 18 evaluates to True
  • citizen is True
  • and ensures both must be True for the block to execute.

This is equivalent to a nested conditional:

if age >= 18:
    if citizen:
        print("Eligible to vote")

But using and is shorter, cleaner, and more readable.

Example using or:

day = "Saturday"

if day == "Saturday" or day == "Sunday":
    print("It's a weekend!")
  • The block executes if either condition is true.
  • This avoids writing nested if statements for multiple possibilities.

Example using not:

is_raining = False

if not is_raining:
    print("Let's go for a walk!")
  • not reverses the Boolean value. Since is_raining is False, not is_raining is True.
  • This allows you to write conditions in a more natural, readable way.

3. Combining Multiple Logical Operators

You can combine and, or, and not in a single condition, but operator precedence matters:

  • not has the highest precedence
  • and comes next
  • or has the lowest precedence

Example:

age = 20
citizen = True
has_permit = False

if age >= 18 and (citizen or has_permit):
    print("Eligible to vote or with special permission")
  • Parentheses are used to explicitly control evaluation order.
  • Without parentheses, and binds more tightly than or. Always use parentheses if the logic is complex.

4. Practical Examples

Example 1 – Eligibility check:

age = 22
citizen = True
has_criminal_record = False

if age >= 18 and citizen and not has_criminal_record:
    print("Eligible to vote")
else:
    print("Not eligible to vote")
  • Combines three conditions.
  • Avoids deep nested if statements.
  • Easy to read and maintain.

Example 2 – Access control:

role = "admin"
active = True

if role == "admin" or (role == "moderator" and active):
    print("Access granted")
else:
    print("Access denied")
  • Checks if the user is an admin or an active moderator.
  • Combines and and or to express complex business rules clearly.

5. Best Practices

  1. Prefer logical operators over deep nesting whenever possible.
  2. Use parentheses for complex conditions to make the logic explicit.
  3. Break complex conditions into variables with meaningful names for readability:
is_adult = age >= 18
is_citizen = citizen
no_criminal_record = not has_criminal_record

if is_adult and is_citizen and no_criminal_record:
    print("Eligible to vote")
  1. Avoid overcomplicating a single if. If a condition becomes too long, consider splitting it or using functions.

 

Best Practices in Control Flow

  1. Keep conditions simple and readable. Use logical operators rather than deeply nested if statements.
  2. Avoid unnecessary loops. Use Python’s built-in functions and comprehensions whenever possible.
  3. Use break and continue sparingly. Overuse can make loops harder to understand.
  4. Always ensure while loops terminate. Infinite loops are a common beginner mistake.
  5. Write clear else clauses. Python’s loop-else is powerful but often underutilized.

Conclusion

Control flow constructs form the decision-making and repetition backbone of Python programs. Understanding how to use if, for, while, and the associated control statements effectively allows you to build programs that can adapt to varying data, process tasks iteratively, and manage complex logic elegantly. By combining these constructs with Python’s idiomatic practices, your code becomes not just functional but also readable, maintainable, and robust.

 

Next Blog- Python Data Structures    

 

 

Sanjiv
0

You must logged in to post comments.

Get In Touch

G06, Kristal Olivine Bellandur near Bangalore Central Mall, Bangalore Karnataka, 560103

+91-8076082435

techiefreak87@gmail.com