1. 程式人生 > >第12節 while循環

第12節 while循環

small mes print ESS 條件 break 結果 bsp while

例1
count=0
while True:
print("count:",count)
count=count+1 // count+=1
輸出結果:
count: 230033
count: 230034
count: 230035
count: 230036
count: 230037
count: 230038
count: 230039
count: 230040
例2:
age_of_oldboy=56
count=0
while True:
if count==3 :
break
guess_age=int(input("guess_age:"))
if age_of_oldboy==guess_age:
print("yes,you got it")

break
elif age_of_oldboy>guess_age:
print("think smaller")
else:
print("think older")
count+=1
輸出結果:
guess_age:56
yes,you got it


例3:
age_of_oldboy=56
count=0
while count<3 : //不要忘記:,在這裏直接隱含著等於3的時候break,執行了3次
guess_age=int(input("guess_age:"))
if age_of_oldboy==guess_age:
print("yes,you got it")

break
elif age_of_oldboy>guess_age:
print("think smaller")
else:
print("think older")
count+=1
輸出結果:
guess_age:1
think smaller
guess_age:58
think older
guess_age:56
yes,you got it


例4:
age_of_oldboy=56
count=0
while count<3 :
guess_age=int(input("guess_age:"))
if age_of_oldboy==guess_age:

print("yes,you got it")
break
elif age_of_oldboy>guess_age:
print("think smaller")
else:
print("think older")
count+=1
else:
print("you have tried too many times!") //如果while的條件符合 就輸出while裏面的,如果不符合就輸出you have tried too many times!


輸出結果:
guess_age:1
think smaller
guess_age:2
think smaller
guess_age:3
think smaller
you have tried too many times!

輸出結果:
guess_age:1
think smaller
guess_age:56
yes,you got it //沒有輸出you have tried too many times!

第12節 while循環