xxxxxxxxxx
text = "Hello World"
for i in text:
print(i)
#Output
#H, e, l, l, o, , W, o, r, l, d
for i in range(10):
print(i)
#1, 2, 3, 4, 5, 6, 7, 8, 9, 10
xxxxxxxxxx
# if you want to get items and index at the same time,
# use enumerate
fruits = ['Apple','Banana','Orange']
for indx, fruit in enumerate(fruits):
print(fruit, 'index:', indx)
xxxxxxxxxx
# print (Hello !) 5 Times.
#(i) it's a name For Variable So You Can Replace it with any name.
for i in range(5):
print("Hello !")
xxxxxxxxxx
# For loop where the index and value are needed for some operation
# Standard for loop to get index and value
values = ['a', 'b', 'c', 'd', 'e']
print('For loop using range(len())')
for i in range(len(values)):
print(i, values[i])
# For loop with enumerate
# Provides a cleaner syntax
print('\nFor loop using builtin enumerate():')
for i, value in enumerate(values):
print(i, value)
# Results previous for loops:
# 0, a
# 1, b
# 2, c
# 3, d
# 4, e
# For loop with enumerate returning index and value as a tuple
print('\nAlternate method of using the for loop with builtin enumerate():')
for index_value in enumerate(values):
print(index_value)
# Results for index_value for loop:
# (0, 'a')
# (1, 'b')
# (2, 'c')
# (3, 'd')
# (4, 'e')
xxxxxxxxxx
for c in "banana":
print(c)
xxxxxxxxxx
scores = [70, 60, 80, 90, 50]
filtered = []
for score in scores:
if score >= 70:
filtered.append(score)
print(filtered)
Code language: Python (python)
xxxxxxxxxx
words=['zero','one','two']
for operator, word in enumerate(words):
print(word, operator)