Python Program: Print All Negative Numbers in a Range
In this blog post, we’ll explore a Python program designed to print all negative numbers within a specified range. We’ll provide a detailed explanation of the algorithm, present the Python code, and include examples with corresponding outputs.
Understanding the Algorithm
The algorithm for printing negative numbers in a given range is straightforward:
Input Range: Receive the lower and upper bounds of the range.
Iterate Through Range: Use a loop to iterate through the range from the lower bound to the upper bound.
Check Negativity: For each number in the range, check if it is negative.
Print Negative Numbers: Display all negative numbers encountered during the iteration.
Output Result: Complete the program by printing the desired negative numbers.
Python Program for Printing Negative Numbers in a Range
Let’s implement the algorithm in a Python program:
def print_negative_numbers(lower, upper):
print(f"Negative numbers in the range {lower} to {upper}:")
for num in range(lower, upper + 1):
if num < 0:
print(num)
# Input range
lower_limit = -10
upper_limit = 10
# Call the function to print negative numbers in the specified range
print_negative_numbers(lower_limit, upper_limit)
Output Example
Example: Printing Negative Numbers in a Range
Consider the input range from -10
to 10
:
Output
Negative numbers in the range -10 to 10:
-10
-9
-8
-7
-6
-5
-4
-3
-2
-1
Explanation
The program defines a function named print_negative_numbers
that takes two parameters: lower
(the lower bound of the range) and upper
(the upper bound of the range). The function then iterates through the specified range and prints each negative number encountered.
In the example, the input range is from -10
to 10
. The program identifies and prints all negative numbers in this range.
Conclusion
This Python program provides a simple and effective solution for printing negative numbers within a specified range. Feel free to customize the range or incorporate this functionality into larger projects. If you have any questions or would like to explore more Python programming topics, don’t hesitate to ask!