首页 > 解决方案 > 我正在尝试制作用户输入字典以获得额外的学分,但我不知道如何正确结束程序

问题描述

my_dict = dict()
more = True
while more:
  bad_input = True

  while bad_input:
    user_input = input("Enter key and value seperated buy commas(,):")
    result = user_input.find(',') 
    print ("Substring ',' found at index:", result )

    if result != -1 and user_input != 'quit':
      bad_input = False
      key , value = user_input.split(",")
      key = key.strip()
      value = value.strip()
      my_dict[key] = value
      print (my_dict)
  if user_input == 'quit':
    print(my_dict)
    break

这是我的代码,我需要它在用户输入字典中找到“,”,并且当您键入“退出”时,程序需要结束。我的老师没有受过足够的python教育来帮助我,请帮助!

标签: pythonloopsif-statementwhile-loopexit

解决方案


break只会打破内循环。为了在while不改变太多逻辑的情况下跳出嵌套循环,您需要更改它们检查的值。

在这种情况下,同时设置bad_inputmoretoFalse就足够了:

if user_input == 'quit':
    print(my_dict)
    more = False
    bad_input = False

话虽如此,您甚至不需要两个循环。使用单个while然后您将能够使用break

my_dict = dict()
while True:
    user_input = input("Enter key and value separated buy commas(,):")
    result = user_input.find(',')
    print("Substring ',' found at index:", result )

    if result != -1 and user_input != 'quit':
        bad_input = False
        key , value = user_input.split(",")
        key = key.strip()
        value = value.strip()
        my_dict[key] = value
        print (my_dict)
    if user_input == 'quit':
        print(my_dict)
        break

推荐阅读