#LOOP THROUGH LIST
names = ["John", "Sonia", "Rakesh"]
for item in names:
print(item)
#LOOP THROUGH DICTIONARY
my_dict = {
"name": "John",
"title": "Programmer",
"lang": "Python"
}
for key in my_dict:
print(key, "is: ", my_dict[key])
# Loop through list of dictionaries
subjects = [
{ "name": "English", "score": 90 },
{ "name": "Math", "score": 100 },
{ "name": "Physics", "score": 90 }
]
for subject in subjects:
print("Subject Name is: ", subject['name'], " Score is: ", subject['score'])
For loop in python is very simple to understand. In the above code snippets, we are printing names that exist in the list. We are using for loop to print them. The 'item' keyword will get each name that exists in the names list one by one.
You can also use break and continue keywords in python to break the loop or to skip an iteration
Break a loop
The 'break' keyword is used to break the iterations of 'for loop' in python. You can understand it with the below code:
So if item equals to 'Sonia', the loop iterations will not execute further. So the above code will output only 'John' and 'Sonia'.
Skip an iteration using continue statement
You can skip an iteration using 'continue' keyword. The below code will skip the iteration if the name is Sonia.
The above code will print 'John' and 'Rakesh' as output as we have applied a condition on second item.