python: for loop

 for loop can iterate any sequence of items, such as a list or a string.

Example 1: custom string


fruits = '5 apples, pears 4'
for I in Fruits:
Print (I)



operation result:

 

Example 2: a custom list

 

List = [ 'apple', 'pear'] 
for I in List:
Print (I)

 

operation result:

 

 

Example 3: Digital output 1-9

 

 

for i in range(1,10):
print(i)

 

operation result:

 

Thinking Development:

Case 1:

fruits = '5 apples, pears 4, 3 watermelon, cantaloupe 6, three peach, orange 7'

The total number of cycles to use for statistics fruit

 

fruits = '5 apples, pears 4, 3 watermelon, cantaloupe 6, three peach, orange 7' 
the Sum = 0
for I in Range (len (Fruits)):
IF Fruits [I] == ' a ':
the Num = int (Fruits [-I. 1])
the Sum + = the Sum the Num
Print (the Sum)

 

operation result:

 

Case 2:

For loop 9 outputs the multiplication table 9 *

for i in range(1,10):
for j in range(1,10):
print('%d*%d=%d\t' %(i,j,i*j),end='')
print()

 

show result:

 

 

 

 



















Guess you like

Origin www.cnblogs.com/my-essay/p/11078972.html