python - 使用 Python 中的 if/then 语句从用户输入创建字典
问题描述
新的 Python 学习者在这里。我到处寻求帮助,但似乎找不到解决问题的方法。我想根据用户输入创建字典,但对于某些变量,我想包含 if/then 或 while 语句,以便跳过与用户输入无关的问题。到目前为止,这是我的代码示例:
input_dict = {'var1': input('Question 1:\n'),
'var2': input('Question 2:\n'),
'var3': input('Question 3:\n'),
'var4': input('Question 4:\n')}
我想做的是创建一个循环,如果问题 3 的答案是“否”,那么它将跳过问题 4。
我也意识到我可能错误地处理了这个问题。最终目标是根据用户输入创建信息数据框。
解决方案
for
如果问题编号为 3 且答案为“否”,您可以创建一个-loop 并中断:
input_dict = {}
for question in range(1, 5):
ans = input("Question {}:".format(question))
input_dict["var{}".format(question)] = ans
if question == 3 and ans == "no":
break
print(input_dict)
印刷:
Question 1:yes
Question 2:yes
Question 3:no
{'var1': 'yes', 'var2': 'yes', 'var3': 'no'}
推荐阅读
- python - 在子目录上运行 Python 脚本
- python - Django 表单处理 div 中的字段
- java - 从没有在springboot JPA中定义bean的mongodb获取所有集合数据
- python - 如何在不影响顺序的情况下将列表数组转换为项目数组?
- hyperledger-fabric - 向 Hyperledger Fabric 中的 RAFT 排序服务添加新的排序节点
- angular - 在一项服务中创建多个行为主体
- solrj - 是否可以针对具有较低版本(7.7)的 Solr 服务器使用 Solrj(版本 - 8.x)客户端库?
- c++ - Qt 获取不同操作系统的默认样式表
- angular - Angular 9,滚动恢复/锚滚动不适用于异步数据加载
- python - Python Tkinter 提交按钮