Use a for
loop to compute the sum of all numbers from 14
to 73
.
Once computed, print this sum to the console.
In this exercise, we will learn how to use a for
loop to compute the sum of a range of numbers. This is a fundamental concept in programming that helps in understanding loops and iteration, which are essential for solving many computational problems.
Summing a range of numbers is a common task in various scenarios, such as calculating totals, averages, or even in more complex algorithms like those used in data analysis and machine learning.
A for
loop is a control flow statement that allows code to be executed repeatedly based on a condition. The loop runs as long as the condition is true. Here, we will use a for
loop to iterate through numbers from 14 to 73 and compute their sum.
Example of a simple for
loop:
# Example of a simple for loop
for i in range(5):
print(i) # This will print numbers from 0 to 4
To solve this problem, we need to:
for
loop to iterate through each number in the specified range.Let's consider the range from 14 to 73. We will initialize a variable total_sum
to 0 and then use a for
loop to add each number in this range to total_sum
.
# Initialize the sum variable
total_sum = 0
# Iterate through numbers from 14 to 73
for number in range(14, 74): # range(14, 74) includes 14 and excludes 74
total_sum += number # Add the current number to total_sum
# Print the final sum
print(total_sum)
Common mistakes to avoid:
Best practices:
For more advanced scenarios, you might need to sum numbers based on certain conditions or use more complex data structures. For example, summing only even numbers in a range:
# Initialize the sum variable
total_sum = 0
# Iterate through numbers from 14 to 73
for number in range(14, 74):
if number % 2 == 0: # Check if the number is even
total_sum += number # Add the even number to total_sum
# Print the final sum
print(total_sum)
To debug and test your code:
# Initialize the sum variable
total_sum = 0
# Iterate through numbers from 14 to 73
for number in range(14, 74):
total_sum += number # Add the current number to total_sum
# Check if the sum is correct
assert total_sum == 2412, f"Expected 2412, but got {total_sum}"
# Print the final sum
print(total_sum)
When approaching problems like this:
Summing a range of numbers using a for
loop is a basic yet powerful concept in programming. Mastering this will help you understand loops and iteration, which are crucial for more complex algorithms and data processing tasks.
Practice this concept with different ranges and conditions to strengthen your understanding.
For further reading and practice: