Python, a versatile and beginner-friendly programming language, offers multiple ways to accomplish simple tasks like summing numbers from 1 to 100. Below, we will explore a straightforward method to achieve this using a for loop and the range function. This program is not only educational for beginners but also serves as a fundamental example of how Python handles loops and accumulative operations.
pythonCopy Code# Initialize the sum variable to 0
sum = 0
# Loop through numbers from 1 to 100
for i in range(1, 101):
sum += i
# Print the result
print("The sum of numbers from 1 to 100 is:", sum)
This script initializes a variable sum
to store the cumulative sum. It then iterates through the numbers from 1 to 100 using the range(1, 101)
function, which generates a sequence of numbers starting from 1 and ending at 100. In each iteration, the current number (i
) is added to the sum
variable. Finally, the script prints the total sum of these numbers.
Moreover, Python provides an even simpler way to achieve the same result using the built-in sum
function combined with range
, as shown below:
pythonCopy Code# Use the built-in sum function with range
print("The sum of numbers from 1 to 100 is:", sum(range(1, 101)))
This one-liner accomplishes the same task by directly summing the range of numbers from 1 to 100, demonstrating Python’s emphasis on code readability and simplicity.
[tags]
Python, programming, sum, loop, range, beginner, accumulative operation, simplicity, one-liner