For Loop in Python is usually Used to iterating over a sequence of list, a tuple, a dictionary, a set, or a string. Syntax of for loop in python is for and it works more like an iterator method as found in other object-orientated programming languages. The for loop does not require an indexing variable to set beforehand. Here is My simple Example of for loop in python.
stds = ["std1", "std2", "std3"] for x in stds: print(x)
Looping Through a String in Python
You can use strings as iterable objects, they contain a sequence of characters. Here is My Example.
for x in "sid": print(x)
Output Will Be like this.
s i d
Statement Used in For Loop in Python
The break Statement
With the break statement we can stop the loop before it has looped through all the items. Exit the loop when
x is “mango”
fruits = ["mango", "graps", "pineple"] for x in fruits: print(x) if x == "mango": break
The continue Statement
With the continue statement we can stop the current iteration of the loop, and continue with the next. Here in Example my cenario is Do not print mango.
fruits = ["mango", "graps", "pineple"] for x in fruits: if x == "mango": continue print(x)
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.
for x in range(8): print(x)
Here is Second Example of range().
for x in range(2, 6): print(x)
Else in For Loop
else keyword in a
for loop specifies a block of code to be executed when the loop is finished. Print all numbers from 0 to 6, and print a message when the loop has ended.
for x in range(7): print(x) else: print("finished!")
A nested loop is a loop inside a loop. The “inner loop” will be executed one time for each iteration of the “outer loop”.
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.
for x in [0, 1, 2]: pass
So This is all About for loop. Hope This tutorial may help you to understand For loop. Thank you.