Chrome Extension

For loop python

#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)
We are a bunch of lazy programmers so we developed this chrome extension
search code from your favorite search engine
Install Now
Output
John
Sonia
Rakesh

name
title
lang

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.

Was this helpful?
1 Comments

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:

names = ["John", "Sonia", "Rakesh"]
for item in names:
    print(item)
    if item == "Sonia":
        break

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.

names = ["John", "Sonia", "Rakesh"]
for item in names:
    if item == "Sonia":
        continue
    print(item)
    

The above code will print 'John' and 'Rakesh' as output as we have applied a condition on second item.

Open Code Manager We are hiring