问题描述
我写这篇文章是作为 Python 练习。该循环应该接受用户输入并使用 eval 函数对其进行评估,并在用户输入 done 时中断循环。返回输入 done 之前的输入。
def eval_loop():
while True:
x = ('done')
s = (input("write a thing. "))
s1 = s
print(eval(s))
if s == x:
break
return s1
eval_loop()
该代码适用于 5、10 + 3 等输入。但是当我输入 done 作为输入时,我得到这个错误:
Traceback (most recent call last):
File "C:/Users/rosem/Progs/1101D4.py",line 11,in <module>
eval_loop()
File "C:/Users/rosem/Progs/1101D4.py",line 6,in eval_loop
print(eval(s))
File "<string>",line 1,in <module>
NameError: name 'done' is not defined
解决方法
你不能这样评价“文本”。老实说,我建议您无论如何不要将 eval 用于此类问题。但如果必须,您可以切换顺序并尝试/捕获。
def eval_loop():
while True:
x = ('done')
s = input("write a thing. ")
s1 = s
#check if input is 'done'
if s == x:
break
else:
try:
#evaluate
print(eval(s))
#error caused by s being something like 'foo'
except NameError:
pass
return s1
eval_loop()
,
发生 NameError: name 'done' is not defined
是因为您在使用 done
之前没有检查输入是否为 eval
。而是试试这个:
def eval_loop():
while True:
s = (input("write a thing. "))
s1 = s
if s == 'done':
break
print(eval(s))
return s1
eval_loop()
如果不检查,python 会尝试“运行”done
,从而引发错误。
另请参阅 Brain 的评论和其他答案。