![](/img/trans.png)
[英]Copy the result of a function as a class variable or call it multiple times Python
[英]Python giving same result when I call a function multiple times, despite random component
我正在写一个棒球比赛模拟。 我希望能够运行多个游戏,看看不同的击球平均值如何影响结果。 每个游戏都由“蝙蝠”组成,其结果来自随机数。
问题在于,当我去运行多个游戏时,每个游戏都会得到相同的结果。
我想Python正在记住函数的结果,只是使用它。 我是Python / CS的新手,所以一直试图查找内存等问题,但我找不到我需要的答案。 我感谢任何帮助或对资源的指导我会很感激。 谢谢
以下是简化版本,以帮助我解释问题。 它只使用了点击率,结束了27场比赛。 最后它循环了五场比赛。
import random
hits = 0
outs = 0
# determine whether player (with .300 batting average) gets a hit or an out
def at_bat():
global hits
global outs
number = random.randint(0,1000)
if number < 300:
hits +=1
else:
outs += 1
# run at_bat until there are 27 outs
def game():
global hits
global outs
while outs < 27:
at_bat()
else:
print "game over!"
print hits
# run 5 games
for i in range(0,5):
game()
问题在于你使用全局变量。
在游戏()第一次运行后,输出为27.当您再次呼叫游戏时,它仍具有相同的值,因此您的while循环立即退出。
import random
# determine whether player (with .300 batting average) gets a hit or an out
def game():
global hits
global outs
hits = 0
outs = 0
while outs < 27:
hits, outs = at_bat()
else:
print("game over!")
print(hits)
def at_bat():
global hits
global outs
number = random.randint(0,1000)
if number < 300:
hits += 1
else:
outs += 1
return hits, outs
# run 5 games
for i in range(0,5):
game()
我总是发现全局有时会陷入困境,但这段代码可以运行并为您提供不同的数字。 每次游戏代码运行时, outs
总是27,将它们重置为0可确保每次运行游戏循环
啊,全球变数令人头疼......
实际上,如果为每个循环重置这两个全局变量,您的代码将运行良好。 所以:
for i in range(0,5):
game()
hits = 0
outs = 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.