投票If / Else / Elif

时间:2018-09-28 21:44:39

标签: python if-statement

Python(和StackOverflow)的新手。试图弄清楚如何使其正确执行。虽然程序本身可以很好地执行,但我希望它没有多余的步骤。我的意思是,如果它使第一个语句失败,我想终止并打印与else语句关联的消息。

def main():

    # init
    messageOne = 'You are too young to vote.'
    messageTwo = 'You can vote.'
    messageThree = 'You need to register before you can vote.'

    # input
    age = int(input('Please enter your age: '))
    registration = input('Are you registered to vote(Y/N)?: ')

    # calculate / display
    if age >= 18:
        if registration.upper() == "Y":
            print(messageTwo)
        else:
            print(messageThree)
    else:
        print(messageOne)

main()

2 个答案:

答案 0 :(得分:0)

程序编写良好。我唯一会改变的想法是在检查registration = input('Are you registered to vote(Y/N)?: ')是否放到age >= 18之后(如果年龄小于18,则不会询问用户是否已注册)。我什么也不会改变。

def main():

    # init
    messageOne = 'You are too young to vote.'
    messageTwo = 'You can vote.'
    messageThree = 'You need to register before you can vote.'

    # input
    age = int(input('Please enter your age: '))

    # calculate / display
    if age >= 18:
        registration = input('Are you registered to vote(Y/N)?: ')
        if registration.upper() == "Y":
            print(messageTwo)
        else:
            print(messageThree)
    else:
        print(messageOne)

main()

答案 1 :(得分:0)

如果您在函数内部,则可以使用return跳过其余语句。

def main():

    # init
    messageOne = 'You are too young to vote.'
    messageTwo = 'You can vote.'
    messageThree = 'You need to register before you can vote.'

    # input
    age = int(input('Please enter your age: '))


    # calculate / display
    if age < 18:
         print(messageOne)
         return    
    registration = input('Are you registered to vote(Y/N)?: ')
    if registration.upper() == "Y":
         print(messageTwo)
         return
    print(messageThree)
    return

main()