What is the syntax of 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 |
|---|---|---|---|---|
| 0 | 12167 | en | https://en.ans.wiki/306/what-is-the-syntax-of-a-for-loop-in-python | 6 |