该python有效,但是正在寻找更优雅的解决方案(尝试并使用1/0 hack进行捕获)

时间:2018-10-10 15:36:37

标签: python python-3.x

我正试图阻止用户输入超过玩家人数的团队成员。

while True:
    try:
        numMembers = int(input("How many students per team (2, or 3) "))
        if numMembers > totalStudents:
            errorHand = 1/0
    except:
        print("Too many members per team, please try again")
        continue
    else:
        break

只是想避免我想出的骇客div / 0技巧。

1 个答案:

答案 0 :(得分:4)

由于在每种错误情况下都需要做一些不同的事情,因此没有太多的复杂性可以解决,但是您可以将try减少到特定位置的特定异常并避免除以零黑客:

while True:
    try:
        numMembers = int(input("How many students per team (2, or 3) "))
    except ValueError:
        continue

    if numMembers > totalStudents:
        print("Too many members per team, please try again")
        continue

    break