Python program to print numbers from 1 to 10
Loops are used to perform iterations on a block of code based on a criteria.
Python provides for
and while
loops to loop over iterable-objects
Python program to print numbers from 1 to 10 using For loop
For loop is used to iterate over arrays(list, tuple, set, dictionary) or strings. Python provides rich set of built-in functions and we are going to use range()
function which is popular in generating iterable sequence in the given range.
print("Print integers 1 to 10 using for loop:")
for i in range(1, 11): # iterates for 10 times
print(i)
Results
Print integers 1 to 10 using for loop:
1
2
3
4
5
6
7
8
9
10
Python program to print numbers from 1 to 10 using While loop
While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of ierations is not known in advance.
input = 1
print("Print integers 1 to 10 using while loop:")
while input <= 10: # iterates for 10 times
print(input)
input += 1
Results
Print integers 1 to 10 using while loop:
1
2
3
4
5
6
7
8
9
10
Note
Indentation is very important in Python, make sure the indentation is followed correctly