Python program to print all positive numbers in a range

In this article, we will learn to create a program to print all positive numbers in a given range using python programming.

We do this program using 2 different methods:

  1. Using loop
  2. Using list comprehension
Input
Starting number is: -2
Ending number is: 10

Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ,10]

For loop

Explanation

  1. First, we take the input from the user of starting and ending numbers.
  2. Then, we initiate the result list.
  3. After that, iterate all numbers from the given range,
  4. And check if the number is greater than or equal to 0.
  5. If it satisfied the above condition and appends those elements to result list.
  6. And lastly, print the result.

Program

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# take input from the user
start = int(input("Enter starting number: "))
end = int(input("Enter ending number: "))

# result
result = []

# iterate all elements from the given range
for ele in range(start, end+1):
    # check positive number
    if ele>=0:
        # appends elements to result
        result.append(ele)
        
# print result
print(result)

Output

Enter starting number: -4
Enter ending number: 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

List Comprehension

Explanation

  1. First, we take the input from the user of starting and ending numbers.
  2. Using list comprehension, check the elements is greater than or equal to 0.
  3. print the result 

Program

1
2
3
4
5
6
7
8
9
# take input from the user
start = int(input("Enter starting number: "))
end = int(input("Enter ending number: "))

# result
result = [num for num in range(start, end+1) if num >=0]
        
# print result
print(result)

Output

Enter starting number: -4
Enter ending number: 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Next Post Previous Post
No Comment
Add Comment
comment url