如何使我的计数重置for for循环

时间:2015-09-23 00:27:41

标签: python for-loop

这是我的代码:

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)

目前,当第一场为hitsatBats输入一封信时,它会抛出异常并说Please enter a number,但它会直接进入游戏2而不会给用户一个机会输入第1场的新输入。

我想知道在抛出异常时是否有任何重置游戏计数的方法。

3 个答案:

答案 0 :(得分:4)

使用while循环在输入无效时运行,并在输入时发生。

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

答案 1 :(得分:1)

您可以尝试不同的方法并使用while循环,创建一个名为 i 的变量,并在发生错误时重置它:

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

答案 2 :(得分: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