我正在嘗試遍歷字典并獲得用戶回應。
在倒數第二個問題上,我想特別宣告,還有一個問題。
我無法將 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")
在用戶回答“你是誰”之后,我希望程式說“最后一個問題”。然后當程式完成時(在用戶回答最后一個問題后”,它說“沒有更多問題”。我在遍歷每個問題并增加“運行”的值時遇到了麻煩。運行此代碼不會得到預期的結果。
uj5u.com熱心網友回復:
我不確定你為什么要在這里使用 while 回圈。為什么不使用這樣的 if 陳述句:
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")
請注意,我還取消了您的最終列印陳述句的縮進,否則它將在每次迭代時執行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/477569.html
