Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 3

Conditional Statements and Loops in Python

Recommended resources

Hello! Welcome to the third lesson in our Python fundamentals module.

In the last lesson, you mastered the building blocks of Python: variables, data types, and operators. You learned how to store data and perform basic calculations and comparisons. These are the nouns and verbs of the Python language.

Today, we'll learn how to write the sentences and paragraphs. This lesson is about control flow—the ability to direct the execution of your code. You'll learn how to make your programs make decisions and repeat actions. This is where your code starts to become powerful, allowing you to automate complex tasks.

Specifically, we will cover two main types of control flow structures:

  1. Conditional Statements (if, elif, else): These allow your program to execute different blocks of code based on certain conditions. This is the decision-making part of programming.
  2. Loops (for, while): These allow you to execute a block of code repeatedly, which is the key to automation.

By the end of this lesson, you'll be able to write scripts that can filter data based on criteria and perform repetitive operations on data collections, two fundamental skills for any data analyst.

Let's start by visualizing these concepts.

Python Control Flow Flowcharts
These flowcharts illustrate the logic of conditional statements (right) and loops (left). On the right, a condition dictates which path the code takes. On the left, a condition determines whether a block of code is repeated.

1. Making Decisions with Conditional Statements

In data analysis, you constantly need to make decisions based on your data. For example: "If a customer's purchase total is over $100, apply a 10% discount," or "If a data point is missing, handle it in a specific way."

Python's if, elif (short for "else if"), and else statements are the tools for this. A condition is evaluated, and if it's True, the indented block of code under the statement is executed.

The following video provides an excellent, concise explanation of how these statements work.

Control Flow in Python - If Elif Else Statements

This video from Programming with Mosh clearly explains the syntax and logic of conditional statements in Python.

Please watch from the beginning until 04:14. Focus on: The structure of an if, elif, and else chain. The importance of the colon (:) and indentation. How Python executes these statements in order, running only the code for the first true condition it finds.

Key Points on Conditional Statements:

  • Syntax: Every if, elif, and else line ends with a colon :. The code to be executed is indented on the following lines. Proper indentation is mandatory in Python.
  • Flow: Python checks the if condition first. If it's true, it runs that block and skips the rest. If it's false, it moves to the first elif and checks its condition. This continues until a condition is met. The else block runs only if all preceding if and elif conditions were false.

Practice in Your Notebook

Let's write a simple script in your Jupyter Notebook to categorize a day's sales performance.

daily_sales = 1550

if daily_sales > 2000:
    print("Excellent sales day!")
elif daily_sales > 1200:
    print("Good sales day.")
else:
    print("This was a slow sales day.")




# Try changing the value of daily_sales to see how the output changes.

2. Creating Complex Conditions with Logical Operators

Often, a simple condition isn't enough. You might need to check if a customer is between 25 and 35 years old, or if they are a new customer or have a high purchase value. For this, you use the logical operators you briefly saw in the last lesson: and, or, and not.

Let's continue with the same video to see how to combine conditions.

Control Flow in Python - If Elif Else Statements

This segment explains how to build more complex logical expressions using and, or, and not.

Please watch from 06:15 to 10:29. Pay attention to how parentheses () can be used to group conditions for clarity, just like in mathematics.

Key Points on Logical Operators:

  • and: Both conditions must be True for the whole expression to be True.
  • or: At least one condition must be True for the whole expression to be True.
  • not: Reverses the boolean value ( not True becomes False).

Practice in Your Notebook

Let's expand our previous example. A "high-value" online order might be defined as an order over $100 from a non-member, or any order over $50 from a club member.

order_total = 120
is_member = False

if (order_total > 100 and not is_member) or (order_total > 50 and is_member):
    print("This is a high-value order.")
else:
    print("This is a standard order.")

Experiment with different values for order_total and is_member to see how the logic works.


3. Automating Repetition with for Loops

Loops are the cornerstone of automation in programming. Instead of writing the same code over and over again, you can write it once inside a loop and have it run multiple times.

The for loop is used when you want to iterate over a sequence of items, like a list of customer names or a range of numbers.

This next video provides a fantastic visual explanation of how loops work, starting with the for loop.

Python Loops (Visually Explained) | For, While, Break, Continue, Else

This video from Data with Baraa uses helpful sketches to explain the concept of loops. We'll start with the for loop, which is perfect for iterating through data.

