Like every programming language, Python has a for loop to iterate a datatype of sequence. It can be an array, list, set, dictionary, or string.
Python for loop
initialization
: variable is initialized and sets the initial value
Condition
: Python condition that evaluates true and false. It is used to test whether the loop continues or exits.
increment/decrement
: updated variable value by add/subtract
Syntax:
for( initialization; condition;increment/decrement){
//code statements body
}
Python loops
Looping through a range of numbers:
- Print the numbers 0 to 9
for index in range(5):
print(5)
Looping through a list:
- Print the elements of a list
numbers = ['one', 'two', 'three']
for number in numbers:
print(number)
Looping through a string:
- Print each character in a string
s = 'hello'
for c in s:
print(c)
Looping through a dictionary:
Copy code
# Print the keys and values of a dictionary
emps = {'john': 1, 'eric': 2, 'mark': 3}
for name, id in emps.items():
print(f'{name}: {id}')
Looping with a counter:
# Print the numbers 0 to 9, along with their indices
numbers = ['one', 'two', 'three']
for i, number in enumerate(numbers):
print(f'{i}: {number}')
These are just a few examples of the types of for loops you can use in Python. Loops are a powerful and flexible way to iterate over a sequence of items and perform a task for each item.