python - 我正在尝试制作用户输入字典以获得额外的学分,但我不知道如何正确结束程序
问题描述
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教育来帮助我,请帮助!
解决方案
break
只会打破内循环。为了在while
不改变太多逻辑的情况下跳出嵌套循环,您需要更改它们检查的值。
在这种情况下,同时设置bad_input
和more
toFalse
就足够了:
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
推荐阅读
- windows - Inno Setup:如何更改卸载背景颜色
- docker - 如何在 gitlab 管道中转发 .gitlab-ci ssh-add 命令?
- scala - Spark(scala)数据框 - 检查列中的字符串是否存在于另一个数据框的列中
- javascript - 如果折扣有效,lodash 按 discountPrice 排序数组
- java - 在 Google Dataproc Spark 中链接原生 .so
- python - Pandas 从列表中设置 dtype
- c++ - 是否可以将通用 lambda 作为非模板参数传递
- c++ - 如何使用 gdb 调试 g++ 分段错误?
- python - 处理列名中的括号
- python - Seaborn 图在 ipython 单元格中显示乱序