windstorm2002
windstorm2002

Reputation: 23

Why is my while loop not breaking when it should

I am currently trying to make a program that runs a simulation where a baseball player has an 81% chance of hitting the ball, and the goal is for the baseball player to get 56 hits in a row. I have it set up so that it will run a million repetitions of this, but it should stop if the player gets 56 or more hits in a row, and will print the attempt number that the player hit 56 hits in a row. However, for some reason, my for loop does not stop when the number of total hits is at least 56 (The predicted probability is much lower than 1/1000000). Why is my loop not breaking correctly?

import random
attempts = 0
totalhits = 0
def baseball():
    totalhits = 0
    hit = 1
    while hit == 1:
        odds = random.randint(1,100)
        if odds <= 81:
            hit = 1
            totalhits = totalhits + 1
        else:
            hit = 0
    return totalhits

for i in range(1,1000000):
    baseball()
    if totalhits >= 56:
        break
    attempts = attempts + 1

print("Attempt " + str(attempts) + " succeeded.")

The result is consistently Attempt 999999 succeeded

Upvotes: 1

Views: 90

Answers (2)

Poojan
Poojan

Reputation: 3519

  • you need to capture the value your are returning from baseball.Or use global.
  • The variable totalhits you used inside baseball function is not same as you declared in global level.
  • Read more about variable scope in python to understand better.
import random
attempts = 0
totalhits = 0
def baseball():
    totalhits = 0
    hit = 1
    while hit == 1:
        odds = random.randint(1,100)
        if odds <= 81:
            hit = 1
            totalhits = totalhits + 1
        else:
            hit = 0
    return totalhits

for i in range(1,1000000):
    totalhits  = baseball()
    if totalhits >= 56:
        break
    attempts = attempts + 1

print("Attempt " + str(attempts) + " succeeded.")

Solution 2 : Using global

import random
attempts = 0
totalhits = 0
def baseball():
    global totalhits
    totalhits = 0
    hit = 1
    while hit == 1:
        odds = random.randint(1,100)
        if odds <= 81:
            hit = 1
            totalhits = totalhits + 1
        else:
            hit = 0

for i in range(1,1000000):
    baseball()
    if totalhits >= 56:
        break
    attempts = attempts + 1

print("Attempt " + str(attempts) + " succeeded.")

Upvotes: 1

NiKS
NiKS

Reputation: 377

You are not returning 'totalhits' from your function. So, everytime you compare the value of 'totalhits', you are comparing it with the initial value of 0.

You can change the for loop as

for i in range(1,1000000):
     totalhits = baseball()
     if totalhits >= 56:
         break attempts = attempts + 1

to get the desired result.

Upvotes: 0

Related Questions