YouTip LogoYouTip

Python Odd Squares

## Python: Calculating the Sum of Squares of Odd Numbers (1 to 100) In Python programming, performing mathematical operations over a range of numbers is a fundamental task. This tutorial demonstrates how to calculate the sum of the squares of all odd numbers between 1 and 100. We will explore multiple approaches to solve this problem, ranging from basic loops to highly optimized, Pythonic one-liners. --- ## 1. Standard Approach: Using a `for` Loop and Conditional Statements This approach is highly readable and ideal for beginners. It uses a `for` loop to iterate through the range of numbers and an `if` statement to filter out the even numbers. ### Code Example ```python # Initialize a variable to store the cumulative sum total_sum = 0 # Loop through numbers from 1 to 100 (101 is exclusive) for i in range(1, 101): # Check if the number is odd if i % 2 != 0: # Add the square of the odd number to the total sum total_sum += i ** 2 # Output the final result print("The sum of the squares of all odd numbers from 1 to 100 is:", total_sum) ``` ### Code Explanation 1. **`total_sum = 0`**: Initializes a tracker variable to `0` to accumulate the sum. 2. **`for i in range(1, 101)`**: Generates a sequence of integers starting from `1` up to (but not including) `101`. 3. **`if i % 2 != 0`**: The modulo operator (`%`) returns the remainder of division. If `i % 2` is not equal to `0`, the number is odd. 4. **`total_sum += i ** 2`**: The `**` operator represents exponentiation in Python. If the condition is met, $i^2$ is added to `total_sum`. 5. **`print(...)`**: Outputs the final calculated sum to the console. ### Output ```text The sum of the squares of all odd numbers from 1 to 100 is: 166650 ``` --- ## 2. Optimized Approach: Using `range()` Step Value Instead of checking every single number to see if it is odd, we can optimize the loop by skipping even numbers entirely. The `range(start, stop, step)` function allows us to specify a step increment. ### Code Example ```python total_sum = 0 # Start at 1, stop before 101, and increment by 2 (generates only odd numbers) for i in range(1, 101, 2): total_sum += i ** 2 print("The sum of the squares of all odd numbers (optimized loop) is:", total_sum) ``` ### Why this is better: * **Performance**: It cuts the number of loop iterations in half (from 100 down to 50). * **Simplicity**: It eliminates the need for an inner conditional `if` statement. --- ## 3. Pythonic Approach: List Comprehension and `sum()` In professional Python development, list comprehensions and built-in functions are preferred for writing clean, concise, and expressive code. ### Code Example ```python # One-liner using generator expression and the built-in sum() function total_sum = sum(i ** 2 for i in range(1, 101, 2)) print("The sum of the squares of all odd numbers (Pythonic way) is:", total_sum) ``` ### Code Explanation * **`i ** 2 for i in range(1, 101, 2)`**: This is a generator expression that yields the square of each odd number on the fly. * **`sum(...)`**: This built-in Python function aggregates all the yielded values directly, saving memory compared to creating a full list in memory. --- ## Considerations & Best Practices * **Memory Efficiency**: When dealing with large ranges (e.g., 1 to 1,000,000), prefer using generator expressions inside `sum()` rather than list comprehensions (i.e., use `sum(x**2 for x in ...)` instead of `sum([x**2 for x in ...])`). This avoids loading the entire list of squared numbers into memory. * **Operator Precedence**: In Python, the exponentiation operator `**` has higher precedence than arithmetic operators like `+`, `-`, `*`, and `/`. Therefore, `i ** 2` is evaluated before addition, making parentheses optional but good for readability.
← Python Sum Even NumbersPython Flask Django β†’