Python Program to Print All Positive Numbers in a Range
Introduction
In this blog post, we will discuss and implement a Python program to print all positive numbers within a specified range. The program will take two integer values as input, representing the lower and upper bounds of the range. It will then identify and print all positive numbers within that range. We’ll provide a step-by-step explanation of the algorithm, present the Python program, and showcase its output with examples.
Algorithm to Print Positive Numbers in a Range
The algorithm for printing positive numbers in a given range can be outlined as follows:
- Input Range: Obtain the lower and upper bounds of the range.
- Iterate Through Range: Use a loop to iterate through each number in the specified range.
- Check Positivity: For each number, check if it is positive.
- Print Positive Numbers: If a positive number is found, print it.
- Output Result: Display the positive numbers within the given range.
Python Program Implementation
Now, let’s implement the algorithm in a Python program:
def print_positive_numbers(lower_bound, upper_bound):
# Check if the bounds are valid
if lower_bound > upper_bound:
print("Invalid range. Lower bound should be less than or equal to upper bound.")
return
print(f"Positive numbers in the range {lower_bound} to {upper_bound}:")
# Iterate through the range and print positive numbers
for num in range(lower_bound, upper_bound + 1):
if num > 0:
print(num, end=" ")
# Example usage
lower_limit = -5
upper_limit = 10
print_positive_numbers(lower_limit, upper_limit)
Output:
For example, if the lower bound is set to -5 and the upper bound to 10, the output will be:
Conclusion
This Python program effectively prints all positive numbers within a specified range. The algorithm checks each number in the range and prints it if it is positive. You can modify the lower and upper bounds to experiment with different ranges. Understanding how to work with loops and conditionals is crucial for writing programs that involve iteration through numerical ranges. Happy coding!