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()

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結構可能會變得更具可讀性。

TA貢獻1858條經驗 獲得超8個贊
您必須在每條input
語句后檢查用戶的輸入。每次都可以使用 if-else 語句。如果答案錯誤,打印一些內容然后使用return
,函數中剩余的代碼main()
將不會被執行。剩下的問題就不會問了。
添加回答
舉報