Python Program to Print Negative Numbers in a Range

Write a Python program to print negative numbers in a range. This example allows start and end numbers and prints the negative numbers within that range.

minimum = int(input("Enter the Minimum Number = "))
maximum = int(input("Enter the Maximum Number = "))

print("\nAll Negative Numbers from {0} and {1}".format(minimum, maximum)) 
for num in range(minimum, maximum + 1):
    if num < 0:
        print(num, end = '   ')
Python Program to Print Negative Numbers in a Range

This program helps to print negative numbers in a range or from 1 to n using a while loop.

minimum = int(input("Enter the Minimum Number = "))
maximum = int(input("Enter the Maximum Number = "))

print("\nFrom {0} and {1}".format(minimum, maximum))
while minimum <= maximum:
    if minimum < 0:
        print(minimum, end = '   ')
    minimum = minimum + 1
Enter the Minimum Number = -35
Enter the Maximum Number = 400

From -35 and 400
-35   -34   -33   -32   -31   -30   -29   -28   -27   -26   -25   -24   -23   -22   -21   -20   -19   -18   -17   -16   -15   -14   -13   -12   -11   -10   -9   -8   -7   -6   -5   -4   -3   -2   -1  

In this Python example, the negativeNumbers function accepts two integers and prints the negative numbers between them.

# using functions
def negativeNumbers(x, y):
    for num in range(x, y + 1):
        if num < 0:
            print(num, end = '   ')


minimum = int(input("Enter the Minimum = "))
maximum = int(input("Enter the Maximum = "))

print("\nFrom {0} and {1}".format(minimum, maximum)) 
negativeNumbers(minimum, maximum)
Enter the Minimum = -25
Enter the Maximum = 120

From -25 and 120
-25   -24   -23   -22   -21   -20   -19   -18   -17   -16   -15   -14   -13   -12   -11   -10   -9   -8   -7   -6   -5   -4   -3   -2   -1   

Python Program to Print Negative Numbers in a Range using list comprehension

Similar to a for loop, we can use a list comprehension to print all negative numbers in a given range. Here, we use an if statement to filter the values less than 0.

start, end = -10, 5

numbers = [i for i in range(start, end + 1) if i < 0]
print(numbers)
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1]

Use filter to display negative numbers from -n  to n

Here, the condition (x < 0) checks whether the iteration value is less than 0. If so, the filter() selects those negative numbers. Finally, list() converts the filter object to a list.

start, end = -5, 10

n = filter(lambda x: x < 0, range(start, end+1))
print(list(n))
[-5, -4, -3, -2, -1]

Also Read