我正在创建一个函数,该函数从一个问题接收一个介于1到5之间的数字(李克特量表)。当用户输入错误的INT时,我的循环正常,该问题重复。但是我想重复这个问题,如果用户也输入了一个字符串。但是在那种情况下,程序会崩溃“ ValueError:int()以10为底的无效文字”
def likert(msg):
while True:
L = int(input(msg))
if 1 <= L <= 5 and type(L) == int:
return L
elif L < 1 or L > 5:
print('\033[031mError [1 to 5] only\033[m')
continue
答案 0 :(得分:1)
不是立即尝试将输入抽象为int
,而是这样做:
def likert():
while True:
L = input()
if L.isalpha:
#if input is string
print('\033[031mError [1 to 5] only\033[m')
continue
elif L.isdigit:
#if input is int
if 1 <= L <= 5:
#if input is within range
return L
else:
#if input is out of range
print('\033[031mError [1 to 5] only\033[m')
continue
答案 1 :(得分:0)
您先将L强制转换为int,然后再检查其类型。因此,当L是字符串时,您的程序尝试将其强制转换为int并崩溃。仅当确定L不是字符串时,才应执行数字运算。解决方案是使用try and catch或使用if语句处理它。
答案 2 :(得分:0)
int()
始终返回整数,因此type(L) == int
始终为true。如果用户键入的内容不是有效的整数,则int()
将表示错误。
如果用户输入的不是整数,请使用try/except
处理错误。
def likert(msg):
while True:
try:
L = int(input(msg))
except ValueError:
print('\033[031mError [1 to 5] only\033[m')
continue
if 1 <= L <= 5:
return L
else:
print('\033[031mError [1 to 5] only\033[m')
您不需要elif
,因为该条件与if
条件相反;使用else
。您也不需要continue
,因为它在循环的结尾,并且无论如何都将继续。