Sometimes we want to iterate over elements of a list, set, string or such in order to perfor operations with each element. This is done using a for
statement, which looks like this
for element in list_name:
perform_first_ operation_with_element
perform_another_ operation_with_element_or_result_of_previous_operation
for
and all lines below it are aligned in the for
statement.
for
statement:¶for
element
, but we coudl have named it i
, j
, t
, n
, or any other name. As before it is useful to choose a name that will let you know what it is. in
followed by the name of the list, set, etc. from which you will take elements to perfrom the operations.:
at the end of that line.tab
or 2 or 4 spaces, write the code for first operation you want to perform using the element
.tab
or 2 or 4 spaces.for
statement, just start a line without the same horizontal spacingLet's iterate over the set of capitals and print a message saying "XXX is a capital of a country." where we will replace XXX with the name of the capital.
set_of_capitals = {'Washington, D.C.', 'Bogotá', 'Berlin'}
# Next line starts for statement
for capital in set_of_capitals:
print(capital, " is a capital of a country.")
# For statment ends