Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-如何防止变量在循环过程中丢失?_Python - Fatal编程技术网

Python-如何防止变量在循环过程中丢失?

Python-如何防止变量在循环过程中丢失?,python,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 questio

我目前正在学习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)))

但每次循环重新启动时,变量都会丢失,这让我很烦恼,因此,如果同样的问题被问两次,可以给出不同的答案。我怎样才能解决这个问题?(我尝试过使用全局语句,但没有成功)

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

我已经将问题及其答案添加到历史词典中,因此每次输入新问题时,都会将其存储起来,当重复相同的问题时,答案不会改变。这是密码

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

变量丢失了?您希望实现什么?您只需使用随机数为1或2的
getAnswer()
函数。没有什么会丢失的!只是随机回答,它可以是1或2两次random@StephenRauch我可能使用了错误的术语,但我想说的是,属性化的随机数没有被保留,所以如果我两次输入同一个问题,我可能会得到不同的答案,我不希望这种情况发生。我想编写代码,让程序对相同的输入总是给出相同的答案。