sec03 - Python For Loop Tutorial: Basics and Usage for Beginners
スポンサーリンク

Basic Syntax and Usage of Python's for Loop

Why for Loops Are Necessary

When you want to repeat the same operation multiple times, using a for loop allows you to write code more concisely. The main advantage of a for loop is that it can "automate" repetitive tasks.

In the following code, the total price of items is being calculated. From the dictionary that defines products and their prices, each price is manually added to the variable total_price line by line. With only three items, this is manageable, but with 100 items, you would need to write 100 lines. This is inefficient and becomes very cumbersome when modifications or additions are required.

# Product data (product name: price in yen)
items = {'Apple Juice': 120, 'Pancake': 350, 'Coffee': 250}
# Initialize variable to store total price
total_price = 0

# Manual addition without for loop
# If the number of products increases to 100, you would need 100 lines
total_price += items['Apple Juice']
total_price += items['Pancake']
total_price += items['Coffee']

print(f'Total price is {total_price} yen.')  # Total price is 720 yen.

By using a for loop, you can handle any number of items with a single loop structure, as shown in lines 7 and 9 below. The code becomes shorter and more extensible, which is a major advantage. However, if the for loop is used incorrectly, it may repeat an unintended number of times, so understanding the syntax is important.

# Product data (product name: price in yen)
items = {'Apple Juice': 120, 'Pancake': 350, 'Coffee': 250}
# Initialize variable to store total price
total_price = 0

# When using a dict, iterating with a for loop retrieves keys (product names) in order
for item_name in items:
    # Even if there are 100 or more items, this single line handles them (adds the item's price to total_price)
    total_price += items[item_name]

print(f'Total price is {total_price} yen.')  # Total price is 720 yen.

Basic Syntax of the for Loop

for variable in iterable:
    operation
  • for: keyword to start the loop.
  • variable: variable that receives one value (element) from the iterable at each iteration. Its value updates with each loop.
  • in: keyword that instructs Python to retrieve elements sequentially from a data structure (like a list or string). Used together as for ~ in.
  • iterable: the target that can be looped over with a for loop. This includes anything that can contain multiple elements or return values sequentially.
    • list or dict, structures that can hold multiple values.
    • String is also an iterable because it holds multiple characters.
    • range() is used for looping a specific number of times, returning consecutive integers based on the arguments.
  • :: a colon is required at the end of the line.
  • operation: commands executed in each iteration. Indentation (usually four spaces) indicates the block scope.

In short, the flow is: "Take each element from the iterable, assign it to variable, and execute operation each time."

for Loops in Other Languages

Some programming languages define for loops like this:

for (i=0; i < 10; i++) {
    // loop operation
}

Python does not support this style of for loop.

Instead, Python provides:

A way to iterate over the number of elements in a data structure,

for var in list:

or a way to repeat a specific number of times using range(),

for var in range(5):

and nothing else.

Once accustomed, Python's syntax reduces code writing effort while maintaining readability.

Simple Example of a for Loop

To understand how a for loop works, let's retrieve and print each element in a list one by one.

fruits = ['apple', 'banana', 'cherry']

for fruit in fruits:
    print(fruit)
# Output
apple
banana
cherry
  • The variable fruits is a list, which is an iterable.
  • The list contains three strings: 'apple', 'banana', 'cherry'.
  • for fruit in fruits: means "take each element from fruits and assign it to fruit, then repeat the operation."
  • Initially, fruit = 'apple', then 'banana', and finally 'cherry'; the value is assigned to fruit each time.
  • print(fruit) outputs each element as it is retrieved.

The advantage of this method is that it works with any number of elements. The limitation is that the same operation is applied to all elements, so conditional logic must be added with if statements if needed.

Indentation (usually four spaces) is mandatory. In Python, indentation defines the block scope, and omitting it will cause an error.

Calculating the Sum of Elements with a for Loop

Using a for loop, as shown at the beginning of this lecture, you can calculate the sum of elements. This approach is more concise and manageable than adding each element manually, especially as the data grows.

Here, we use a list in the sample code.

numbers = [10, 20, 30, 40, 50]
total = 0

for number in numbers:
    total += number

print(f'Sum: {total}')  # Sum: 150

In this code, the variable numbers contains 5 numerical values. The variable total is initialized to 0. Using a for loop, each element of the variable numbers is retrieved one by one and added to total using total += number. The value of the variable total is 10(0+10) in the first loop iteration, 30(10+20) in the second... ultimately reaching 150.

Without a for loop, you would need to write all additions manually:

total += numbers[0]
total += numbers[1]
total += numbers[2]
total += numbers[3]
total += numbers[4]

For loops make the code more efficient and readable, especially with larger data sets.

Python also provides the sum() function, which achieves the same result in one line. Passing a list as an argument returns the sum of all elements. For simple addition, sum() is fine, but using a for loop allows more flexible control, such as conditional operations. For example, summing only positive numbers or raising an error if an abnormal value is encountered requires using a for loop to manage the logic.

スポンサーリンク

Conditional Processing with for and if

By combining a for loop with an if statement, you can process only elements that meet certain conditions. The following example adds only even numbers to a new list.

numbers = [10, 15, 20, 25, 30]
evens = []

for number in numbers:
    if number % 2 == 0:
        evens.append(number)

print(f'Even numbers: {evens}')  # Even numbers: [10, 20, 30]

if number % 2 == 0 means "if the remainder when divided by 2 is 0, it is even." Only when the condition is met is evens.append(number) executed, adding the number to evens.

Combining for and if allows flexible operations, such as selecting only elements that meet a condition or counting only specific values.

Repeating a Specific Number of Times with range()

For loops can also repeat a task a specific number of times, not just iterate over lists or dicts. The range() function is useful in these cases.

for i in range(5):
    print(i)
# Output
0
1
2
3
4
  • range() generates integers starting from 0 up to one less than the specified argument.
    • For range(5), integers 0 through 4 are generated in order.
  • The variable i receives 0 → 1 → 2 → 3 → 4 sequentially.
  • print(i) outputs each number.

Details of range() usage will be covered in a dedicated lecture.

Common Mistakes and Precautions with for Loops

Forgetting Indentation

for number in numbers:
print(number)  # This will cause an error.

In Python, indentation defines the block scope. Omitting it, as above, will cause an IndentationError. Always indent the block of code one level.

Misunderstanding the End of range()

for i in range(3):
    print(i)
# Output
0
1
2

range(3) generates numbers 0 through 2 (one less than 3). Remember that the end value is not included.

Do Not Modify a List During Looping

Modifying a list while looping through it can change the list's length mid-iteration, potentially causing infinite loops or unexpected behavior.

In the example below, numbers is modified within the for loop using append(). Python will continue iterating as long as elements remain in the list, so adding elements inside the loop can lead to an endless loop.

numbers = [1, 2, 3]
for number in numbers:
    numbers.append(number * 2)  # Can cause infinite loops or unexpected behavior.

An endless loop like this is called an "infinite loop." If it occurs, you must forcibly terminate the program. In Visual Studio Code, click the Stop button at the top of the screen to halt execution.

To avoid infinite loops, it is safer to iterate over a copy using numbers.copy().

In the following example, the variable numbers and the list generated by numbers.copy() are separate objects. Modifying numbers does not affect the iteration count, which ends after the original 3 elements.

numbers = [1, 2, 3]
for number in numbers.copy():
    numbers.append(number * 2)
スポンサーリンク