简体   繁体   中英

Python giving same result when I call a function multiple times, despite random component

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.

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()

I have always found global to mess up sometimes but this code works and gets you different numbers. outs would always be 27 each time your game code ran, resetting them to 0 ensures your game loop will run each time

Ah, the global variables headache...

Actually, your code would work well if you reset those two globals for each loop. So:

for i in range(0,5):
    game()
    hits = 0
    outs = 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM