python 带有 for 循环的 while 语句

python while statement with for loop

我正在尝试遍历字典并获取用户响应。

倒数第二题,我想特别声明一下,还有一题。

我在将 while 语句与 for 循环组合时遇到问题。这是我的代码:

# my dictionary

q_dict = {"where are we? " : "usa",
          "who are you? " : "jon",
          "how old are you? " : 22}

# my function 

def q_prompt(question, answer):

    response = input(question)

    if response != answer:

        print("incorrect")

    else:

        print("correct!")


# having trouble here with this logic combining for loop and while     

run = 1

for key, val in q_dict.items():
    
    q_prompt(key, val)
    

    while run < (len(q_dict)-1):
        print("on to the next question")
        run += 1

    else:
        print("on to the last question")  # i would like this to print when there is one more question left  

    print("no more questions")



在用户回答“你是谁”之后,我希望程序说“关于最后一个问题”。然后当程序完成时(在用户回答最后一个问题后),它说“没有更多的问题”。我无法遍历每个问题并增加 'run' 的值。运行 这段代码确实没有得到想要的结果。

我不确定您为什么要在这里使用 while 循环。为什么不像这样 if-statement:

q_dict = {"where are we? " : "usa",
          "who are you? " : "jon",
          "how old are you? " : 22}

for key, val in q_dict.items():
    
    q_prompt(key, val)
    

    if key != list(q_dict.keys())[-2]:
        print("on to the next question")

    else:
        print("on to the last question")  # i would like this to print when there is one more question left  

print("no more questions")

请注意,我还 un-indented 您的最终打印语句,否则它将在每次迭代时执行。