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.
1 2 3 4 5 6 7 |
number_list = [5, -2, 10, 0, 8, -7] positive_sum = 0 for number in number_list: if number > 0: positive_sum += number print("Sum of positive numbers:", positive_sum) |
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.
1 2 3 4 |
number_list = [5, -2, 10, 0, 8, -7] positive_sum = sum([number for number in number_list if number > 0]) print("Sum of positive numbers:", positive_sum) |
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.
1 2 3 4 |
number_list = [5, -2, 10, 0, 8, -7] positive_sum = sum(filter(lambda number: number > 0, number_list)) print("Sum of positive numbers:", positive_sum) |
Output:
Sum of positive numbers: 23
Full Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Method 1: Using a Loop number_list = [5, -2, 10, 0, 8, -7] positive_sum = 0 for number in number_list: if number > 0: positive_sum += number print("Sum of positive numbers:", positive_sum) # Method 2: Using List Comprehension number_list = [5, -2, 10, 0, 8, -7] positive_sum = sum([number for number in number_list if number > 0]) print("Sum of positive numbers:", positive_sum) # Method 3: Using a Lambda Function with the filter() Function number_list = [5, -2, 10, 0, 8, -7] positive_sum = sum(filter(lambda number: number > 0, number_list)) print("Sum of positive numbers:", positive_sum) |
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!