I have been working on a project to evaluate baseball statistics. I am working on a program that simulates a full game of baseball. For the program, I have created a function called at-bat that takes in a player's on-base percentage and determines whether or not the player gets on base, or gets out. I have created a while loop that says while outs is not equal to 27, continue the program. However, most of the time, the program gets stuck in an infinite loop, completely ignoring the while condition. I believe that there is some disconnect between what the variable assignment should be and what it actually is, however, I am not sure what I am missing. Any feedback would be greatly appreciated.
import random
first= {"obp": 383, "avg": 310}
second= {"obp": 370, "avg": 295}
third= {"obp": 465, "avg": 313}
fourth= {"obp": 351, "avg": 261}
fifth= {"obp": 281, "avg": 221}
sixth= {"obp": 314, "avg": 210}
seventh= {"obp": 297, "avg": 262}
eighth= {"obp": 337, "avg" : 269}
ninth= {"obp": 317, "avg": 277}
order = [first, second, third, fourth, fifth, sixth, seventh, eighth, ninth]
outs=0
total_runs=0
on_base=0
game_log=[]
def at_bat(player):
x=random.randint(1,1000)
if player["obp"] >= x:
print("ON BASE: " str(on_base))
return "on_base"
else:
print("OUTS: " str(outs))
return "out"
while outs != 27:
for a in order:
if at_bat(a)=="on_base":
on_base =1
else:
outs =1
print("Outs = " str(outs))
print("ON base = " str(on_base))```
CodePudding user response:
The loop goes through each a
in order
then checks if it's not equal to outs once it's gone through the whole list. Because there is a possibility outs
gets incremented twice during the for
loop, you get into an infinite loop as outs
skips past 27
If you want to stop as soon as outs
reaches 27, regardless if all items in order
have been traversed, you can do this
i = 0
while outs != 27:
a = outs[i]
if at_bat(a)=="on_base":
on_base =1
else:
outs =1
i = 1
# Return to the first item
if i == len(outs):
i = 0