Skip to main content

Welcome to a Grasp lesson

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

Lesson 2

Python Functions: Control Flow, Loops, and Comprehensions

Recommended resources

Hello! Welcome back to your AI course.

In our last lesson, we covered the fundamental ways Python stores data using its four core data structures: lists, tuples, sets, and dictionaries. You learned about their properties, such as mutability and order, and how to choose the right one for a given task.

Today, we move from storing data to processing it. This lesson will equip you with the essential tools for writing algorithms and performing computations. We'll cover how to:

  1. Write Functions: Package your code into reusable and logical blocks.
  2. Use Control Flow: Make decisions in your code with if, elif, and else statements.
  3. Implement Loops: Repeat tasks using for and while loops.
  4. Master List Comprehensions: Combine loops and conditionals for concise and elegant list creation.

These concepts are the verbs of the programming language, allowing you to bring the data structures we've learned to life. Given your computer science background, you are already familiar with these ideas in principle; our focus will be on Python's specific syntax and its idiomatic way of expressing them.

1. Writing Functions

A function is a reusable block of code that performs a specific task. Defining functions is crucial for organizing your code, making it more readable, testable, and avoiding repetition. In Python, you define a function using the def keyword.

Let's watch a video that provides a quick and clear introduction to the mechanics of functions, including how to define them, pass them data using arguments, and get results back using the return statement.

Functions in Python are easy 📞

The video 'Functions in Python are easy 📞' by Bro Code is a great starting point for understanding the basic syntax and concepts of Python functions.

Please watch the following segments: Function Definition (0:00 - 1:47): This part explains the basic def syntax and how to call a function. Arguments and Parameters (1:47 - 6:08): Focus on how to send data into a function. Note the distinction between arguments (the values you pass) and parameters (the variables that receive the values inside the function). The return Statement (6:08 - 10:14): This is key. Understand how return sends a value back from the function to the code that called it.

Key Concepts of a Python Function

Let's break down the structure of a function.

def calculate_area(width, height):
    """
    Calculates the area of a rectangle.
    
    Args:
        width (int or float): The width of the rectangle.
        height (int or float): The height of the rectangle.
        
    Returns:
        The area of the rectangle.
    """
    area = width * height
    return area

# Calling the function
rect_area = calculate_area(10, 5)
print(f"The area is: {rect_area}") # Output: The area is: 50
  • def keyword: Starts the function definition.
  • calculate_area: The name of the function.
  • (width, height): The parameters the function accepts.
  • Docstring: The triple-quoted string is a documentation string, or "docstring." It explains what the function does. It's a critical best practice for writing understandable code.
  • Function Body: The indented code block where the logic happens.
  • return area: The return statement exits the function and passes the value of area back to the caller. A function without an explicit return statement implicitly returns None.

For a more in-depth and formal look at functions, including advanced features like default arguments and keyword arguments, the official Python documentation is an excellent resource.

4. More Control Flow Tools — Python 3.14.3 documentation

The official Python documentation, 'More on Defining Functions', offers a comprehensive guide to function definitions, going beyond the basics.

Skim through section '4.9. More on Defining Functions'. You don't need to memorize everything, but pay attention to: 'Default Argument Values': How you can make function parameters optional. 'Keyword Arguments': How you can pass arguments by name, which improves code clarity. These are features you will use frequently.

Test your understanding!

Write a function called is_prime that takes an integer as input and returns True if the number is prime and False otherwise. A prime number is a number greater than 1 that has no positive divisors other than 1 and itself. (For this exercise, you can use a simple trial division method.)

Show answer
def is_prime(number):
    """Checks if a number is prime."""
    if number <= 1:
        return False
    # Check for factors from 2 up to the square root of the number
    # Your calculus background will tell you why checking up to sqrt(n) is sufficient!
    for i in range(2, int(number**0.5) + 1):
        if number % i == 0:
            return False
    return True

# Test cases
print(f"Is 7 prime? {is_prime(7)}")   # Expected: True
print(f"Is 10 prime? {is_prime(10)}") # Expected: False
print(f"Is 1 prime? {is_prime(1)}")   # Expected: False

2. Control Flow: if, elif, else

Control flow statements allow your program to execute different blocks of code based on certain conditions. In Python, this is primarily handled by if, elif (short for "else if"), and else.

A crucial aspect of Python syntax is the use of indentation to define code blocks. Unlike languages like C++ or Java that use curly braces {}, Python uses whitespace. This enforces a clean, readable style.

This video from Programming with Mosh provides a concise and clear explanation of control flow.

Control Flow in Python - If Elif Else Statements

This video, 'Control Flow in Python - If Elif Else Statements', clearly explains how to make decisions in your code.

