如果其中一条为假,如何不运行 If 语句的其余部分?

对于以下程序,如果对任何问题的回答使用户没有资格投票,那么我如何让程序立即这么说而不问剩下的问题?


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


鸿蒙传说
浏览 51回答 3
3回答

临摹微笑

使用嵌套的“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':&nbsp; &nbsp; q2 = int(input('What is your age?:&nbsp; '))&nbsp; &nbsp; if q2 > 18:&nbsp; &nbsp; &nbsp; &nbsp; q3 = str(input('Do you meet your states residency requirement? y/n:&nbsp; '))&nbsp; &nbsp; &nbsp; &nbsp; if q3 == 'y':&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("\nYou are eligible to vote!")&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("\nNot eligible to vote.")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; exit()&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print("\nNot eligible to vote.")&nbsp; &nbsp; &nbsp; &nbsp; exit()else:&nbsp; &nbsp; print("\nNot eligible to vote.")&nbsp; &nbsp; exit()main()

呼唤远方

如果您以后不再需要问题的结果,您可以将 放入input条件中if并将它们与 链接起来and。这样,input如果第一个条件已经决定了条件的结果,则不会再次询问第二个条件,第三个条件也是如此。if (input("Are you a US citizen? y/n: ") == "y" and&nbsp; &nbsp; &nbsp; &nbsp; int(input("What is your age?: ")) >= 18 and&nbsp; &nbsp; &nbsp; &nbsp; input("Do you meet your state's residency requirement? y/n: ") == "y"):&nbsp; &nbsp; print("\nYou are eligible to vote!")else:&nbsp; &nbsp; print("\nNot eligible to vote.")您还可以将其与(...)或结合起来or以获得更复杂的条件,尽管在某些时候使用嵌套if/else结构可能会变得更具可读性。

猛跑小猪

您必须在每条input语句后检查用户的输入。每次都可以使用 if-else 语句。如果答案错误,打印一些内容然后使用return,函数中剩余的代码main()将不会被执行。剩下的问题就不会问了。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python