簡體   English   中英

如果有一個錯誤,如何不運行 If 語句的其余部分?

[英]How to not run the rest of an If statement if one is false?

對於以下程序,如果對任何問題的回答使用戶沒有投票資格,那么我如何讓程序立即說出來而不是問剩余的問題?

def main():
    print("This program determines if a user is eligible to vote in the US\n")

    q1 = str(input("Are you a US citizen? y/n: "))
    q2 = int(input("What is your age?: "))
    q3 = str(input("Do you meet your state's residency requirement? y/n: "))

    if q1 == "n":
        print("\nNot eligible to vote.")
    elif q2 < 18:
        print("\nNot eligible to vote.")
    elif q3 == "n":
        print("\nNot eligible to vote.")
    else:
        q1 == "y"
        q2 >= 18
        q3 == "y"
        print("\nYou are eligible to vote!")
main()

使用嵌套的“if else”語句,當問題之一出錯時退出。 像這樣:

def main():
print("This program determines if a user is eligible to vote in the US\n")

q1 = str(input("Are you a US citizen? y/n: "))
if q1 == 'y':
    q2 = int(input('What is your age?:  '))
    if q2 > 18:
        q3 = str(input('Do you meet your states residency requirement? y/n:  '))
        if q3 == 'y':
            print("\nYou are eligible to vote!")
        else:
            print("\nNot eligible to vote.")
            exit()
    else:
        print("\nNot eligible to vote.")
        exit()
else:
    print("\nNot eligible to vote.")
    exit()
main()

如果您以后不再需要問題的結果,您可以將input放入if條件中,並用and它們鏈接起來。 這樣,如果第一個輸入已經決定了條件的結果,則不會再次詢問第二個input ,第三個input也是如此。

if (input("Are you a US citizen? y/n: ") == "y" and
        int(input("What is your age?: ")) >= 18 and
        input("Do you meet your state's residency requirement? y/n: ") == "y"):
    print("\nYou are eligible to vote!")
else:
    print("\nNot eligible to vote.")

您也可以將其與(...)or結合使用以獲得更復雜的條件,盡管在某些時候使用嵌套的if/else結構可能會變得更具可讀性。

您必須在每次input語句后檢查用戶的input 每次都可以使用 if-else 語句。 如果答案是錯誤的,打印一些東西然后使用return並且main()函數中剩余的代碼將不會被執行。 剩下的問題就不會問了。

暫無
暫無

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

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