Watch the following parts: Basic if statement (0:03 - 2:53): Understand the syntax and the role of indentation. elif and else (2:53 - 4:14): See how to chain multiple conditions. Logical Operators (6:15 - 10:29): Learn how to combine conditions using and, or, and not.

Here is a summary of the logic:

grade = 85

if grade >= 90:
    print("Excellent!")
elif grade >= 80:
    print("Good job.")
elif grade >= 60:
    print("You passed.")
else:
    print("You need to study more.")

# Output: Good job.

The conditions are checked in order. As soon as one is found to be True, its corresponding block is executed, and the rest of the if/elif/else structure is skipped.


3. Loops: for and while

Loops are used to execute a block of code repeatedly. Python has two main types of loops: for loops and while loops.

for Loops

In Python, for loops are best described as "for each" loops. They are designed to iterate over the items of any sequence, such as a list, a tuple, or a string. This is different from the counter-based for loops you may have seen in languages like C.

# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Iterating over a string
for letter in "Python":
    print(letter, end=" ") # prints P y t h o n

To loop a specific number of times, you can use the range() function.
range(n) generates numbers from 0 up to (but not including) n.

# Looping 5 times
for i in range(5):
    print(i) # prints 0, 1, 2, 3, 4

while Loops

A while loop repeats a block of code as long as a condition is True.

count = 0
while count < 5:
    print(f"Count is {count}")
    count += 1 # It's crucial to update the variable in the condition!

break and continue

You can control the flow of loops further:

  • break: Immediately exits the innermost loop.
  • continue: Skips the rest of the current iteration and proceeds to the next one.

The official documentation provides excellent, concise examples of these concepts.

4. More Control Flow Tools — Python 3.14.3 documentation

The Python documentation provides the definitive guide to loop structures.

Read the following sections: '4.2. for Statements': Understand how Python's for loop works with sequences. '4.3. The range() Function': This is the standard way to create loops that run a set number of times. '4.4. break and continue Statements': See the examples of how these statements alter loop behavior.

Test your understanding!

Using the is_prime function you wrote earlier, write a loop that finds and prints the first 5 prime numbers.

Show answer
def is_prime(number):
    if number <= 1:
        return False
    for i in range(2, int(number**0.5) + 1):
        if number % i == 0:
            return False
    return True

prime_count = 0
num = 2 # Start checking from the first prime number

print("First 5 prime numbers:")
while prime_count < 5:
    if is_prime(num):
        print(num)
        prime_count += 1
    num += 1

4. List Comprehensions

In the last lesson, we briefly introduced list comprehensions. Now that you understand for loops and if conditions, we can explore them more deeply. A list comprehension provides a concise and readable way to create lists. It often consists of a for loop and an optional if condition, all on one line.

Given your strong math background, you can think of a list comprehension as being very similar to set-builder notation.

Mathematical Notation:

Python List Comprehension:

squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares) # Output: [0, 4, 16, 36, 64]

Let's break down the syntax: [expression for item in iterable if condition]

Introduction to Python List Comprehensions
This image shows the basic structure of a list comprehension, comparing it to a standard for loop for clarity.

This infographic provides a more detailed breakdown.

Python List Comprehensions 101 Infographic
This infographic details the anatomy of a list comprehension, showing how it corresponds to the parts of a regular loop and providing examples of more complex uses.

List comprehensions are considered more "Pythonic" than creating an empty list and manually appending items in a loop. They are also generally faster because the looping is optimized in Python's C implementation.

Test your understanding!

You are given a list of sentences: sentences = ["This is a sample", "Another example here", "Short one"].
Use a list comprehension to create a new list containing the number of words in each sentence, but only for sentences that have more than 10 characters.

Show answer
sentences = ["This is a sample", "Another example here", "Short one"]

word_counts = [len(s.split()) for s in sentences if len(s) > 10]

print(word_counts) # Output: [4, 3]

Conclusion

Congratulations! You have now mastered the fundamental logic and control flow structures in Python. These are the tools that allow you to build complex algorithms and tell the computer exactly what to do with the data you've stored.

Key Takeaways:

  • Functions (def, return): Are essential for writing modular, reusable, and readable code.
  • Control Flow (if, elif, else): Allows your code to make decisions and follow different paths.
  • Loops (for, while): Enable your code to perform repetitive tasks, either over a sequence or until a condition is met.
  • List Comprehensions: Provide a powerful and Pythonic syntax for creating lists by combining loops and conditionals.

In the next lesson, we will take a significant step towards the world of AI and data science. You'll be introduced to NumPy, the fundamental package for scientific computing in Python. We will learn how to create and manipulate NumPy arrays, which are far more efficient for numerical operations than standard Python lists and form the basis of almost every machine learning and data science library.