为了账号安全,请及时绑定邮箱和手机立即绑定

这个 python 可以工作,但正在寻找更优雅的解决方案

这个 python 可以工作,但正在寻找更优雅的解决方案

UYOU 2021-07-09 13:01:43
我试图阻止用户输入超过玩家池的团队成员数量。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只是想避免我想出的 hackity div/0 技巧。
查看完整描述

1 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

由于您需要在每个错误情况下做一些不同的事情,因此可以消除的复杂性并不多,但是您可以将 减少try到特定位置的特定异常并避免除以零 hack:


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


查看完整回答
反对 回复 2021-07-13
  • 1 回答
  • 0 关注
  • 131 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信