A Butler
A Butler

Reputation: 99

How to make my count reset on for loops

Here is my code:

for count in range(1,numGames+1):
    print()
    try:
        print("Game", str(count))
        atBats = input("How many at bats did the player have? ")
        atBats = int(atBats)
        hits = input("How many hits did the player have? ")
        hits = int(hits)
        battingAverage = (hits / atBats)
    except Exception as err:
        print("Please enter a number")
        print(err)

Currently, when a letter is entered for hits or atBats for Game 1, it throws the exception and says Please enter a number, but it goes right to Game 2 without giving the user a chance to enter a new input for Game 1.

I would like to know if there is any way where it resets the game count when an exception is thrown.

Upvotes: 4

Views: 6409

Answers (3)

Shawn Mehan
Shawn Mehan

Reputation: 4568

You were close. Try this:

count = 1
play = True # instead of the for loop use a while until you set it to false
while play:
    print "Game #%d" % count
    try:
        atBats = int(input("How many at bats did the player have?"))
    except Exception as err:
        print "You need to enter a number for at bats"
        continue # this will start the while loop over, missing counts += 1
    try:
        hits = int(input("How many hits did the player have?"))
    except Exception as err:
        print "You need to enter a number for hits"
        continue
    battingAverage = hits / atBats
    print "Your batting average is %d" % battingAverage
    count += 1

Upvotes: 1

spaceisstrange
spaceisstrange

Reputation: 25

You can try a different approach and use a while loop instead, creating a variable called i and reseting it when the error happens:

numGames = 5 # This is an example, take your variable instead
i = 1
while i < numGames:
    print()
    try:
        print("Game",str(i))
        atBats=input("How many at bats did the player have? ")
        atBats=int(atBats)
        hits=input("How many hits did the player have? ")
        hits=int(hits)
        battingAverage=hits/atBats
        i = i + 1
    except Exception as err:
        print("Please enter a number")
        print(err)
        i = 1

Upvotes: 1

Carlos H Romano
Carlos H Romano

Reputation: 626

Use a while loop to run while the input isn't valid and breaks out when it is.

for count in range(1,numGames+1):
    print()
    while True:
        try:
            print("Game",str(count))
            atBats=input("How many at bats did the player have? ")
            atBats=int(atBats)
            hits=input("How many hits did the player have? ")
            hits=int(hits)
            battingAverage=hits/atBats
        except Exception as err:
            print("Please enter a number")
            print(err)
            continue
        break

Upvotes: 4

Related Questions