【问题标题】:function either returns None or says "maximum recursion depth exceeded"函数要么返回 None 要么说“超出最大递归深度”
【发布时间】:2019-12-26 06:25:55
【问题描述】:

我正在尝试创建一个程序,该程序将采用两组随机整数,并根据这两组整数的结果打印一条语句。但是,当我调用该方法时,我要么收到“无”,要么收到“超出最大递归深度”的错误消息。我似乎无法弄清楚如何在这些方法中构建我的 return 语句,以使其正常工作。

def genre(a,b):
    genreType = random.randint(a,b)

    if genreType == '1':
        genreType = "Fantasy"
        return genre()
    elif genreType == '2':
        genreType = "Sci-Fi"
        return genre()

def medium():
    mediumType = random.randint(1,2)

    if mediumType == '1':
        genre = genre(1,2)
        print("Play a " + genre + "game")
        return medium()
    elif mediumType == '2':
        genre = genre(1,2)
        print("Watch a " + genre + "anime")
        return medium()

【问题讨论】:

  • 为什么要递归呢?为什么还要两个函数?
  • 您正在使用 mediumType = random.randint(1,2) 生成 int 值并比较字符串值 if mediumType == '1',因此无限循环在没有任何返回语句的情况下运行。
  • 这些代码行存在多个问题。 @VikasGautam 已经分享了一个。另外,genre() 方法在内部调用它时接受两个参数而不提供任何参数。

标签: python function


【解决方案1】:

首先,如果一个函数有一个没有return的分支,它将返回None,例如:

def something():
    if False:
        return "Thing"
    # There is no return in "else"

print(something()) # None

第二,数字与字符串的比较永远不会成功:

print(1 == 1) # True
print(1 == '1') # False

所以你提供的例子只能总是返回None


第三,你没有从你的函数中返回任何有意义的东西:

def genre(a,b):
    genreType = random.randint(a,b)

    if genreType == '1':
        genreType = "Fantasy"
        return genre() # call this function again, but with no parameters, why?!

如果条件有机会为真,你会得到

TypeError: genre() missing 2 required positional arguments: 'a' and 'b'

我只能猜到你是故意的:

    if genreType == 1:
        genreType = "Fantasy"
        return genreType

或者,更短且可读性更强:

def genre(a,b):
    genreType = random.randint(a,b)

    if genreType == 1:
        return "Fantasy"
    elif genreType == 2:
        return "Sci-Fi"
    # And you can add your own error to know what exactly went wrong
    else:
       raise Exception("Genre bounds must be between 1 and 2")

【讨论】:

  • 这很有帮助。我需要将字符串与整数进行比较以及返回genreType 而不是genre() 的问题。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-01
  • 1970-01-01
  • 2017-03-24
  • 2011-12-31
  • 2017-08-09
  • 2011-03-31
相关资源
最近更新 更多