首页 > 解决方案 > 无法读取空输入,应将刷新设置为 60,改为出现错误

问题描述

refresh = int(input('REFRESH (secs/enter=60s): '))
if refresh == '':   
    refresh = 60

ValueError: int() 以 10 为底的无效文字:''

当我输入 int 值时,我没有收到错误,但是我认为当我输入“无”时这应该可以工作

标签: python

解决方案


这是因为您正在混合变量类型。不要将文本输入转换为refresh,而是将其int保留为字符串,以便您可以检查空字符串。然后在您完成检查转换为int(Python 在某些情况下会为您进行这种转换,而其他时候您必须自己明确地进行转换,我已将两者都包含在下面的代码中)。

refresh = input('REFRESH (secs/enter=60s): ')
print(type(refresh))

if refresh == '':  # here you are comparing a string with an empty string
    refresh = 60   # here Python does the conversion for you
else:
    refresh = int(refresh) # here you explicitly change the string to an int
    
print(refresh)
print(type(refresh))

推荐阅读