python logo

python for loop


Python hosting: Host, run, and code Python in the cloud!

Loops are fundamental in programming, allowing for repetitive code execution based on specific conditions. Python provides versatile looping mechanisms that cater to various programming needs. This article delves into the primary looping structures in Python: for loops, while loops, and nested loops.

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

For Loop in Python

The for loop in Python provides a concise way to iterate over iterable objects such as lists, strings, and tuples.

1
2
3
4
items = ["Abby", "Brenda", "Cindy", "Diddy"]

for item in items:
print(item)

Visualization of for loop

Additionally, using the range() function, you can easily generate a sequence of numbers, making it simple to repeat a block of code N times.

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

While Loop in Python

The while loop offers a way to execute a block of code as long as a specific condition remains true. It’s particularly useful when the number of repetitions isn’t known beforehand.

1
2
3
4
5
6
7
8
9
10
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 in Python

For advanced use-cases, Python supports nesting loops within loops. While this allows for more sophisticated patterns, it’s essential to use with caution as nested loops can increase computational complexity.

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

To truly harness the power of loops in Python, practice and real-world application are key. Download Python Exercises to get started.

Navigate through our guide: < Back | Next >






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.