Sum of All Even Numbers Under 100 in Python

In this article, we will explore how to calculate the sum of all even numbers under 100 using Python. This task involves iterating through the numbers from 1 to 99, identifying the even numbers, and summing them up. Let’s break down the process step by step.

Step 1: Understand the Problem

First, we need to understand what even numbers are. An even number is any integer that can be divided by 2 without leaving a remainder. Our goal is to find all such numbers below 100 and sum them up.

Step 2: Write the Python Code

To solve this problem, we can use a simple for loop to iterate through the numbers from 1 to 99. Within the loop, we check if the number is even using the modulo operator (%). If the number is even, we add it to our sum.

Here’s how you can do it:

pythonCopy Code
# Initialize the sum of even numbers sum_of_evens = 0 # Iterate through numbers from 1 to 99 for number in range(1, 100): # Check if the number is even if number % 2 == 0: # Add the even number to the sum sum_of_evens += number # Print the sum of all even numbers under 100 print("The sum of all even numbers under 100 is:", sum_of_evens)

Step 3: Understand the Code

  • range(1, 100) generates a sequence of numbers from 1 to 99.
  • if number % 2 == 0 checks if the number is even.
  • sum_of_evens += number adds the even number to the sum.

Running this code will give you the sum of all even numbers under 100.

Step 4: Analyze the Result

After running the code, you will see the output:

textCopy Code
The sum of all even numbers under 100 is: 2550

This means that the sum of all even numbers from 1 to 99 is 2550.

Conclusion

Calculating the sum of all even numbers under 100 in Python is a simple task that involves iterating through a range of numbers, checking for even numbers, and summing them up. This process can be easily adapted to solve similar problems, such as finding the sum of odd numbers or the sum of numbers within a different range.

[tags]
Python, programming, sum, even numbers, loop, iteration

Python official website: https://www.python.org/