gpt4 book ai didi

python - 更清晰的代码来绕过在 Python 中打印 Int 值

转载 作者:太空宇宙 更新时间:2023-11-04 07:27:06 25 4
gpt4 key购买 nike

我有一段代码要求用户年龄。用户的输入是 int 类型。此外,如果用户不想输入任何内容,他们只需按“Enter”退出程序(如下):

print("What is your age?")
answer = int(input())
if answer == '':
print("Don't want to disclose? That's fine.")

但是,当我按下 Enter 时,出现以下错误:

Traceback (most recent call last):
File "C:/Users/test/PycharmProjects/exceptions/testinput.py", line 2, in <module>
answer = int(input())
ValueError: invalid literal for int() with base 10: ''

Process finished with exit code 1

我知道我可以做一个 try block 并且代码像下面我想要的那样工作:

print("What is your age?")
try:
answer = int(input())
if answer == '':
print()
except ValueError:
print("Don't want to disclose? That's fine.")

我的问题是,除了 try block 之外,还有其他方法可以打印 int 类型的空白值吗?

最佳答案

当然:转换为 int 之前检查输入:

answer = input("What is your age? ")
if answer == '':
print("Don't want to disclose? That's fine.")
else:
...

关于python - 更清晰的代码来绕过在 Python 中打印 Int 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57169921/

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