Python Sum Even
## Python: Summing Numbers and Even Numbers from 1 to 100
In Python, calculating the sum of a range of numbers and filtering them based on specific conditions (such as finding even numbers) is a fundamental task. This tutorial demonstrates how to calculate the total sum of integers from 1 to 100 and extract the sum of only the even numbers within that range.
---
## 1. Basic Implementation Using a Loop
This approach uses a standard `for` loop combined with a conditional `if` statement to calculate both the total sum and the sum of even numbers in a single pass.
### Code Example
```python
# Initialize accumulators for the total sum and the sum of even numbers
total_sum = 0
even_sum = 0
# Iterate through numbers from 1 to 100 (101 is exclusive)
for i in range(1, 101):
total_sum += i
# Check if the number is even using the modulo operator
if i % 2 == 0:
even_sum += i
# Output the results
print(f"The total sum from 1 to 100 is: {total_sum}")
print(f"The sum of even numbers from 1 to 100 is: {even_sum}")
```
### Code Explanation
1. **Initialization**: We define two variables, `total_sum` and `even_sum`, and initialize them to `0`.
2. **Range Generation**: The `range(1, 101)` function generates a sequence of integers starting from `1` up to (but not including) `101`.
3. **Accumulation**: In each iteration, the current integer `i` is added to `total_sum`.
4. **Modulo Condition**: The conditional statement `if i % 2 == 0` checks if the number is divisible by 2 with no remainder. If true, the number is even and is added to `even_sum`.
5. **Output**: Finally, we use f-strings to print the formatted results.
### Output
```text
The total sum from 1 to 100 is: 5050
The sum of even numbers from 1 to 100 is: 2550
```
---
## 2. Alternative Pythonic Approaches
While the loop-based approach is highly readable for beginners, Python offers more concise, idiomatic, and efficient ways to achieve the same result.
### Method A: Using `range()` Step Parameter
Instead of checking every number with an `if` statement, you can use the third argument of the `range()` function (the step size) to generate only even numbers directly.
```python
# Sum of all numbers from 1 to 100
total_sum = sum(range(1, 101))
# Sum of even numbers from 2 to 100 (stepping by 2)
even_sum = sum(range(2, 101, 2))
print(f"Total Sum: {total_sum}")
print(f"Even Sum: {even_sum}")
```
### Method B: Using List Comprehension and Generator Expressions
You can filter even numbers dynamically using a generator expression inside the built-in `sum()` function.
```python
# Calculate even sum using a generator expression
even_sum = sum(i for i in range(1, 101) if i % 2 == 0)
print(f"Even Sum (Generator): {even_sum}")
```
---
## 3. Key Considerations
* **Boundary Conditions**: In Python, `range(start, stop)` is right-exclusive. To include the number `100`, the `stop` parameter must be set to `101`.
* **Performance**: For large-scale numerical computations, using Python's built-in `sum()` function combined with `range()` is significantly faster than manual `for` loops because the summation is optimized in C under the hood.
* **Memory Efficiency**: Generator expressions (e.g., `sum(i for i in ... )`) are memory-efficient because they yield items one at a time instead of constructing a full list in memory.
YouTip