【问题标题】:Why my function is not returning the print statement under if为什么我的函数在 if 下没有返回打印语句
【发布时间】:2021-05-20 19:09:56
【问题描述】:

x是每月繁殖1对的成熟兔子的数量,y是需要一个月才能成熟的未成熟兔子的数量,z是时间周期,以月为单位。 def Rabbits(x,y,z) 这个函数返回 None。我是新手。

def Rabbits(x,y,z):
  for m in range(z):
    if z == 0:
        return ("total number of mature rabbits are ", x, "and immature rabbits are ", y)
    else:
        x=x+y
        y=x
        z = z-1
count = Rabbits(1,1,5)

【问题讨论】:

  • 因为你的代码中没有任何print()语句,你只是返回一个str对象,如果你想打印结果,计算后写一个打印,@987654329 @
  • 您将print()return 混淆了。 return 关键字返回您列为tuple 的值。
  • 打印(计数)也不起作用
  • 显示的代码中没有count。 “打印(计数)也不起作用”是什么意思?
  • 无论我理解什么,我都通过 count = Rabbits(1,1,5) 调用该函数,并且我不需要在函数 z = z-1 中定义 count 以减少月数,所以当 z=0 时,IF 条件将起作用

标签: python return


【解决方案1】:

我认为您在不需要倒计时z

我认为你的意思是:

def Rabbits(x, y, z):
    for _ in range(z):
        x = x + y
        y = x
    return ("total number of mature rabbits are", x, "and immature rabbits are", y)

count = Rabbits(1, 1, 5)
print(count)

【讨论】:

  • 是的,这就是问题所在
  • return 语句仍然不正确,它只会返回元组。我猜你需要使用f 字符串或其他格式
  • @RustamGarayev:你怎么知道它不正确?
  • 我只是假设。 PS:我不负责downvote..
【解决方案2】:
def Rabbits(x,y,z):
    for m in range(z+1):
        if z == 0:
            return print("total number of mature rabbits are ", x, "and immature rabbits are ", y)
        else:
            y=x
            x=x+y
            z = z-1

count = Rabbits(1,1,5)
print(count)

【讨论】:

  • 您可能会注意到,在您想要的输出之后,屏幕上打印了一条额外的行——无。这是由于您在主代码中返回 print(...)`,然后是 print(count)。那是因为 print 总是返回 None。
最近更新 更多