Loop through range
Case #1
# Loop through a range of numbers
# starting from 0 to 4
# as range(n) return number from 0 to n-1
for i in range(5):
print(i)
PythonOutput:
0
1
2
3
4
PlaintextCase #2
# Loop through a range of numbers
# starting from 5 to maximum 19(=20-1), and each step is 3 numbers
for i in range(5, 20, 3):
print(i)
PythonOutput:
5
8
11
14
17
PlaintextLoop through Tuple
items = (5, 10, 15, 20, 25, 30)
for i in items:
print(i)
PythonOutput:
5
10
15
20
25
30
PlaintextLoop through Set
items = {5, 10, 15, 20, 25, 30}
for i in items:
print(i)
PythonOutput:
20
5
25
10
30
15
PlaintextLoop through List items
Case #1
for i in [5, 10, 15, 20, 25, 30]:
print(i)
PythonOutput:
5
10
15
20
25
30
PlaintextCase #2
We can enumerate a list and loop through it to get the key and value-
items = [5, 10, 15, 20, 25, 30]
for key, value in enumerate(items):
print(f"Key: {key} || Value: {value}")
PythonOutput:
Key: 0 || Value: 5
Key: 1 || Value: 10
Key: 2 || Value: 15
Key: 3 || Value: 20
Key: 4 || Value: 25
Key: 5 || Value: 30
PlaintextCase #3
Let’s see how we can find the largest number of a list using a for loop-
# Array of positive integers
items = [523, 687, 271, 99, 401, 178, 366, 836, 290, 730, 444, 123, 76, 357, 456, 679]
# Initialize with 0
largestNum = 0
# Loop through the array
# and try to find the largest number
for item in items:
if item > largestNum:
largestNum = item
# For debugging purpose
print("largestNum is updated to: ", largestNum)
print("\n\nLargest number: ", largestNum)
PythonOutput:
largestNum is updated to: 523
largestNum is updated to: 687
largestNum is updated to: 836
Largest number: 836
PlaintextCase #4
We can also calculate the sum of the numbers looping through the numbers by looping though each item and adding that to the sum-
# Array of integers
items = [523, 687, 271, 99, 401, 178, 366, 836, 290, 730, 444, 123, 76, 357, 456, 679]
# Initialize with 0
total = 0
# Loop through the array
# and calcualte the sum
for item in items:
total += item
print("Total value: ", total)
PythonOutput:
Total value: 6516
PlaintextLoop through Dictionary items
Case #1
# Dictionary of capitals of different countries
country_capitals = {
"United Kingdom": "London",
"France": "Paris",
"Germany": "Berlin",
"Japan": "Tokyo",
"China": "Beijing",
"India": "New Delhi",
"Russia": "Moscow",
"Australia": "Canberra",
"United States": "Washington, D.C.",
"Canada": "Ottawa",
}
# Loop through the dictionary items
for country, capital in country_capitals.items():
print(f"Country: {country} || Capital: {capital}.")
PythonOutput:
Country: United Kingdom || Capital: London.
Country: France || Capital: Paris.
Country: Germany || Capital: Berlin.
Country: Japan || Capital: Tokyo.
Country: China || Capital: Beijing.
Country: India || Capital: New Delhi.
Country: Russia || Capital: Moscow.
Country: Australia || Capital: Canberra.
Country: United States || Capital: Washington, D.C..
Plaintext