How to make my account reset enabled for cycles

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 hitsor atBatsfor game 1, it throws an exception and says Please enter a number,, but it goes directly to Game 2, preventing the user from entering a new input for Game 1.

I would like to know if there is a way by which it resets the game score when an exception is thrown.

+4
source share
3 answers

Use the while loop to start while the input is invalid and break 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
+4
source

You can try a different approach and use the while loop instead, creating the variable i and iterating over it when an error occurs:

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
+1

. :

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
+1

Source: https://habr.com/ru/post/1608604/


All Articles