这是我的代码:
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)
目前,当为游戏 1 的 hits
或 atBats
输入字母时,它会抛出异常并提示 Please enter a number,
但它会直接进入游戏 2,而不会让用户有机会为游戏 1 输入新的内容。
我想知道是否有任何方法可以在抛出异常时重置游戏计数。
最佳答案
使用 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
关于python - 如何让我的计数重置为循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32729158/