簡體   English   中英

在Python中,else塊可以有更多if-elif-else塊嗎?

[英]In Python , can else block have further if-elif-else blocks?

電影票:電影院根據人的年齡收取不同的票價。 如果未滿3歲,則免費提供門票; 如果介於3到12之間,則票價為10美元; 如果他們的年齡超過12歲,則票價為15美元。 編寫一個循環,在其中詢問用戶年齡,然后告訴他們電影票的價格。

我希望該程序具有退出價值。 我本可以使用0作為退出值,但我想使用“ quit”。

prompt = "What is your age? "
prompt += "\nEnter 'quit' to close program."

age = 0

while True:


     age = raw_input(prompt)
        if age == 'quit':
            break
        else:
            age = int(age)
            if age < 3:
                print("The movie ticket is FREE for you.")
            elif 3 <= age < 12:
                print("The movie ticket is $10 for you.")
            elif age >= 12:
                print("The movie ticker is $15 for you.")

我想指出,您不需要else子句。 您可以將其他條件語句包含在先前的縮進級別中,因為break退出循環,而不是繼續循環的其余部分。

而不是

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

只是:

    if age == 'quit':
        break

    age = int(age)

如果不清楚,這里是整個程序進行了更改:

prompt = "What is your age? "
prompt += "\nEnter 'quit' to close program."

while True:

    age = raw_input(prompt)
    if age == 'quit':
        break

    age = int(age)
    if age < 3:
        print("The movie ticket is FREE for you.")
    elif 3 <= age < 12:
        print("The movie ticket is $10 for you.")
    elif age >= 12:
        print("The movie ticker is $15 for you.")

我還刪除了無用的分配: age = 0因為該值在可以被讀取之前被age = raw_input(prompt)取代。

是的,您可以根據需要嵌套if語句,但是我總是首先嘗試尋找一種更好的方法。 在這種情況下,我們可以使用while語句的條件部分。

age = 0
while age != "quit":
    age = raw_input(prompt)
    age = int(age)
    if age < 3:
        print("The movie ticket is FREE for you.")
    elif 3 <= age < 12:
        print("The movie ticket is $10 for you.")
    elif age >= 12:
        print("The movie ticker is $15 for you.")

現在,只要age不等於"quit" ,代碼就會循環播放。

您可以使用try:通過輸入othert值(而不是整數)來避免腳本崩潰。

prompt = "What is your age? [quit to Exit the program] : "
while True:
     age = raw_input(prompt)
     if age == 'quit':
        break
     try:
        age = int(age)
        if age < 3:
            print("The movie ticket is FREE for you.")
        elif 3 <= age < 12:
            print("The movie ticket is $10 for you.")
        elif age >= 12:
            print("The movie ticker is $15 for you.")
     except:
        print 'Invalid Age entered !!!'
        pass

暫無
暫無

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

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