I am trying to iterate through a dictionary and get user response.
At the second to last question, I want to specifically declare that there is one more question left.
I am having trouble combining a while statement with for loop. This is my code:
# 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")
after the user responds to "who are you", I want the program to say "on to the last question". then when the program is done (after user answers the last question", it says "no more questions". I am having trouble iterating through each question and increasing the value of 'run'. Running this code does not get the desired result.
CodePudding user response:
I'm not sure why you'd want to use a while loop here. Why not just have an if-statement like so:
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")
Note, I've also un-indented your final print statement since otherwise it will execute on every iteration.