Python Dict 2 参数,如何用一个退出 while 循环
已经编写了下面的程序,但是如何避免系统在按下 Enter 时检查两个参数,我们使用 Enter 键退出 while 循环。
while True: # need to exit the while loop thru one <Enter>
itemcode, quantity = input("Enter item code and quantity (Press <Enter> key to end): ") .split()
if itemcode == " " : #got two argument, one enter will crash the system, how to amend it
return
if itemcode not in orderdict.keys():
print("Invalid item code! Try again.")
continue
if itemcode in orderdict.keys():
orderdict [itemcode] = orderdict
#print("{:4s} {:<3d} {:<3d} X {:<3d} ".format(itemcode, [0], [1], [3]))
else :
input ()
break
Have written below program, but how to avoid the system checking the two argument when enter is pressed, we are using the enter key to exit the while loop.
while True: # need to exit the while loop thru one <Enter>
itemcode, quantity = input("Enter item code and quantity (Press <Enter> key to end): ") .split()
if itemcode == " " : #got two argument, one enter will crash the system, how to amend it
return
if itemcode not in orderdict.keys():
print("Invalid item code! Try again.")
continue
if itemcode in orderdict.keys():
orderdict [itemcode] = orderdict
#print("{:4s} {:<3d} {:<3d} X {:<3d} ".format(itemcode, [0], [1], [3]))
else :
input ()
break
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题是,第一行是硬编码的,程序需要两个且恰好两个由空格分隔的值。如果您给它的值少于两个(并且简单地按“回车”意味着给它零值),或超过两个,这会导致回溯,因为预期的值数量不存在。
如果您不信任用户输入正确数量的值,那么我认为您可以使用 try/exception 块或重复提示用户输入的简单循环来避免崩溃直到输入的值的数量正好是 2:
Your problem is that the first line is hardcoded in such a way that the program expects two, and exactly two, values separated by a space. If you give it less than two (and simply hitting "enter" means giving it zero values), or more than two, this causes a traceback because the expected number of values isn't there.
If you don'T trust your users to enter the correct number of values, then I think you can avoid a crash either with a
try/exception
block, or a simple loop that repeats promtping the user for input until the number of entered values is exactly two:您可以开始要求用户仅输入该项目的值,并检查该值是否为回车键,然后中断循环。否则,检查该项目的值是否在键内(如果是),然后询问用户相应的数量。我认为你需要替换
orderdict
以及用户输入的商品相应的
数量
。注意:不需要编写
orderdict.keys()
,只使用字典的名称即可迭代orderdict
的键>。You can start to ask the user to enter only the value of the item and check this value if it is an enter key, then break the loop. Otherwise, check the value of the item if it is within the keys if so, then ask the user for the corresponding quantity. I think you need to replace
orderdict
with the corresponding
quantity
for the item entered by the user.Note: you do not need to write
orderdict.keys()
, you can use only the name of a dictionary to iterate through the keys oforderdict
.