python for迴圈的應用

2022-06-30 06:30:12 字數 3618 閱讀 1895

for迴圈:

1,基礎訓練

方法一例1

for i in (1,2,3,4,5,6,7,8,9,0):

print('

lpc'

)

print

(i)元素列表:

(1,2,3,4,5,6,7,8,9,0):

for迴圈會對應匹配列表裡每乙個值,直到講所有值迴圈完成結束

方法二例1

for i in range(12,16):

print

(i)結果就是12 13 14 15例2

for i in range(0,10,2):

print

(i)0-10,每次間隔2

例3for a in range(10):

for b in range(10):

print('

axiba

',end=''

)

print()

2.加強訓練

用for迴圈做三角形

一for a in range(1,6):

for b in range(i,6):

print('

# ',end=''

)

print()#

# # # #

## # #

## # ##

#二for a in range(0,6):

for b in

range(0,a):

print('

',end='')

for b in range(a,6):

print('

# ',end=''

)

print()#

# # # # #

## # # #

## # #

## # ##

#三for a in range(1,6):

for b in range(6,i+1):

print('

# ',end=''

)

print()#

# # #

## # #

## # #

## # #

## # #

四for a in range(1,8):

for b in range(1,a+1):

print('

* ',end=''

)

for b in range(a,8):

print('

# ',end=''

)

print

()* #

# # # # # #

* * #

# # # # #

* * * #

# # # #

* * * * #

# # #

* * * * * #

# #

* * * * * * #

# * * * * * * * #

五for i in range(1,10):

for j in range(1,11-i):

print('

',end='')

for j in range(1,i):

print('

@ ',end='')

print

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

for j in range(1,i):

print('

',end='')

for j in range(1,11-i):

print('

@ ',end='')

print

() @

@ @

@ @ @

@ @ @ @

@ @ @ @ @

@ @ @ @ @ @

@ @ @ @ @ @ @

@ @ @ @ @ @ @ @

@ @ @ @ @ @ @ @ @

@ @ @ @ @ @ @ @

@ @ @ @ @ @ @

@ @ @ @ @ @

@ @ @ @ @

@ @ @ @

@ @ @

@ @

@

六for a in range(1,8):

for b in range(1,a+1):

print('

# ',end=''

)

print()#

## ## #

## # #

## # # #

## # # # #

## # # # # #

七for a in range(1,8):

for b in range(a,8):

print('

',end='')

for c in range(1,a):

print('

# ',end=''

)

print

() ##

# ## #

## # #

## # # #

## # # # #

3.加強訓練

用for迴圈做乘法口決表

方法一:

for i in range(1,10):

for j in range(1,i+1):

print(str(i)+"

*"+ str(j)+"

="+str(i*j),end="")

print

()方法二:

for i in range(1,10):

for j in range(1,i+1):

print("

%d*%1d=%2d

" % (j,i,i*j) ,end='')

print()

結果:
1*1=1 

2*1=2 2*2=4

3*1=3 3*2=6 3*3=9

4*1=4 4*2=8 4*3=12 4*4=16

5*1=5 5*2=10 5*3=15 5*4=20 5*5=25

6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36

7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49

8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64

9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81

python for迴圈遍歷應用

需求 在列表中搜尋指定姓名 import json students find name str raw input 請輸入姓名 print 您輸入的是 s find name for stu dict in students if stu dict name find name print 恭喜,...

pythonfor迴圈教程 for迴圈

for迴圈 它能夠迭代任何序列的項,例如列表或字串。語法 syntax for iterating var in sequence statements s 如果序列包含表示式列表,則首先對其進行求值。然後,將序列中的第一項分配給迭代變數iterating var 接下來,執行語句塊。列表中的每個專...

python for迴圈的使用

for 變數 in range 10 迴圈需要執行的 else 迴圈結束時,需要執行的 range stop 0 stop 1 range start,stop start stop 1 range start,stop,step start stop step 步長 測試 range 5 0,1,...