HomePython

Write a program to print first n numbers in python

Write a program to print first n numbers in python
Like Tweet Pin it Share Share Email

This program to print the first n number, introduces you to the usage of looping structures in python.

One of the important thing to remember in python is, it does not have any “{” for marking the code blocks like in any other programming languages. In python it is handled completely differently, set of statements are set to one block when they follow similar indentation . i.e. if 4 statements are having a tab space(4 spaces for single tab) at the beginning of each statement, they form one code block. These are important to know when working with conditional and looping structures.

There are multiple ways to write solution for this problem using a “for” , “while” looping structures, following are the 2 ways:

Way 1 – Print first n numbers in Python with a “for” loop

#initialise a variable "numbers" with the number of numbers you want to print.
#In Python you need not declare the variables to a specific data type.

numbers = 10;

#for looping as per python's syntax

for num in range(1,numbers):
    print num;

#next python statement in this program is outside of for loop, 
#as it does not have 4 spaces before the statement.
#Each statement inside the for loop is identified by number of spaces provided before each statement.

print "This statement is outside of for loop"; 

Way 2 – Print first n numbers in Python with a “while” loop

#initialise a variable "num", "numbers" with the starting number and number of numbers you want to print respectively.
#In Python you need not declare the variables to a specific data type.

num = 1;
numbers = 10;

#while loop as per python's syntax 

while (num<=10):
	print num;
	num = num + 1;

#next python statement in this program is outside of while loop, 
#as it does not have 4 spaces before the statement.
#Each statement inside the above while loop is identified by number of spaces provided before each statement.

print "This statement is outside of while loop"; 

Hope this example had given basic usage of looping structures i.e. “for” and “while”, in case of any queries, please do share them in form of comments, we would be more than happy to respond.

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *