【问题标题】:python 3 try/except exiting rather than loopingpython 3 try/except 退出而不是循环
【发布时间】:2015-11-13 08:16:11
【问题描述】:

我不确定我在这里做错了什么。我正在尝试将用户输入限制为 1-6(骰子游戏)。逻辑正常,但是当引发 ValueError() 时,它不会再次提示用户。

try:
    while True:
        choice = input('Enter number to hold - type D to roll: ')
        print(choice)
        if choice == 'D':
            return choice_list
        elif len(choice) > 1 or choice not in '12345':
            raise ValueError()
        else:
            choice_list[int(choice) - 1] = 'X'
            printer(roll_list, choice_list)
except ValueError:
    print ("Invalid input")

【问题讨论】:

    标签: python-3.x try-except


    【解决方案1】:

    因为您要在 Exception 处退出循环。你应该写这样的代码:

    while True:
        try:
            choice = input('Enter number to hold - type D to roll: ')
            print(choice)
            if choice == 'D':
                return choice_list
            elif len(choice) > 1 or choice not in '12345':
                raise ValueError()
            else:
                choice_list[int(choice) - 1] = 'X'
                printer(roll_list, choice_list)
        except ValueError:
            print ("Invalid input")
    

    【讨论】:

    • 谢谢 - 非常有帮助
    【解决方案2】:

    在 try 代码之前使用 while 循环,这样会不断循环 try 和 catch 块

    while True:
       try:
         # Your Code
    
       except ValueError:
         # Your Code
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      • 2021-12-13
      • 2019-06-26
      • 1970-01-01
      相关资源
      最近更新 更多