How to create a for loop in Python?
In Python, the for loop is used for iterating over a sequence (list, dictionary, string ...). Here are examples of the most used syntaxes:
Using the range()
function:
for x in range(2, 8):
print(x)
Iterate over a list:
list = ["en", "fr", "de"]
for x in list:
print(x)
Iterate over a string:
text = "This is my string"
for x in text:
print(x)
Iterate over a dictionary:
dict = {'lastname': 'Smith', 'firstname': 'John', 'year': 1942}
for x in dict:
print(x, dict[x])
In Python, the for loop is used for iterating over a sequence (list, dictionary, string ...). Here are examples of the most used syntaxes:
Using the range()
function:
for x in range(2, 8):
print(x)
Iterate over a list:
list = ["en", "fr", "de"]
for x in list:
print(x)
Iterate over a string:
text = "This is my string"
for x in text:
print(x)
Iterate over a dictionary:
dict = {'lastname': 'Smith', 'firstname': 'John', 'year': 1942}
for x in dict:
print(x, dict[x])
In Python, the for loop is used for iterating over a sequence (list, dictionary, string ...). Here are examples of the most used syntaxes:
Using the range()
function:
for x in range(2, 8):
print(x)
Iterate over list:
list = ["en", "fr", "de"]
for x in list:
print(x)
Iterate over string:
text = "This is my string"
for x in text:
print(x)
Iterate over dictionary:
dict = {'lastname': 'Smith', 'firstname': 'John', 'year': 1942}
for x in dict:
print(x, dict[x])
# | ID | Query | URL | Count |
---|