繁体   English   中英

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

[英]How to stop a while loop with a user input?

我正在尝试使用用户输入的产品和价格制作字典,但是当我输入停止时它不会停止? 这是我得到的消息:

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)

使用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)

我为变量使用了更有意义的名称,根据Python 代码风格指南格式化代码并删除了eval的危险使用。

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

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

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:然后添加一个单独的测试来打破循环。

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM