即使在python 3中value不是none,方法也返回None

时间:2019-06-01 21:32:15

标签: python python-3.x exception recursion

我在运行时得到输入。如果第一次尝试本身输入正确,则表示我没有收到错误。否则,它显示无法解压不可重复错误。

如果递归方法调用一次,我可以看到它正在发送None。即使它在返回之前也打印值,但是在接收后却显示None。

class Game:
    def set_val(self):
        try:
            p1=input("Enter player 1 name:")
            p2=input("Enter player 2 name:")
            goal=int(input("Enter a number to set goal:"))
            if p1 is None or p2 is None or goal is None:
                print("Please give proper input")
                self.set_val()
            else:
                print(p1,p2,goal)
                return p1,p2,goal
        except:
            print("Please give proper input")
            self.set_val()
G=Game()

p1,p2,goal=G.set_val()
print(p1,p2,goal)

输出:

Enter player 1 name:s
Enter player 2 name:c
Enter a number to set goal:s
Please give proper input
Enter player 1 name:s
Enter player 2 name:v
Enter a number to set goal:2
s v 2
Traceback (most recent call last):
  File "D:\test.py", line 18, in <module>
    p1,p2,goal=G.set_val()
TypeError: cannot unpack non-iterable NoneType object

由于递归调用,我可以假定它,但无法弄清楚原因。请说明给出一种解决方案,以获取所有输入值而不会出现错误。

2 个答案:

答案 0 :(得分:2)

1)切勿执行一般性异常以捕获所有内容。

2)您不应将递归用于用户输入。它无缘无故地消耗了堆栈。只需使用while循环即可。基本上,递归不旨在在发生某些故障时继续重复。它旨在潜入某些物体并最终返回。

3)确保您正确地放置了代码。这没有引起问题,但是确实使代码难以阅读。运算符前后应有一个空格(即=),多个元素逗号之间应有一个空格(即(1, 2, 3)

话虽如此,当您进行递归时,您需要返回递归调用:

class Game:
    def set_val(self):
        try:
            p1 = input("Enter player 1 name:")
            p2 = input("Enter player 2 name:")
            goal = int(input("Enter a number to set goal:"))
            if p1 is None or p2 is None or goal is None:
                print("Please give proper input")
                return self.set_val()
            else:
                print(p1, p2, goal)
                return p1, p2, goal
        except:
            print("Please give proper input")
            return self.set_val()
G = Game()

p1, p2, goal = G.set_val()
print(p1, p2, goal)

也可以将您的if缩写为:

if p1 and p2 and goal:

答案 1 :(得分:2)

递归有其用途,但是使用递归不是其中之一。赤裸裸也很糟糕。

如果需要循环,请使用循环。

如果需要捕获异常,请捕获 expected 异常。这样,如果发生意外的异常,您可以查看并处理该错误。

示例:

class Game:
    def set_val(self):
        while True:
            p1=input("Enter player 1 name:")
            if p1: break
        while True:
            p2=input("Enter player 2 name:")
            if p2: break

        # Loop until good input
        # int() will throw ValueError if input is not convertible to int.
        while True:
            try:
                goal=int(input("Enter a number to set goal:"))
                break # break from the loop if no exception
            except ValueError:
                print("Please give proper input")

        return p1,p2,goal

G=Game()

p1,p2,goal=G.set_val()
print(p1,p2,goal)