How To Add Only Positive Numbers In Python

Python is a powerful programming language widely used in various fields, such as data analysis, artificial intelligence, and web development.

The languageā€™s simplicity and readability make it easy for beginners to create basic programs, such as adding only positive numbers. In this tutorial, we will explore different methods to add positive numbers in Python.

Method 1: Using a Loop

The simplest method to add positive numbers is by using a for or while loop and an if statement to add only the positive numbers in your dataset.

Output:

Sum of positive numbers: 23

Method 2: Using List Comprehension

Another method to add positive numbers is by using list comprehension. This is a concise way to create lists and apply conditions.

Output:

Sum of positive numbers: 23

Method 3: Using a Lambda Function with the filter() Function

You can also use the filter() function along with a lambda function to filter out the positive numbers and then use the sum() function to add the filtered numbers.

Output:

Sum of positive numbers: 23

Full Code:

Conclusion:

In this tutorial, you learned three methods to add only positive numbers in Python. Understanding these methods is beneficial, as it allows you to choose the most appropriate technique for your specific use case. Keep exploring and experimenting with Python!