Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
52 views

For Loop Python

Python for loops can be used to iterate over sequences like lists, tuples, dictionaries and strings. A for loop executes a set of statements for each item in the sequence. The range() function returns a sequence of numbers used to iterate a specific number of times in a for loop. Additional for loop concepts include nested loops, the break and continue statements, and using else with for loops.

Uploaded by

Raja Prasant
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views

For Loop Python

Python for loops can be used to iterate over sequences like lists, tuples, dictionaries and strings. A for loop executes a set of statements for each item in the sequence. The range() function returns a sequence of numbers used to iterate a specific number of times in a for loop. Additional for loop concepts include nested loops, the break and continue statements, and using else with for loops.

Uploaded by

Raja Prasant
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more like an iterator method as found in
other object-orientated programming languages.

With the for loop, we can execute a set of statements, once for each item in a list, tuple, set etc.

Example- Print each fruit in a fruit list: Output:


fruits = ["apple", "banana", "cherry"] apple
for x in fruits: banana
print(x) cherry
The for loop does not require an indexing variable to set beforehand.
Looping Through a String
Even strings are iterable objects, they contain a sequence of characters:
Example Output:
Loop through the letters in the word "banana": b
a
for x in "banana": n
print(x) a
Example 2: Python program to display the use of 'for' loop with String, List and Tuple Iteration. n
# String Iteration a
print ("*" * 20)
print ("String Iteration")
str = "Balaji" Output:
for i in str:
print (i)
# A list Iteration
print ("*" * 20)
print ("List Iteration")
lst = ["Sun", "Moon", "Earth"]
for i in lst:
print (i)
# A tuple Iteration
print ("*" * 20)
print ("Tuple Iteration")
tpl= ("CCC", "O Level", "A Level")
for i in tpl:
print (i)
# dictionary Iteration
print ("*" * 20)
print ("Dictionary Iteration")
ax= dict ()
ax ['a'] =100
ax ['b'] =200
for i in ax:
print ("%s %d" %(i, ax[i]))
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"] Output:
for x in fruits:
apple
banana
print(x)
if x == "banana":
break
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": Output:
break
print(x) 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"] Output:
for x in fruits:
if x == "banana": apple
continue cherry
print(x)
The range() Function
In Python, range() function accepts an integer and returns a range object, which is nothing but a sequence of
integers. Let's understand how to use range() function with the help of simple examples.
Syntax:
range (start, stop) , step])
range() takes three arguments. Out of the three 2 arguments are optional. i.e., Start and Step are the
optional arguments. The most common use of range() function in python is to iterate sequence type (List, string etc)
with for and while loop.
 A start argument is a starting number of the sequence. i.e., lower limit. By default, it starts with 0 if not
specified.
 A stop argument is an upper limit. i.e., generate numbers up to this number. The range() function doesn't
include this number in the result. (by default argument)
 The step is a difference between each number in the result. The default value of the step is 1 if not specified.

Rules:
 All argument must be integers i.e., whole numbers only. You cannot pass a string or float number or any
other type in a start, stop and step argument of a range().
 All three arguments can be positive or negative.
 The step value must not be zero. If a step is zero python raises a ValueError exception.
To loop through a set of code a specified number of times, we can use the range() function, Output:
The range() function returns a sequence of numbers, starting from 0 by default, and increments 0
by 1 (by default), and ends at a specified number. 1
Example 2
Using the range() function: 3
for x in range(6): 4
print(x) 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): Output:
Example 2
Using the start parameter: 3
for x in range(2, 6): 4
print(x) 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 Output:
Increment the sequence with 3 (default is 1): 2
for x in range(2, 30, 3): 5
print(x) 8
11
Else in For Loop 14
The else keyword in a for loop specifies a block 17
of code to be executed when the loop is 20
finished: 23
26
Example 29
Print all numbers from 0 to 5, and print a
Output:
message when the loop has ended:
0
for x in range(6):
1
print(x)
2
else:
3
print("Finally finished!")
4
5
Note: The else block will NOT be executed if
Finally finished!
the loop is stopped by a break statement.

Example Output:
Break the loop when x is 3, and see what happens with the else block: 0
for x in range(6): 1
if x == 3: break 2
print(x)
else:
print("Finally finished!")
#If the loop breaks, the else block is not executed.

Nested Loops Output:


A nested loop is a loop inside a loop. red apple
The "inner loop" will be executed one time for each iteration of the "outer loop": red banana
Example red cherry
Print each adjective for every fruit: big apple
adj = ["red", "big", "tasty"] big banana
fruits = ["apple", "banana", "cherry"] big cherry
for x in adj: tasty apple
for y in fruits: tasty banana
print(x, y) tasty cherry

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

# having an empty for loop like this, would raise an error without the pass statement

You might also like