Python Loops and Ranges

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to use for loop statements and the range() function in Python. For loop statements allow you to iterate over a sequence of elements, such as a list or a string. The range() function is a built-in function that returns a sequence of numbers, starting from 0 by default, increments by 1 (also by default), and ends at a specified number.

Achievements

  • For loop Statements
  • The range() function
  • The enumerate() function
  • The zip() function

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/sets("`Sets`") python/PythonStandardLibraryGroup -.-> python/data_collections("`Data Collections`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-78{{"`Python Loops and Ranges`"}} python/variables_data_types -.-> lab-78{{"`Python Loops and Ranges`"}} python/for_loops -.-> lab-78{{"`Python Loops and Ranges`"}} python/lists -.-> lab-78{{"`Python Loops and Ranges`"}} python/tuples -.-> lab-78{{"`Python Loops and Ranges`"}} python/sets -.-> lab-78{{"`Python Loops and Ranges`"}} python/data_collections -.-> lab-78{{"`Python Loops and Ranges`"}} python/build_in_functions -.-> lab-78{{"`Python Loops and Ranges`"}} end

for Loop

A for loop is a control flow statement that allows you to iterate over a sequence of elements. The syntax for a for loop is as follows:

for variable in sequence:
    statements

Where sequence is a sequence of elements (such as a list, tuple, or string) and variable is a variable that takes on each value in the sequence one at a time. The statements inside the loop will be executed for each value in the sequence.

Open up a new Python interpreter.

python3

Here is an example of a simple for loop that iterates over a list of integers and prints out each value:

numbers = [1, 2, 3, 4, 5]
for number in numbers:
    print(number)

Iterating over a string:

for char in 'Hello':
    print(char)

the Range() Function

The range() function is a built-in function in Python that returns a sequence of numbers. The syntax for the range() function is as follows:

range(start, stop, step)

Where start is the starting number of the sequence (default is 0), stop is the ending number of the sequence (not included), and step is the increment between each number in the sequence (default is 1).

You can use the range() function in a for loop to iterate over a sequence of numbers. For example:

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

You can also specify a start and stop value for the range() function:

for i in range(2, 5):
    print(i)

You can even specify a step value:

for i in range(2, 10, 2):
    print(i)

Nested for Loops

You can also use multiple for loops to iterate over nested sequences. For example:

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

Exercise

Now it's your turn to practice using for loop statements and the range() function. Write a program that prints the following pattern:

*
**
***
****
*****

Some hints:

Your program should use two for loops, one nested inside the other. The outer loop should iterate over the number of rows, and the inner loop should iterate over the number of columns.

To complete this exercise, you will need to use the print() function to print out the asterisks. You can use the range() function to control the number of iterations for the loops.

the Enumerate() Function

The enumerate function takes an iterable as an input, such as a list, and returns an iterator that generates tuples containing the index and the value of each element. In the example below, we use the unpacking operator (index, fruit) to assign the index and value of each tuple to the variables index and fruit, respectively.

## Example of using the enumerate function in a for loop in Python

## Sample list to iterate over
fruits = ['apple', 'banana', 'cherry']

## Using a for loop and the enumerate function to iterate over the list
for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Fruit: {fruit}")

## Output:
## Index: 0, Fruit: apple
## Index: 1, Fruit: banana
## Index: 2, Fruit: cherry

In the above example, we define a list fruits containing the elements apple, banana, and cherry.

Then, we use a for loop to iterate over the list of fruits and the enumerate function to get both the index and value of each element in the list. Inside the loop, we use string formatting to print out the index and the fruit. The enumerate function by default starts counting from 0 but you can use the optional argument start to specify a different starting point for counting.

the Zip() Function

The zip() function can be useful when working with multiple lists or other iterable objects and you want to iterate over their elements in pairs, or when you want to combine multiple iterable objects into one.

## Example of using the zip() function in a for loop in Python

## Sample lists to iterate over
fruits = ['apple', 'banana', 'cherry']
prices = [1.2, 3.5, 2.5]

## Using a for loop and the zip function to iterate over the lists
for fruit, price in zip(fruits, prices):
    print(f"Fruit: {fruit}, Price: ${price}")

## Output:
## Fruit: apple, Price: $1.2
## Fruit: banana, Price: $3.5
## Fruit: cherry, Price: $2.5

In the above example, we define two lists fruits and prices containing the elements apple, banana, cherry and 1.2, 3.5, 2.5 respectively.

Then, we use a for loop to iterate over the elements from the two lists using the zip() function. The zip() function takes multiple iterable objects as input and returns an iterator that generates tuples containing the elements of the input iterables at corresponding positions. In the example above, we use the unpacking operator (fruit, price) to assign the elements of each tuple to the variables fruit and price, respectively. Inside the loop, we use string formatting to print out the Fruit and the price.

If the length of the input iterable is not equal, the zip() function will stop at the end of the shortest iterable.

Summary

In this lab, you learned how to use Python's for loop statements and the range() function to iterate over a sequence of elements. You learned the syntax for for loops and the range() function, and saw examples of using them to iterate over lists, strings, tuples, and sequences of numbers. You also learned how to use nested for loops to iterate over nested sequences.

Now that you have learned the basics of for loops and the range() function, you can use these tools to perform tasks such as processing data, generating outputs, and more.

Other Python Tutorials you may like