條件控制之while和for
一。while 迴圈
1.迴圈:重複做某件事
2.語法
while 條件:
code1
3.結束while的方式:
1.條件不滿足,下次迴圈開始時判斷
2.break直接結束本層迴圈
4.while + continue
continue 之後的程式碼不會運行了,直接開始下次迴圈
n= 0
while n < 6:
if n == 4:
n+=1
continue
else:
print(n)
n+=1
5.while迴圈巢狀
while:
while:
while:
break
break
break
count = 1
tag = True
while tag:
name = input("name: ")
passwd = input("passwd ")
if count == 3:
print("too many")
break
if name == "chad" and passwd == "123":
print("successfull")
while tag:
print("""
1
2
3
""")
cho = input("choice:")
if cho == "1":
print(1)
elif cho == "2":
print(2)
else:
print(3)
tag = False
else:
print("error")
count +=1
6. while + else
如果while迴圈沒有被break打斷,才會執行
迴圈要正常結束
count = 0
while count < 3:
print(count)
count += 1
else:
print("run")
二。for 迴圈
迴圈取值簡潔
for+brek
for+continue
for+else
dic = {"name":"sdfa","age":23}
for i in dic:
print(i,dic[i])
返回字串
dic = {"name":"sdfa","age":23}
for i,r in dic.items():
print(i,r)
以字串返回key和value
dic = {"name":"sdfa","age":23}
for i in dic.items():
print(i)
以元組返回key和value,一對key,value是一個元組
range(起始,結束,步長)
取頭不取尾