Python 巢狀迴圈

2021-09-25 07:12:34 字數 3576 閱讀 1359

#

巢狀迴圈

forxinrange(5

):foryinrange(5

):print

(x,end

="\t")

# \t

製表符print

("\n")

#print

天然有換行,新增\n也是換行

#列印九九乘法表

forminrange(1

,10):forninrange(1

,m+1

):print

("*=".format(m,n,m*n),

end="\t")

print()#

換行#用列表和字典儲存**資訊

r1=dict

(name

="spy",

age=18,

salary

=10000

,city

="北京")

r2=dict

(name

="py",

age=19,

salary

=20000

,city

="上海")

r3=dict

(name

="y",

age=20,

salary

=30000

,city

="深圳")

tb=[r1,r2,r3]

forxintb:

ifx.get("salary")>

20000

:print

(x)

用於while或for迴圈,中斷迴圈,跳出最近一層的迴圈

用於結束本次迴圈,繼續下一次。

#測試break,結束整個迴圈

while true:

a =

input

("請輸入乙個字元(q或q):")

ifa=="q"ora=="q":

print

("迴圈結束,退出")

break

else:

print

(a)

#測試continue,結束本次迴圈,繼續下一次

empnum=

0salarysum=

0salarys =

while true:

s =

input

("please emp salary(q or q exit):")

ifs =="q"ors=="q":

print

("錄入完畢,退出")

break

iffloat

(s) < 0:

continue

empnum +=

1float

(s))

salarysum +=

float

(s)print

("員工數".format(empnum))

print

("錄入薪資:",salarys)

print

("平均薪資:".format(salarysum/empnum))

while/for迴圈可以附帶乙個else語句。

如果while/for語句被break中斷,則會不會執行else語句,否則執行else語句

#測試for迴圈中的else語句,迴圈被中斷,else不執行;否則else執行

empnum=

0salarysum=

0salarys =

foriinrange(4

):s =

input

("please emp salary(q or q exit):")

ifs =="q"ors=="q":

print

("錄入完畢,退出")

break

iffloat

(s) < 0:

continue

empnum +=

1float

(s))

salarysum +=

float

(s)else:

#迴圈4次,迴圈未中斷,else執行;否則else不執行

print

("你已經全部錄入4名員工的薪資")

print

("員工數".format(empnum))

print

("錄入薪資:",salarys)

print

("平均薪資:".format(salarysum/empnum))

Python 迴圈巢狀

python 語言允許在乙個迴圈體裡面嵌入另乙個迴圈。python for 迴圈巢狀語法 foriterating var insequence foriterating var insequence statements s statements s python while 迴圈巢狀語法 whi...

Python 迴圈巢狀

python 語言允許在乙個迴圈體裡面嵌入另乙個迴圈。python for 迴圈巢狀語法 for iterating var in sequence for iterating var in sequence statements s statements s python while 迴圈巢狀語法...

Python 迴圈巢狀

python 語言允許在乙個迴圈體裡面嵌入另乙個迴圈。python for 迴圈巢狀語法 for iterating var in sequence for iterating var in sequence statements s statements s python while 迴圈巢狀語法...