DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Day 23: Python Positive Sum Function – Calculate the Sum of Positive Numbers in a List

Welcome to Day 23 of the #80DaysOfChallenges journey! This beginner challenge centers on writing a function to sum positive numbers in a list, using straightforward iteration and checks to filter out negatives and zeros. It's a great way to get comfortable with loops, conditionals, and accumulating values, skills that pop up everywhere in data filtering and basic stats. If you're new to Python or tuning up your loop game, this "Python sum positives" walkthrough shows how to build clean, focused code that handles numeric lists with ease.


💡 Key Takeaways from Day 23: Positive Sum Function

This task builds a function that scans a list, adds up only the positives, and returns the total. It's a prime example of targeted processing: input a list, apply a filter, compute a result. We'll dig into the basics: function setup with accumulation, conditional filtering in loops, and practical output for testing.

1. Function Design: Basic Accumulation Logic

The sum_of_positives function takes a list of integers and outputs a single integer sum. Its signature is no-frills:

def sum_of_positives(numbers: list[int]) -> int:
    """
    Return the sum of positive numbers from the input list.
    """
Enter fullscreen mode Exit fullscreen mode

Start with a counter:

# Initialize a variable to keep the running total of positive numbers
total = 0
Enter fullscreen mode Exit fullscreen mode

This keeps things modular, no globals, just local math. The function runs in one loop, building the sum incrementally, and returns it directly. It's efficient for everyday lists and easy to slot into bigger code, like tallying scores or expenses where negatives don't count.

2. Loop and Conditional: Checking for Positives

The core is a for loop with a simple if:

for number in numbers:           # Loop through each number in the list
    if number > 0:               # Check if the current number is positive
        # Add it to the total if it's positive
        total += number
Enter fullscreen mode Exit fullscreen mode

Here, > 0 skips negatives and zeros cleanly. No extras like type checks (assuming integers), but it handles mixed signs without fuss. This pattern is versatile; swap the condition, and you're filtering evens, multiples, or whatever. It's a loop that reads like plain English, making it beginner-proof while scaling to real tasks.

3. Example Usage: Testing with Output

Tie it together in a quick demo:

sample_list = [5, -3, 15, -10, 2, 0, -13, 1]
result = sum_of_positives(sample_list)
print(f"\nList: {sample_list}")
print(f"Sum of positive numbers: {result}\n")
Enter fullscreen mode Exit fullscreen mode

For this list, it sums 5 + 15 + 2 + 1 = 23. The prints give clear feedback, showing input and output side-by-side. It's a setup that encourages experimenting, toss in your own list, run it, and see. No try-except needed here, but adding one later for empty lists or non-numbers would toughen it up.


🎯 Summary and Reflections

This positive sum challenge packs a lot into a small function, reminding me how loops and ifs team up for selective math. Key wins:

  • Simplicity: One loop, one check, one variable, easy to follow and fix.
  • Filtering basics: The if > 0 is a gateway to more complex conditions.
  • Reusability: Drop this into any numeric script for quick aggregates.

I noticed how ignoring zeros feels right for many scenarios, like positive-only totals. For fun, I pondered adding a count of positives or handling floats by rounding.

Advanced Alternatives: Use a generator: sum(n for n in numbers if n > 0), or list comps for the same. What's your go-to for summing subsets in Python? Share in the comments!


🚀 Next Steps and Resources

Day 23 kept the focus on core loops, paving the way for trickier data manipulations. In #80DaysOfChallenges? Did you extend it to sum negatives too? Post your tweaks!

Top comments (0)