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:
- Using loop
- Using list comprehension
For loop
Explanation
- First, we take the input from the user of starting and ending numbers.
- Then, we initiate the result list.
- After that, iterate all numbers from the given range,
- And check if the number is greater than or equal to 0.
- If it satisfied the above condition and appends those elements to result list.
- 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
- First, we take the input from the user of starting and ending numbers.
- Using list comprehension, check the elements is greater than or equal to 0.
- 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]