如何使用用户输入停止while循环?

2024-05-04 21:26:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着用用户输入的产品和价格来制作一本字典,但当我输入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)

Tags: 用户in信息input字典产品evalline
3条回答

如果你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)

如果满足条件,则使用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格式化代码,并删除了^{}的危险用法。你知道吗

由于处理输入,可能需要稍微不同的方法来停止循环:

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:,然后添加一个单独的测试来中断循环。你知道吗

相关问题 更多 >