Python For Loop: Summing Numbers from 1 to 100

In Python, summing a series of numbers from 1 to 100 can be achieved using a simple for loop. This is a fundamental exercise for beginners to understand the basic structure of loops and how they can be used to perform repetitive tasks. Let’s delve into how this can be accomplished.

Understanding the For Loop

A for loop in Python is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string) or other iterable objects. In our case, we’ll use it to iterate through a range of numbers from 1 to 100.

Summing Numbers from 1 to 100

To sum the numbers from 1 to 100, we can follow these steps:

1.Initialize a variable to store the sum. This variable will accumulate the sum of all numbers as we iterate through the range.

2.Use a for loop to iterate through the range of numbers from 1 to 100.

3.Add each number to the sum variable within the loop.

4.Print the final sum after the loop completes.

Here’s how you can implement it:

pythonCopy Code
# Initialize sum total_sum = 0 # Iterate through numbers from 1 to 100 for number in range(1, 101): total_sum += number # Print the final sum print(total_sum)

This script initializes total_sum to 0. It then iterates through each number in the range from 1 to 100 (inclusive), adding each number to total_sum. After the loop completes, it prints the total sum, which should be 5050.

Conclusion

Using a for loop to sum numbers from 1 to 100 is a simple yet powerful exercise to grasp the concept of looping in Python. It demonstrates how to iterate through a sequence of numbers and accumulate their sum, showcasing the practical application of for loops in performing repetitive tasks.

[tags]
Python, for loop, summing numbers, range, basic programming

As I write this, the latest version of Python is 3.12.4