簡體   English   中英

初學者Python-在循環中使用字符串或變量進行回答

[英]Beginner Python - Answering with either a string or a variable in a loop

到目前為止,我的代碼:

prompt = "\nEnter 'quit' when you are finished."
prompt += "\nPlease enter your age: "

while True:
    age = input(prompt)
    age = int(age)

    if age == 'quit':
        break
    elif age <= 3:
        print("Your ticket is free")
    elif age <= 10:
        print("Your ticket is $10")
    else:
        print("Your ticket is $15")

除非您輸入“退出”以結束循環,否則程序運行正常。 我知道age = int(age)將用戶輸入定義為整數。 我的問題是如何將其更改為不將“ quit”視為整數,並在輸入“ quit”時結束循環。

如果age'quit' ,您還是會破產。 因此,您可以將if用作下一個。 只要您這樣做,之后就可以將其設置為int, if

while True:
    age = input(prompt)

    if age == 'quit':
        break
    age = int(age)

    if age <= 3:
        print("Your ticket is free")
    elif age <= 10:
        print("Your ticket is $10")
    else:
        print("Your ticket is $15")

但是,當用戶鍵入其他內容時,您應該注意那些情況,所以我建議以下幾點:

while True:
    age = input(prompt)

    if age == 'quit':
        break
    elif not age.isdigit():
        print("invalid input")
        continue

    age = int(age)

    if age <= 3:
        print("Your ticket is free")
    elif age <= 10:
        print("Your ticket is $10")
    else:
        print("Your ticket is $15")

實際上,我會在這里介紹一個try/except

您的應用程序的主要目標是收集年齡。 因此,用try / except包裹您的輸入,以始終獲取整數。 如果收到ValueError ,則進入異常塊並檢查是否輸入quit

該應用程序將告訴用戶它正在退出並退出。 但是,如果用戶未輸入quit ,而是輸入其他字符串,則會提示您該輸入無效,並且它將繼續詢問用戶有效年齡。

同樣,為了確保您不會錯過任何可能用不同大小寫鍵入的“退出”消息,您可以始終將輸入設置為lower以始終比較字符串中的相同大小寫。 換句話說,當您檢查要quit的條目時,請使用age.lower

這是一個工作示例:

prompt = "\nEnter 'quit' when you are finished."
prompt += "\nPlease enter your age: "

while True:
    age = input(prompt)
    try:
        age = int(age)
    except ValueError:
        if age.lower() == 'quit':
            print("Quitting your application")
            break
        else:
            print("You made an invalid entry")
            continue

    if age <= 3:
        print("Your ticket is free")
    elif age <= 10:
        print("Your ticket is $10")
    else:
        print("Your ticket is $15")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM