Question #518

How to write a for loop in Python?

Answer

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])

5 events in history
Question by Alphonsio 12/23/2020 at 04:56:45 PM
How to write a for loop in Python?
Question by Alphonsio 12/23/2020 at 04:56:39 PM
How to create a for loop in Python?
Answer by Alphonsio 12/23/2020 at 04:56:09 PM

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])

Answer by Alphonsio 12/23/2020 at 04:53:37 PM

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])

Question by Alphonsio 12/23/2020 at 04:42:06 PM
What is the syntax of a for loop in Python?
# ID Query URL Count

Icons proudly provided by Friconix.