簡體   English   中英

投票If / Else / Elif

[英]Voting If/Else/Elif

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

該程序編寫良好。 我唯一要更改的想法是在檢查age >= 18等於age >= 18之后將registration = input('Are you registered to vote(Y/N)?: ')registration = input('Are you registered to vote(Y/N)?: ') (因此不會詢問用戶是否已注冊他們是否已注冊) 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()

如果您在函數內部,則可以使用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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM