为了账号安全,请及时绑定邮箱和手机立即绑定

如果其中一条为假,如何不运行 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 关注
  • 46 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信