我正在尝试制作一个包含用户输入的产品和价格的字典,但是当我输入stop时它不会停止吗?这是我收到的消息:
Traceback (most recent call last):
File "C:/Users/ACER/Desktop/faks/recnici, torke, skupovi/v1.py", line 7, in <module>
y=eval(input("its price?"))
File "<string>", line 1, in <module>
NameError: name 'stop' is not defined
这是代码:
d={}
x=""
y=""
d[x]=y
while x!="stop":
x=input("product?(type stop if you want to stop)")
y=eval(input("its price?"))
d[x]=y
print(d)
答案 0 :(得分:1)
使用while True
循环,如果满足条件,则使用break
。
d={}
while True:
product = input("product?(type stop if you want to stop)")
if product == 'stop':
break
price = float(input("its price?"))
d[product] = price
print(d)
我为变量使用了更有意义的名称,根据Style Guide for Python Code设置了代码格式,并删除了eval
的危险用法。
答案 1 :(得分:0)
如果您eval
字符串"stop"
,您将得到该错误,因为stop
是无法评估的。
此外,您应该避免使用eval
来评估用户输入,因为它不安全。
d={}
x=""
y=""
while x!="stop":
x=input("product?(type stop if you want to stop)")
if x!="stop":
d[x] = float(input("price?"))
print(d)
答案 2 :(得分:0)
由于处理了输入,您可能需要稍微不同的方法来停止循环:
d = {}
while True:
x = input("product?(type stop if you want to stop)")
if x == "stop":
break
y = input("its price?")
d[x] = y
print(d)
使用while True:
,然后添加单独的测试以打破循环。
答案 3 :(得分:-1)
d = {}
x = ""
y = ""
while True:
x = input("product?(type stop if you want to stop)")
if x != "stop":
y = eval(input("its price?"))
d[x] = y
else:
break
print(d)