python - 如何让我的计数重置为循环

标签 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)

目前,当为游戏 1 的 hitsatBats 输入字母时,它会抛出异常并提示 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/

相关文章:

python - 运行Spark时遇到 "WARN ProcfsMetricsGetter: Exception when trying to compute pagesize"错误

python - 尝试制作一个基本的波长/频率转换器,大值是有问题的

java - 将 While 循环更改为 for 循环

javascript - 重命名属性名称并更改多个对象的值

c++ - for循环的索引问题

python - 使用 python 打打印新 stdout 行时出现问题

python - 将 ctypes 与 cuda 结合使用,在脚本末尾出现段错误(核心转储)错误

python - Pandas 适用于除缺失值以外的所有值

java - For循环类型比较

Java 简单的 For 循环不工作