Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

Python for Loop

In computer programming, loops are used to repeat a block of code.

For example, if we want to show a message 100 times, then we can use a loop. It's just a simple
example; you can achieve much more with loops.
There are 2 types of loops in Python:

 for loop
 while loop

Python for Loop

In Python, a for loop is used to iterate over sequences such as lists, tuples, string, etc. For
example,
languages = ['Swift', 'Python', 'Go', 'JavaScript']

# run a loop for each item of the list


for lan in languages: #lan=languages[0] #lan=languages[1]
print(lan)
#print(languages[0]);

output:

Swift
Python
Go
JavaScript

In the above example, we have created a list called languages.


Initially, the value of language is set to the first element of the array,i.e. Swift, so the print
statement inside the loop is executed.
language is updated with the next element of the list, and the print statement is executed again.
This way, the loop runs until the last element of the list is accessed.
Example

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

for Loop Syntax

The syntax of a for loop is:

for val in sequence:


# statement(s)

Here, val accesses each item of sequence on each iteration. The loop continues until we reach the
last item in the sequence.

Example: Loop Through a String


for x in 'Python':
print(x)

Output:
P
y
t
h
o
n

A range is a series of values between two numeric intervals.


We use Python's built-in function range() to define a range of values. For example,
values = range(4)
Here, 4 inside range() defines a range containing values 0, 1, 2, 3.
In Python, we can use for loop to iterate over a range. For example,
# use of range() to define a range of values
values = range(4)

# iterate from i = 0 to i = 3
for x in values:
print(x)

Output:
1
2
3
4

Using a for Loop Without Accessing Items

It is not mandatory to use items of a sequence within a for loop. For example
languages = ['Swift', 'Python', 'Go']

for language in languages:


print('Hello')
print('Hi')
Output
Hello
Hi
Hello
Hi
Hello
Hi

Here, the loop runs three times because our list has three items. In each iteration, the loop body
prints 'Hello' and 'Hi'. The items of the list are not used within the loop.
If we do not intend to use items of a sequence within the loop, we can write the loop like this:

languages = ['Swift', 'Python', 'Go']

for _ in languages:
print('Hello')
print('Hi')
The _ symbol is used to denote that the elements of a sequence will not be used within the loop
body.

Python for loop with else

A for loop can have an optional else block. The else part is executed when the loop is exhausted
(after the loop iterates through every item of a sequence). For example,
digits = [0, 1, 5]

for i in digits:
print(i)
else:
print("No items left.")
Output

0
1
5
No items left.
The break Statement

With the break statement we can stop the loop before it has looped through all the items:

Example

Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break

Output:
apple
banana
Example

Exit the loop when x is "banana", but this time the break comes before the print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x)

Output:
apple
The continue Statement

With the continue statement we can stop the current iteration of the loop, and continue with the
next:

Example

Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

output:
apple
cherry

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and ends at a specified number.

Example

Using the range() function:

for x in range(6):
print(x)
output:
0
1
2
3
4
5

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):

Example

Using the start parameter:


for x in range(2, 6):
print(x)
output
2
3
4
5

The range() function defaults to increment the sequence by 1, however it is possible to specify
the increment value by adding a third parameter: range(2, 30, 3):

Example

Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)
output:

Else in For Loop

The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:

Example

Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):
print(x)
else:
print("Finally finished!")
Note: The else block will NOT be executed if the loop is stopped by a break statement.

Example

Break the loop when x is 3, and see what happens with the else block:

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
output:
0
1
2
Nested Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example

Print each adjective for every fruit:

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)
The pass Statement

for loops cannot be empty, but if you for some reason have a for loop with no content, put in
the pass statement to avoid getting an error.

Example
for x in [0, 1, 2]:
pass

Python While Loops


Python Loops

Python has two primitive loop commands:

 while loops
 for loops

The while Loop

With the while loop we can execute a set of statements as long as a condition is true.

Example

Print i as long as i is less than 6:

i=1
while i < 6:
print(i) #1 2 3 4 5
i += 1 #i=i+1

Note: remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example we need to define an
indexing variable, i, which we set to 1.

The break Statement

With the break statement we can stop the loop even if the while condition is true:

Example

Exit the loop when i is 3:

i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example

Continue to the next iteration if i is 3:

i=0
while i < 6:
i += 1 #1 #2 #3 #4 #5 #6
if i == 3:
continue
print(i)

i=1
while i<6:
if i==3:
continue
print(i)
i+=1
output:
1
2
4
5
The else Statement

With the else statement we can run a block of code once when the condition no longer is true:

Example

Print a message once the condition is false:

i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

You might also like