亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果其中一條為假,如何不運行 If 語句的其余部分?

如果其中一條為假,如何不運行 If 語句的其余部分?

鴻蒙傳說 2024-01-12 10:38:01
對于以下程序,如果對任何問題的回答使用戶沒有資格投票,那么我如何讓程序立即這么說而不問剩下的問題?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()
查看完整描述

3 回答

?
臨摹微笑

TA貢獻1982條經驗 獲得超2個贊

使用嵌套的“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()


查看完整回答
反對 回復 2024-01-12
?
呼喚遠方

TA貢獻1856條經驗 獲得超11個贊

如果您以后不再需要問題的結果,您可以將 放入input條件中if并將它們與 鏈接起來and。這樣,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結構可能會變得更具可讀性。


查看完整回答
反對 回復 2024-01-12
?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

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



查看完整回答
反對 回復 2024-01-12
  • 3 回答
  • 0 關注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號