Python For Loops
Python For loop is used for sequential traversal i.e.it is used for iterating over an iterable like String, Tuple, List, Set, or Dictionary.
Example
for var in iterable: # statements
Example
fruits = ["apple", "banana", "orange"] for fruit in fruits: print(fruit)
Flowchart of For Loop
Here the iterable is a collection of objects like lists, and tuples.
The indented statements inside the for loops are executed once for each item in an iterable.
The variable var takes the value of the next item of the iterable each time through the loop.
Example
for x in 'Python': print(x) Output p y t h o n
Looping Through a String
Even strings are iterable objects, they contain a sequence of characters:
Example
# Define a string my_string = "Hello, CodeLines!" # Loop through each character in the string for char in my_string: print(char) Output H e l l o , C o d e L i n e s !
The break Statement
With the break statement we can stop the loop before it has looped through all the items:
Example
fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": break print(x)
The continue Statement
Example
fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) print(x)
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
for x in range(6): print(x) else: print("Finally finished!")
Nested Loops
A nested loop
is a loop inside a loop.
Example
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
ement to avoid getting an error.
Example
for x in[0, 1, 2]: pass