Counting Positive and Negative Numbers in a List using Python
In this comprehensive blog post, we will delve into the Python programming language to create a program that counts positive and negative numbers in a given list. The article will provide an in-depth explanation of the algorithm used, include the Python code for implementation, and showcase examples with corresponding outputs.
Understanding the Algorithm
The algorithm for counting positive and negative numbers in a list involves the following steps:
- Input List: Accept a list of integers, either predefined or entered by the user.
- Initialize Counters: Initialize counters for positive and negative numbers.
- Iterate Through the List: Traverse each element in the list and increment the respective counter based on its sign.
- Display Counts: Print or display the counts of positive and negative numbers.
Python Program for Counting Positive and Negative Numbers
Let’s implement the algorithm in a Python program:
def count_positive_negative(numbers):
positive_count = 0
negative_count = 0
# Count positive and negative numbers
for num in numbers:
if num > 0:
positive_count += 1
elif num < 0:
negative_count += 1
return positive_count, negative_count
# Example list of numbers
example_numbers = [5, -8, 10, -3, 7, 2, -1, 0]
# Count positive and negative numbers
positive, negative = count_positive_negative(example_numbers)
# Display the counts
print("List of Numbers:", example_numbers)
print("Positive Numbers Count:", positive)
print("Negative Numbers Count:", negative)
Output Example
Example: Counting Positive and Negative Numbers in [5, -8, 10, -3, 7, 2, -1, 0]
List of Numbers: [5, -8, 10, -3, 7, 2, -1, 0]
Positive Numbers Count: 5
Negative Numbers Count: 3
Explanation
The Python program defines a function count_positive_negative
that takes a list of numbers as input. It initializes counters for positive and negative numbers and iterates through the list, updating the counters accordingly. The counts are then displayed.
Conclusion
Counting positive and negative numbers is a fundamental operation in data analysis and algorithmic problem-solving. This Python program provides a simple yet effective way to perform this task on a given list of numbers. Feel free to experiment with different lists to observe how the counts change. Understanding such basic operations is essential for building more complex programs and algorithms.
If you have any questions or would like further clarification, please don’t hesitate to ask!