Python for Loops: The Roller Coasters of Coding!

·

7 min read

In Python, a for loop is a control structure that allows you to iterate over elements in an iterable, which is a general term for any object capable of producing a sequence of values. I've covered the usage of for loops with lists in detail in my earlier blog post titled 'Data Types.' I plan to explore similar iterations with tuples and dictionaries in upcoming articles. The most common use of a for loop is to execute a block of code repeatedly for each item in the iterable.

Structure of For Loops

  • variable represents a temporary variable that takes on the value of each item in the iterable during each iteration of the loop. You can choose any valid variable name.

  • iterable is the object over which you want to iterate. It can be a string, tuple, range, dictionary, or any other iterable object.

  • The colon: at the end of the first line is crucial as it indicates the start of the loop block.

  • The code inside the indented block below the for statement is what will be executed for each item in the iterable.

Example 1

Type the below code to your code editor.

  1. name: str = "William Wilberforce": This line declares a variable named name with a type hint str to indicate that it's expected to store a string. It's then assigned the string value "William Wilberforce."

  2. for char in name:: This line initiates a for loop. It tells Python to iterate over each character in the name string. The variable char is a temporary variable that will take on the value of each character during each iteration.

  3. print(char): Inside the for loop, this line is responsible for printing the current character represented by the char variable. During each iteration of the loop, a character is printed.

When you run this code, it iterates over the characters in the name string "William Wilberforce" one by one, and for each character, it prints that character. The result is that it prints each character in the name on a new line:

Example 2

Please enter the following code, which defines a list containing the aliens from the Ben 10 series.

  1. ben_10_aliens: list = ["Heatblast", "Four Arms", "XLR8", "Diamondhead", "Upgrade"]: This line declares a variable named ben_10_aliens and explicitly specifies its type as a list using type hinting (list). It then assigns this variable a list containing the names of several Ben 10 aliens.

  2. for alien in ben_10_aliens: This line starts a for loop. It iterates over the elements in the ben_10_aliens list, and during each iteration, the alien variable takes on the value of the current element (in this case, each alien's name).

  3. print(alien): Inside the for loop, this line is responsible for printing the value of the alien variable during each iteration. It prints the name of each alien.

When you run this code, it iterates through the ben_10_aliens list, one alien at a time, and prints the name of each alien. The output is the list of Ben 10 aliens with each name printed on a separate line due to the print(alien) statement inside the for loop as shown below.

Example 3

Let's enhance the complexity of the code. Please input the following code into the text editor.

Some concepts need some explanation. If you look at the for loop, you will notice a certain word called range. That is an inbuilt function that is commonly used in for loops to generate a sequence of numbers. The range() function generates numbers starting from a specified start (by default, it starts at 0) up to, but not including, a specified end value.

In the line of code for i in range(num_items):, the range(num_items) generates a sequence of numbers starting from 0 and ending at num_items - 1.

Here's how it works:

  • If num_items is 5, for example, range(5) generates the numbers 0, 1, 2, 3, and 4.

  • If num_items is 10, range(10) generates the numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9.

This is a common convention in programming languages, where counting often starts from 0 (zero-based indexing). So, to iterate through num_items items in a sequence, the loop uses range(num_items), and i takes on the values from 0 to num_items - 1, effectively iterating through all the items in the sequence.

With that out of the way, let's explain the code.

  1. def create_list():: This line defines a Python function named create_list().

  2. num_items = int(input("Enter the number of items you want to add to the list: ")): This line prompts the user to enter the number of items they want to add to the list. The input() function takes user input as a string, and int() is used to convert it into an integer. The entered number is stored in the variable num_items.

  3. my_list = []: This line initializes an empty list named my_list that will store the items entered by the user.

  4. for i in range(num_items):: This line starts a for loop that will iterate num_items times. It uses the range() function to generate a sequence of numbers from 0 to num_items-1, which represents each iteration.

  5. item = input(f"Enter item {i + 1}: "): Inside the loop, this line prompts the user to enter an item for the list. The f-string is used to include the iteration number (i + 1) in the prompt to make it clear which item is being entered. The entered item is stored in the item variable. Let's explain the input(f"Enter item {i + 1}:") more clearly:

    . input(...): This function is used to take user input from the keyboard. Whatever the user types is treated as a string.

    . f"Enter item {i + 1}:": This is an f-string, which is a feature in Python that allows you to embed expressions within string literals.

    . "Enter item ": This is a string literal that provides a prompt to the user, asking them to enter an item.

    . {i + 1}: Inside the f-string, {} is used to enclose an expression. Here, i + 1 is the expression.

    . i is the loop variable, representing the current iteration of the loop. It starts at 0 for the first iteration.

    . i + 1 is used to adjust the iteration count to make it more user-friendly. Since many people count items starting from 1 (not 0), adding 1 to i ensures that the prompt displays "Enter item 1:" for the first iteration, "Enter item 2:" for the second iteration, and so on.

  6. my_list.append(item): This line adds the user-entered item to the my_list using the append() method. This step accumulates the items in the list during each iteration of the loop.

  7. After all the iterations are complete, the function create_list() returns the populated list my_list.

  8. my_created_list = create_list(): This line calls the create_list() function and stores the returned list in the my_created_list variable.

  9. print("The created list is:", my_created_list): Finally, this line prints the content of the my_created_list to display the list of items entered by the user.

  10. Run the program and let's assume the user types the number 5. After the user enters the number 5 as the number of items they want to add to the list and provides the items "Banana," "Orange," "Watermelon," "Mango," and "Pineapple," the program executes the following line of code: print("The created list is:", my_created_list)

  11. This line prints the content of the my_created_list variable, displaying the list of items entered by the user. In this specific example, the user's input results in the following output:

That concludes our discussion on for loops. It became evident that example 3 needed more explanation than initially thought. Consequently, I focused on breaking down the code into manageable parts, especially the for loop. It's worth mentioning that previous articles have covered Python functions and lists in depth.

Moving forward, our exploration of Python programming will shift to more advanced topics, including dictionaries and tuples. In the upcoming article, we'll be focusing on Python tuples. Stay tuned for an interesting discussion!