Python-如何防止变量在循环期间丢失?

时间:2018-12-15 05:24:12

标签: python

我目前正在学习Python,为期三天;这是《用Python自动化乏味的东西-来自Al Sweigarts的面向初学者的实用编程》一书中的一个非常基本的程序,我自己做了一些改进。

import random
import sys
#
def getAnswer(answerNumber):
 if answerNumber == 1:
    return 'no'
 elif answerNumber == 2:
    return 'yes'
#
print("Yes or no questions will be answerd. To end the program, enter 'exit'")
while True:
 resposta = input ()
 if resposta == 'exit':
  print ('goodbye')
  sys.exit()
 print(getAnswer(random.randint(1, 2)))

但是让我感到困扰的是,每次循环重新启动时,变量都会丢失,因此,如果同一问题被问到两次,则会给出不同的答案。我该如何解决? (我尝试使用全局语句没有成功)

1 个答案:

答案 0 :(得分:2)

假设您不想为同一问题显示不同的输出。这可能会对您有所帮助。

我已将问题及其答案添加到历史字典中,因此每次输入新问题时,都会存储该问题,并且在重复相同问题时,答案将不会改变。这是代码。

import random
import sys

history = {} # History Dictionary

def add_to_history(resposta, answer): # New addition
    history.update({resposta: answer})

def getAnswer(answerNumber):
 if answerNumber == 1:
    return 'no'
 elif answerNumber == 2:
    return 'yes'

print("Yes or no questions will be answerd. To end the program, enter 'exit'")

while True:

 resposta = input()
 if resposta == 'exit':
  print ('goodbye')
  sys.exit()

 # Check if the question has been answered before
 if resposta in history.keys():
     print("printing from history")
     print(history[resposta])
 # If not then create a new answer
 else:
     print("getting answer")
     answer = getAnswer(random.randint(1, 2))
     print(answer)
     add_to_history(resposta, answer)

这里就是行动

Does the sun rise in the east?
getting answer
no
Did my program work?
getting answer
yes
Does the sun rise in the east?
printing from history
no