Please watch from the beginning until 15:52. The video covers: The basic concept of loops. The syntax of a for loop. How to iterate through lists and strings. How to use the range() function to generate a sequence of numbers to loop through.

Key Points on for Loops:

  • A for loop iterates over an iterable (e.g., a list, a string, a range object).
  • In each iteration, the loop variable (e.g., item in for item in my_list:) takes on the value of the next element in the sequence.
  • The range(start, stop, step) function is extremely useful for looping a specific number of times or for creating number sequences. Remember that the stop value is not included in the sequence.

Practice in Your Notebook

Let's use a for loop to process a list of weekly expenses.




# A list of weekly expenses
expenses = [120.50, 85.00, 230.75, 55.20]
total_expense = 0.0




# Iterate through each expense in the list
for expense in expenses:
    print(f"Processing expense: {expense}")
    total_expense += expense # Add the current expense to the total

print(f"\nFinal total expense: {total_expense}")

4. Looping with Conditions: The while Loop

While a for loop is great when you have a known sequence to iterate over, sometimes you need to loop until a certain condition is no longer true. For this, you use a while loop.

A common example is a process that needs to keep trying until it succeeds, like connecting to a database. Or, it could be a simulation that runs until a target is met.

Let's return to our video guide for another clear, visual explanation.

Python Loops (Visually Explained) | For, While, Break, Continue, Else

This segment introduces the while loop, contrasting it with the for loop and explaining its condition-based nature.

Please watch from 01:16:33 to 01:24:51. Focus on the three essential parts of a while loop: Initialization: Setting up a variable before the loop starts. Condition: The boolean expression that is checked before each iteration. Update: Changing the variable inside the loop to eventually make the condition false.

A Word of Caution: If the condition in a while loop never becomes False, you will create an infinite loop, which will cause your program to hang. Always make sure there is a mechanism inside your loop to change the condition.

Python While Loop in Jupyter Notebook
This image shows a simple `while` loop in a Jupyter Notebook. Notice the initialization (`x = 0`), the condition (`while x < 5`), and the update (`x = x + 1`) that prevents an infinite loop.

5. Advanced Loop Control: break and continue

Sometimes you need more granular control over your loops. Python provides two statements for this:

  • break: Immediately terminates the entire loop.
  • continue: Immediately stops the current iteration and jumps to the beginning of the next one.

These are often used inside an if statement within a loop to handle special cases. For example, you might break out of a loop once you find the item you're searching for, or you might continue to skip over invalid data points.

Python Loops (Visually Explained) | For, While, Break, Continue, Else

This final video segment explains how to use break and continue to control the flow of your loops with more precision.

Please watch the segment from 23:21 to 34:44. It provides clear visual flowcharts for both break (stopping the loop) and continue (skipping an iteration).

Practice: Combining Loops and Conditionals

This is the most common pattern you'll use. Let's write a script that processes a list of transactions, but only sums the positive ones (credits) and stops if it encounters a large withdrawal (a potential security flag).

transactions = [500, 120, -300, 250, -50, -5000, 800]
account_balance = 1000

for transaction in transactions:
    if transaction < -1000:
        print(f"Stopping: Large withdrawal detected ({transaction}).")
        break  # Stop processing immediately

    if transaction < 0:
        print(f"Skipping withdrawal: {transaction}")
        continue  # Skip to the next transaction




    # If the code reaches here, the transaction is a credit
    print(f"Processing credit: {transaction}")
    account_balance += transaction

print(f"\nFinal account balance: {account_balance}")

Conclusion

Congratulations! You've taken a massive step forward in your programming journey. You can now write code that doesn't just run from top to bottom, but can make decisions and perform thousands of repetitive actions in seconds.

Key Takeaways:

  • Conditional Statements (if, elif, else) are used to execute code based on whether a condition is true or false.
  • for loops are used to iterate over a known sequence of items. This is your go-to loop for processing lists of data.
  • while loops are used to iterate as long as a condition is true. Be careful to ensure the condition will eventually become false.
  • break and continue give you fine-grained control to exit a loop or skip an iteration, which is very useful for handling exceptions and special cases in your data.

In our next lesson, we'll learn about functions. Functions allow you to bundle up the control flow logic you've learned today into reusable, named blocks of code. This is the key to writing clean, organized, and efficient programs for data analysis.