You Are Given a Number as an Input. You Have to Display All The Numbers From 0 Till X

Hi, in this article let's learn a Python program that accepts a  number as input from the user and displaces the numbers from 0 and till the given number using the loop.

Let's try to solve this Python program using the while loop and the for loop.

 

You Are Given a Number as an Input. You Have to Display All The Numbers From 0 Till X

 

 


You Are Given a Number as an Input. You Have to Display All The Numbers From 0 Till X


Take a variable named as X and using the input function call ask the user to enter the number.  Once the user enters the number, convert it into an integer type and store the value into variable X.

x = int(input("Enter a Number : "))




Now using the print statement Print a user friendly message to display the numbers between zero to x are …

Using the for loop, iterate all the numbers that are present in the range 0 till x + 1 to get the value of x inclusive.  inside the for low print the value of number.

print(f"Numbers from 0 till {x} are ...")

for number in range(x+1):
   print(number)



The print statement will display the numbers between zero till x  to standard output.


Complete Python program
=============================


x = int(input("Enter a Number : "))

print(f"Numbers from 0 till {x} are ...")

for number in range(x+1):
   print(number)




Output
==========

Enter a Number : 5
Numbers from 0 till 5 are ...
0
1
2
3
4
5



Output 2
===========

Enter a Number : 3
Numbers from 0 till 3 are ...
0
1
2
3





Now let's try to  solve the same program using the while loop constant.

As usual as the user to enter a number that is value of x convert it into an integer type and store it in variable x

Take the index variable, initialize it to zero and until the value of the index variable is not equal to X.  use the while loop to iterate and print the index.



Complete Python program
=============================

x = int(input("Enter a Number : "))

print(f"Numbers from 0 till {x} are ...")

index = 0
while index <= x:
   print(index)
   index += 1




Output
=============

Enter a Number : 7
Numbers from 0 till 7 are ...
0
1
2
3
4
5
6
7




Conclusion
==================

The above Python program asks the user to enter a number and stores it in variable x.  so using the looping construct it prints the values between zero till the value of x.

Execute the above Python program by providing a random  integer as input to the Python program and note down the results.

Comment it down below if you have any queries regarding the above  python program

Post a Comment

0 Comments