PythonFor Loops are used for iterating over a sequence like lists, tuples, strings, and ranges.
- For loop allows you to apply the same operation to every item within loop.
- Using For Loop avoid the need of manually managing the index.
- For loop can iterate over any iterable object, such as dictionary, list or any custom iterators.
For Loop Example:
Pythons=["Geeks","for","Geeks"]# using for loop with stringforiins:print(i)
Flowchart of Python For Loop
For Loop flowchartPython For Loop Syntax
for var in iterable:
# statements
pass
Note:In Python, for loopsonlyimplement thecollection-based iteration.
Python For Loop with String
This code uses a for loop to iterate over astring and print each character on a new line. The loop assigns each character to the variable i and continues until all characters in the string have been processed.
Pythons="Geeks"foriins:print(i)
Using range() with For Loop
Therange() function is commonly used with for loops to generate a sequence of numbers. It can take one, two, or three arguments:
- range(stop): Generates numbers from 0 to stop-1.
- range(start, stop): Generates numbers from start to stop-1.
- range(start, stop, step):Generates numbers from start to stop-1, incrementing by step.
Pythonforiinrange(0,10,2):print(i)
Control Statements with For Loop
Loop control statements change execution from their normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.
Continue with For Loop
Pythoncontinue Statement returns the control to the beginning of the loop.
Python# Prints all letters except 'e' and 's'foriin'geeksforgeeks':ifi=='e'ori=='s':continueprint(i)
Break with For Loop
Pythonbreak statement brings control out of the loop.
Pythonforiin'geeksforgeeks':# break the loop as soon it sees 'e'# or 's'ifi=='e'ori=='s':breakprint(i)
Pass Statement with For Loop
Thepass statement to write empty loops. Pass is also used for empty control statements, functions, and classes.
Python# An empty loopforiin'geeksforgeeks':passprint(i)
Else Statement with For Loops
Python also allows us to use theelse condition for loops. The else block just after for/while is executed only when the loop is NOT terminated by a break statement.
Pythonforiinrange(1,4):print(i)else:# Executed because no break in forprint("No Break\n")
Using Enumerate with for loop
In Python,enumerate() function is used with the for loop to iterate over an iterable while also keeping track of index of each item.
Pythonli=["eat","sleep","repeat"]fori,jinenumerate(li):print(i,j)
Output0 eat1 sleep2 repeat
Nested For Loops in Python
This code uses nested for loops to iterate over two ranges of numbers (1 to 3 inclusive) and prints the value of i and j for each combination of these two loops. \
The inner loop is executed for each value of i in outer loop. The output of this code will print the numbers from 1 to 3 three times, as each value of i is combined with each value of j.
Pythonforiinrange(1,4):forjinrange(1,4):print(i,j)
Output1 11 21 32 12 22 33 13 23 3
Python For LoopExercise Questions
Below are two Exercise Questions on Python for-loops. We have covered continue statement and range() function in these exercise questions.
Q1.Code to implement Continue statement in for-loop
Pythona=["shirt","sock","pants","sock","towel"]b=[]foriina:ifi=="sock":continueelse:print(f"Washing{i}")b.append("socks")print(f"Washing{b}")
OutputWashing shirtWashing pantsWashing towelWashing ['socks']
Q2.Code to implement range function in for-loop
Pythonforiinrange(1,8):d=3+(i-1)*0.5print(f"Day{i}: Run{d:.1f} miles")
OutputDay 1: Run 3.0 milesDay 2: Run 3.5 milesDay 3: Run 4.0 milesDay 4: Run 4.5 milesDay 5: Run 5.0 milesDay 6: Run 5.5 milesDay 7: Run 6.0 miles
Test Your Knowledge -Python For Loop Quiz