1. 程式人生 > 實用技巧 >python--if,while,break,continue

python--if,while,break,continue

if

你在生活中是不是經常遇到各種選擇,比如玩色子,猜大小,比如走那條路回家。python程式中也會遇到這種情況,這就用到了if語句

_username = 'zou'
_password = 'abc123'
username = input("username:")
password = input("password:")
if _username == username and _password == password:
    print("Welcome user {name} login...".format(name=username))
else:
    print("
Invalid username or password!")
money = int(input("請輸入你兜裡的錢:"))
if money > 500:
    print("吃啤酒吃炸雞. 生活美滋滋")
elif money > 300:
    print("蓋澆飯走起")
elif money > 50:
    print("方便麵走起")
else:
    print("減肥走起")

while

在生活中,我們遇到過迴圈的事情吧?比如迴圈聽歌,在程式中,迴圈也是存在的,

count=0
while True:
    print("count:",count)
    count
=count+1

陷入了死迴圈,在實際專案中要避免出現死迴圈,True的T必須是大寫

age_of_oldboy = 56
while True:
    guess_age = int(input('guess age:'))
    if guess_age == age_of_oldboy:
        print("yes, you got it. ")
    elif guess_age > age_of_oldboy:
        print("think smaller...")
    else:
        print("thing bigger...
")

一直可以輸入,對或錯都不結束

age_of_oldboy = 56
while True:
    guess_age = int(input('guess age:'))
    if guess_age == age_of_oldboy:
        print("yes, you got it. ")
        break
    elif guess_age > age_of_oldboy:
        print("think smaller...")
    else:
        print("thing bigger...")

加了個break,輸入正確時退出
break 結束迴圈. 停止當前本層迴圈

age_of_oldboy = 56
count = 0
while count < 3:
    guess_age = int(input('guess age:'))
    if guess_age == age_of_oldboy:
        print("yes, you got it. ")
        break
    elif guess_age > age_of_oldboy:
        print("think smaller...")
    else:
        print("thing bigger...")
    count = count + 1

輸錯三次退出迴圈

age_of_oldboy = 56
count = 0
while count < 3:
    guess_age = int(input('guess age:'))
    if guess_age == age_of_oldboy:
        print("yes, you got it. ")
        break
    elif guess_age > age_of_oldboy:
        print("think smaller...")
    else:
        print("thing bigger...")
    count = count + 1
else:
    print("you have tried too many times...")

當程式正常執行完會執行最後一個else,如果中間遇到break,不執行else

while True:
    s = input("請開始說:")
    if s == 'q':
        break  # 停止當前迴圈
    # 過濾掉馬化騰
    if "馬化騰" in s:  # 在xxx中出現了xx
        print("你輸入的內容非法. 不能輸出")
        continue  # 停止當前本次迴圈.繼續執行下一次迴圈
    print("噴的內容是:" + s)
count = 1
while count <= 10:
    print(count)
    count = count + 1
    if count == 5:
        break  # 徹底停止迴圈. 不會執行後面的else
else:  # while條件不成立的時候執行
    print("這裡是else")

continue:停止本次迴圈,繼續執行下一次迴圈