Skip to main content
 首页 » 编程设计

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

2025年05月04日14sky-heaven

我有一段代码要求用户年龄。用户的输入是 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: 
    ...