I am writing a baseball game simulation. I would like to be able to run multiple games to see how different batting averages affect outcomes. Each game is made up of "at-bats", the result of which comes from a random number.
The issue is that when I go to run multiple games, I get the same result for every game.
I imagine Python is remembering the result of the function, and just using that. I am new to Python/CS, and so have been trying to look up issues of memory, etc, but am not finding the answers I need. I appreciate any help or direction to a resource I would appreciate it. Thank you
Following is a simplified version in order to help me explain the problem. It uses just hits and outs, ending a game at 27 outs. At the end it loops through five games.
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()
The problem lies in your use of global variables.
After your game() has run for the first time, outs is 27. When you call game again, it still has the same value, so your while loop exits immediately.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With