首页 > 解决方案 > 使用 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。

我也意识到我可能错误地处理了这个问题。最终目标是根据用户输入创建信息数据框。

标签: pythondataframeloopsdictionaryuser-input

解决方案


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'}

推荐阅读