Py学习  »  Python

方法返回None,即使在python 3中value不是None[duplicate]

Vanjith • 4 年前 • 757 次点击  

这个问题已经有了答案:

我在运行时得到输入。如果第一次尝试自己纠正给定的输入意味着我没有得到错误。否则它会显示 无法打开不可读取的 错误。

我能看到它在发送 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

我可以假设它是因为递归调用,但无法找出原因。请解释给出一个解决方案,以获得所有输入值没有错误。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/49410
 
757 次点击  
文章 [ 2 ]  |  最新文章 4 年前