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

时间:2020-10-27 23:09:51

标签: python python-3.x if-statement nested

对于以下程序,如果对任何问题的回答都使用户无权投票,那么我如何使该程序立即说出来而不问其余问题?

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 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

如果以后不再需要这些问题的结果,则可以将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.") 是否已经确定了条件的结果,而第三个也是如此。

(...)

您也可以将其与orif/else结合使用,以获得更复杂的条件,尽管在某些时候使用嵌套的<nav class="hoverable"> <div> Hover me <div/> <ul class="submenu"><li>Item</li></ul> </nav> 结构可能会提高可读性。

答案 2 :(得分:0)

每个input语句后,您都必须检查用户的输入。您可以每次使用if-else语句。万一答案有误,请打印一些内容然后使用return,并且main()函数中的其余代码将不会执行。其余问题将不会被问到。

相关问题