Write A Python Script To Create A List Of First N Natural Numbers

Hi, in this article let's learn how to create a Python list containing the first n natural numbers. I will be asking a user to enter the number and then based upon that I will be generating a range of natural numbers.


I'll be using a list comprehension method to generate the natural numbers and store it into a list.

 

Write A Python Script To Create A List Of First N Natural Numbers

 

Write A Python Script To Create A List Of First N Natural Numbers

Take a variable named as number and using the input function call let's ask a user to enter a number and then convert it into an integer using the type conversion.

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




Use the if statement to check if the number is less than or equal to zero if so print an error message that is you entered an invalid number and then exit the program.

Use the else block to generate the natural numbers, take a variable named as natural_numbers and use the list comprehension technique to generate the list of natural numbers. Inside the else block print all the natural numbers present in the list.

if number <= 0:
   print("You Entered Invalid Number")
else:
   natural_numbers = [index for index in range(1, number + 1)]
   print("List of Natural Numbers are ...")
   for item in natural_numbers:
       print(item, end=" ")



Python Code
=====================


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

if number <= 0:
   print("You Entered Invalid Number")
else:
   natural_numbers = [index for index in range(1, number + 1)]
   print("List of Natural Numbers are ...")
   for item in natural_numbers:
       print(item, end=" ")






Output
==================
Enter a Number : 5
List of Natural Numbers are ...
1 2 3 4 5



Output
===========
Enter a Number : -6
You Entered Invalid Number




Output
=============
Enter a Number : 100
List of Natural Numbers are ...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100




Conclusion
=================
Execute the above Python program by providing input as integer number, note down the result it displays.

Comment down below if you have any suggestions to improve the Python program. 

 

 



Post a Comment

0 Comments