Looping in Python provides a feasible way to deal with each element of an object for particular operations using just a single block of statements. A for loop handling a list in Python creates a temporary variable first, then do a series expected operation with the block. Although the temporary variable name can be chosen with any string just like naming any other objects in Python, it is often identified with a single variable with respect to a list with chosen plural names. The following example shows each member of a list ‘member’ is printed out with a for loop.
members = ['Shirley', 'Wilson', 'Dudu','Maomao','Mico','Mia','Miaomiao']
for member in members:
print(member)
#output
Shirley
Wilson
Dudu
Maomao
Mico
Mia
Miaomiao
Just note that Python uses 4 space indentation for a loop, similar as for function definition.
With a for loop, we can also do a little more on elements of list. For example, each member’s name title form is concatenated with extra strings into a sentence, before they are printed out.
members = ['Shirley', 'Wilson', 'Dudu','Maomao','Mico','Mia','Miaomiao']
for member in members:
print(member.title() + ", you are welcome")
print("I can't wait to see your combing back, " + member.title() + ".\n")
print("Thank you everyone, that was a great meeting!")
#output
Shirley, you are welcome
I can't wait to see your combing back, Shirley.
Wilson, you are welcome
I can't wait to see your combing back, Wilson.
Dudu, you are welcome
I can't wait to see your combing back, Dudu.
Maomao, you are welcome
I can't wait to see your combing back, Maomao.
Mico, you are welcome
I can't wait to see your combing back, Mico.
Mia, you are welcome
I can't wait to see your combing back, Mia.
Miaomiao, you are welcome
I can't wait to see your combing back, Miaomiao.
Thank you everyone, that was a great meeting!
And you can see that the last statement has no indentation on the left side, so it does not belong to the for loop block. This sentence is printed out only once.
0 Comments