Introduction
Python Data Types & Operators
Conditional Statements
Python Loops
Python Strings
Python Lists
Python Tuple
Python for Loop
Sometimes a programmer wants to execute a group of statements a certain number of times. This can be done using loops. Based on this loops are further classified into following types; for loop, while loop, nested loops.
for Loop
for loops can iterate over a sequence of iterable objects in python. Iterating over a sequence is nothing but iterating over strings, lists, tuples, sets and dictionaries.
Example: iterating over a string:
name = 'Hello yes'
for i in name:
print(i, end=", ")
Output:
H,e,l,l,o, ,y,e,s
Example: iterating over a tuple:
colors = ("Red", "Green", "Blue", "Yellow")
for x in colors:
print(x)
Red
Green
Blue
Yellow
Similarly, we can use loops for lists, sets and dictionaries.
What if we do not want to iterate over a sequence? What if we want to use for loop for a specific number of times?
Here, we can use the range() function.
Example:
for i in range(5):
# for is a keyword and i is a variable and in is a operator and range is a func
print("hello")
# python code range function value generate start from 0 to 4
Output:
hello
hello
hello
hello
hello