xxxxxxxxxx
# how to use for in python for (range, lists)
fruits = ["pineapple","apple", "banana", "cherry"]
for x in fruits:
if x == "apple":
continue
if x == "banana":
break
print(x)
# fron 2 to 30 by 3 step
for x in range(2, 30, 3):
print(x)
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
list1 = [1,'hello',2] #we've created a list
for element in list1:
print(element) #we will print every element in list1
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
adj = ["red", "big"]
fruits = ["apple", "banana"]
for x in adj:
for y in fruits:
print(x, y)
#output: red apple, red banana, big apple, big banana