A for-loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string) with the for-loop we can execute a set of statements, once for each item in a list, tuple, set etc.
''' eg of FL with continue Statement '''
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x) # It will only print apple because when banana comes it'll continue to statement
''' eg of FL with break Statement '''
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x) # It will only print apple because when banana comes it'll break the statement and continue to next statement
''' ForLoops in List '''
list1 = ["akash", "thor", "hulk", "mark", "tony"]
for names in list1:
print(names, end=" ")
list2 = [["akash",17], ["oliver", 18], ["rohit", 16], ["ajay", 17]]
for name,age in list2:
print(name, ", he is", age, "yrs old")
''' Program : Print all numbers greater than 6 in a List '''
lst = ["akash", 15, 17, 2, 5, "oliver", 55.4, 23, "ajay"]
for val in lst:
if str(val).isnumeric() and val>6:
print(val)
''' ForLoops in Dictionary'''
lst = [["akash",17], ["oliver", 18], ["rohit", 16], ["ajay", 17]]
dict1 = dict(lst)
for key in dict1:
print(key, ", he is",dict1[key], "yrs old")
''' OR '''
for name, age in dict1.items():
print(name, ", he is", age, "yrs old")