Python Program: Print Positive Numbers in a List
In this blog post, we’ll explore a Python program that prints positive numbers from a given list. The program takes a list of numbers as input and outputs only the positive ones. We will provide a step-by-step explanation of the algorithm, showcase the Python code, and include examples with corresponding outputs.
Understanding the Algorithm
To print positive numbers from a list, we need to iterate through each element in the list and check if it is greater than zero. Here are the key steps:
Input List: Receive a list of numbers as input.
Iterate Through List: Use a loop to go through each element in the list.
Check for Positivity: For each element, check if it is greater than zero.
Print Positive Numbers: If an element is positive, print it.
Output Result: Display the positive numbers in the list.
Python Program for Printing Positive Numbers
Let’s implement the algorithm in a Python program:
def print_positive_numbers(numbers):
positive_numbers = [num for num in numbers if num > 0]
print("Positive numbers in the list:")
for num in positive_numbers:
print(num, end=" ")
# Input list of numbers
numbers = [12, -7, 5, 64, -14, 9, -23, 6]
# Call the function to print positive numbers
print_positive_numbers(numbers)
Output Example
Example: Print Positive Numbers
Let’s consider the input list [12, -7, 5, 64, -14, 9, -23, 6]
:
Output
Positive numbers in the list:
12 5 64 9 6
Explanation
The program defines a function print_positive_numbers
that takes a list of numbers as input. It uses a list comprehension to create a new list containing only the positive numbers. The function then prints the positive numbers.
In the example, the input list [12, -7, 5, 64, -14, 9, -23, 6]
is passed to the function, and it outputs the positive numbers [12, 5, 64, 9, 6]
.
Conclusion
This Python program provides a simple yet effective way to extract and print positive numbers from a given list. Understanding list comprehensions and conditional statements in Python is essential for such tasks.
Feel free to modify the program for different lists of numbers or integrate it into a larger application. If you have any questions or want to explore more Python programming topics, feel free to ask!