logo

Loops: For loop, while loop

Code can be repeated using a loop. Lines of code can be repeated N times, where N is manually configurable. In practice, it means code will be repeated until a condition is met. This condition is usually (x >=N) but it’s not the only possible condition.

Python has 3 types of loops: for loops, while loops and nested loops.

Related Course:
Python Programming Bootcamp: Go from zero to hero

For loop

We can iterate a list using a for loop

#!/usr/bin/python

items = [ "Abby","Brenda","Cindy","Diddy" ]

for item in items:
print(item)

Visualization of for loop:
for loop

The for loop can be used to repeat N times too:

#!/usr/bin/python

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

While loop


If you are unsure how many times a code should be repeated, use a while loop.
For example,


correctNumber = 5
guess = 0

while guess != correctNumber:
guess = int(input("Guess the number: "))

if guess != correctNumber:
print('False guess')

print('You guessed the correct number')

Nested loops


We can combine for loops using nesting. If we want to iterate over an (x,y) field we could use:

#!/usr/bin/python

for x in range(1,10):
for y in range(1,10):
print("(" + str(x) + "," + str(y) + ")")

Nesting is very useful, but it increases complexity the deeper you nest.

If you are new to Python programming, I highly recommend this book.

Download Python Exercises

BackNext





Leave a Reply:




Daniel Dauda Fri, 22 May 2015

simple and understandable examples. thanks

Ron Hall Wed, 17 Jun 2015

I notice that the loops terminate without executing for the last value (10 in your example). Also, how do you control the number of statements executed by the loop? There don't seem to be any block boundaries.

Frank Thu, 18 Jun 2015

Hi Ron, That's correct, the parameters of range() are: range(start, stop[, step]) or range(start, stop). If you want to have 1 to 10, use range(1, 11).
To define block boundaries you use 4 spaces. This applies for functions, loops, conditonal statements etc. The way we define the for loop is equivalent to C/C++ for (i = 1; i < 10; i++). I hope you enjoy the site :-)

Ryan Wed, 05 Aug 2015

Do you have any examples of the continue/break statements that C-style languages have?

Admin Thu, 06 Aug 2015

Hi Ryan, you can simply use the break keyword in Python.

#!/usr/bin/env python

x = 0
while True:
print(x)

if x == 10:
break

x = x + 1

And example of continue:

#!/usr/bin/env python

x = 0
while True:

# use break to end the loop
if x == 10:
break

x = x + 1

# use continue to skip
if x >= 3 and x <= 6:
continue

print x
Ben Wed, 19 Aug 2015

Hi Frank, How about a-z? I wrote range (a,z), it showed me "name 'a' is not defined"

Frank Wed, 19 Aug 2015

Hi Ben, there are several ways to iterate through a character set:

#!/usr/bin/python

for x in range(ord('a'), ord('z')+1):
print chr(x)

or:

#!/usr/bin/python

x = "abcdefghijklmnopqrstuvwxyz"

for i in range(0,len(x)):
print(x[i])

or

#!/usr/bin/python
from string import ascii_lowercase

for i in ascii_lowercase :
print(i)

I hope that helps :-)

Barry Peters Wed, 19 Aug 2015

Can you explain the drive ()? Thanks!

Frank Wed, 19 Aug 2015

Sure, this is an example of a condition in a while loop. It may be that while you do not press the break in a car, the car keeps moving forward.

#!/usr/bin/env python

def drive():
print("driving")

action = "driving"
while "stop" not in action:
action = raw_input("What to do next?")
drive()

A while loops code continues to be executed until the condition is True.

Ian Thu, 20 Aug 2015

For the driving example in the comments section, it makes more sense to put the drive() command, in the while loop, before getting new input for the variable, action. As the code stands now, when one enters "stop", one sees "driving" as the output response. Switching the order of the statements in the while loop, just terminates the loop silently when "stop" is entered.

Michael Fri, 21 Aug 2015

nice examples thx .

Frank Sat, 22 Aug 2015

Thanks! I'm happy you enjoy the site

Ben Thu, 27 Aug 2015

Thank you so much

Amina Khatun Mon, 31 Aug 2015

From where I should start I can't understand? How to save, How to edit, How to run, These are my problems.

Frank Mon, 31 Aug 2015

Hi Amina, start from here: https://pythonspot.com/getting-started/
Download an editor like PyCharm to edit, save and run your code.

Deepak V a Thu, 03 Dec 2015

why are you using str() in print statement i am getting even i used variable directly

Frank Thu, 03 Dec 2015

sometimes that may lead to problems as they have different datatypes,just being cautious.

Prashant Raina Thu, 28 Jan 2016

whats wrong with this code not generating primes as i expected

i=3
num=int(input("enter the no. upto which u want the primes: "))
arr=[2]
print(2)
while i<num:
j=0
while j<len(arr):
if i%arr[j]==0:
i=i+1
j=len(arr)
else:
j=j+1
print i
arr[len(arr)]=i
Frank Sat, 30 Jan 2016

The conditions in the while loops are never true. I fixed your code:

num=int(input("enter the no. upto which u want the primes: "))

arr=[2]
print(arr)

i = 2
while max(arr) < num:

prime = True
for p in arr:
if i % p == 0:
prime = False
break

if prime:
arr.append(i)

i = i + 1

print(arr)

print(arr)


You can see the prime numbers being added to the array in the loop.

Sagi Sulimani Sat, 22 Apr 2017

Hi Frank.
There is a little mistake in the "While loop" example. It should be:
[python]
guess = int(input("Guess the number: "))
[/python]
Otherwise, the compiler will compare between string and integer, and '5'!=5.
Except it - excellent!

Frank Sat, 22 Apr 2017

Thanks Sagi!
I've updated the article.