Python

champak
₹2,000.00 ₹300.00
The Python Programming Language at Champak's World
  • 22 students
  • 41 lessons
  • 0 quizzes
  • 10 week duration

Python

For loop in Python

In this lesson we shall study the Python for loop in some detail.

The simplest for loop is.


for i in range(11):
print(i)

for i in range(11)  will run a loop from 1 to 10 increasing by 1 every time. In the general case it is

for i in range(n+1) running a loop from 1 to n.

What happens if we want to run a loop from 3 to 9.

We shall write


for i in range(3,10):
print(i)

What happens if we want to go from 9 to 3. Would changing the range variables help?

Let us try this loop.


for i in range(10,3):
print(i)

The loop doesn’t run.

The correct loop is


for i in range(10,2,-1):
print(i)

This brings us to the most diverse form of the Python for loop.


start=2
end=12
increment=2
for i in range(start,end,increment):
print(i)

 

Assignments.

  1. Write a program to find the factorial of a number.
  2. Write a program to find the sum of factorials.
  3. Write a program to print the binary equivalent of a positive decimal integer.

end

Leave a Reply

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