Like a every programming langauge, Python has for loop to iterate a datatype of sequence. It can be array, list, set,dictionary or a string.
Perl for loop
initialization
: variable is initialized and sets intial value
Condition
: perl Condition that evaluates true and false. It is used to test whether loop continue or exit.
increment/decrement
: updated variable value by add/substract
Syntax:
for( initialization; condition;increment/decrement){
//code statements body
}
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
prices = {'apple': 0.5, 'banana': 0.25, 'cherry': 0.75}
for fruit, price in prices.items():
print(f'{fruit}: {price}')
Looping with a counter:
Copy code
# Print the numbers 0 to 9, along with their indices
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
print(f'{i}: {fruit}')
These are just a few examples of the types of for loops you can use in Python. For loops are a powerful and flexible way to iterate over a sequence of items and perform a task for each item.