gpt4 book ai didi

python - 投票 If/Else/Elif

转载 作者:太空宇宙 更新时间:2023-11-03 21:45:04 29 4
gpt4 key购买 nike

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 (所以如果用户未满 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()

关于python - 投票 If/Else/Elif,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52562991/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com