![](/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.