Javaexercise.com

Python Program To Print All Positive Numbers In A Range

In this article, we will learn to write a python program to print all positive numbers in a range.

A number that is greater than zero is known as a positive number. Positive numbers can be written without any sign or '+' sign in front of them.

Sample input and output examples:

Input: start = -7, end = 5
Output: 0, 1, 2, 3, 4, 5 
​
Input: start = -5, end = 6
Output: 0, 1, 2, 3, 4, 5, 6

We will use the following approaches to solve this problem:

  1. Assigning range limits

  2. Taking range limits from the user as input

Let's understand with the help of some simple examples.

Print the positive numbers in a range by assigning range limits in python

Here, we will use a for loop to traverse each element in the range and fetch the positive numbers. An algorithm is given below.

Algorithm:

Step 1: Start

Step 2: Assign upper and lower limits of the range

Step 3: Run a loop from lower limit to upper limit

Step 4: Add an if condition to check the positive number in the range

Step 5: If the condition is true, print that number

Step 6: End

Look at the program below to understand the implementation of the above-mentioned algorithm.

# Python program to print positive numbers in a given range
​
lwr_limit, upr_limit = -7, 10
​
print(f"The positive numbers in the range are: ")
# iterating each number in list
for num in range(lwr_limit, upr_limit + 1):
​
    # checking condition
    if num >= 0:
        print(num, end=" ")

Output:

The positive numbers in the range are:

0 1 2 3 4 5 6 7 8 9 10

 

Progam from the user as input in python

Here, we will use another approach to solve the problem, we will take the upper limit and lower limit from the user as input. And then to print positive numbers, we will do traversing and checking with the help of for loop and if statement.

Algorithm:

Step 1: Start

Step 2: Take input of lower limit of the range

Step 3: Take input of upper limit of the range

Step 4: Run a loop from lower limit to upper limit

Step 5: Add an if condition to check the positive number in the range

Step 6: If the condition is true, print that number

Step 7: End

Here, we have used the above-mentioned algorithm to print the positive numbers in range limits provided by the user as input.

# Python program to print positive Numbers in a given range
​
lwr_limit = int(input("Enter the start of range: "))
upr_limit = int(input("Enter the end of range: "))
​
# iterating each number in list
for num in range(lwr_limit, upr_limit + 1):
​
    # checking condition
    if num >= 0:
        print(num, end=" ")

Output:

Enter the start of range: -100

Enter the end of range:

7 0 1 2 3 4 5 6 7