简体   繁体   English

在Python中,当执行`if`语句时,如何从函数返回值?

[英]In Python, how do I return a value from a function when an `if` statement is executed?

In this function, I want to return a value when the if statement is executed. 在此函数中,我想在执行if语句时返回一个值。

Since Python always returns something, it returns None . 由于Python总是返回某些内容,因此它返回None

def Persistence(number, counter):
    numArr = [int(i) for i in str(number)]
    result = 1
    data = None
    for j in numArr:
        result *= j
    if len(str(number)) == 1:
        data = str(f'Done. {counter} steps taken')
        print(data)
        # return data
    else:
        counter = counter + 1
        Persistence(result, counter)
    # return data

print(Persistence(333,0))

Maybe I put the return keyword in the wrong place (I checked by putting it in two different places, marked as a comment) or something else, but I couldn't figure it out. 也许我将return关键字放在错误的位置(我通过将其放在两个不同的位置进行检查,标记为评论)或其他方式,但是我无法弄清楚。

Please help me out. 请帮帮我。 Also, if there is another way to count the recursion steps besides my technique, please let me know. 另外,如果除我的技术外还有其他方法可以计算递归步骤,请告诉我。

Maybe try this : 也许试试这个:

def Persistence(number, counter):
    numArr = [int(i) for i in str(number)]
    result = 1

    for j in numArr:
        result *= j
    if len(str(number)) == 1:
        return str(f'Done. {counter} steps taken')

    counter = counter + 1
    return Persistence(result, counter)

print(Persistence(333,0))

Hope it helps 希望能帮助到你

The issue is that you're not setting the value from the else call to persistence to anything. 问题在于您没有将else调用中的值设置为persistence The following code return the data value for me: 以下代码为我返回了数据值:

def Persistence(number, counter):
    numArr = [int(i) for i in str(number)]
    result = 1
    data = None
    for j in numArr:
        result *= j
    if len(str(number)) == 1:
        data = str(f'Done. {counter} steps taken')
        print(data)
        return data
    else:
        counter = counter + 1
        data = Persistence(result, counter)
    return data

x = Persistence(333, 0)

Then if we print x: 然后,如果我们打印x:

print(x)
# Done. 3 steps taken

Your logic to count the recursion steps is basically correct, you just need to place the return statements for both the: 1)Base case 2)The recursive call itself 您计算递归步骤的逻辑基本上是正确的,您只需要为以下两者放置return语句:1)基本情况2)递归调用本身

The following modification to your code will do the trick of what you are asking: 对代码的以下修改将实现您所要求的技巧:

def Persistence(number, counter):
    numArr = [int(i) for i in str(number)]
    result = 1
    data = None
    for j in numArr:
        result *= j
    if len(str(number)) == 1:
        data = str(counter)
        return data
    else:
        counter = counter + 1
        return Persistence(result, counter)


print(Persistence(333,0))

The above code will return the output of: 上面的代码将返回以下内容的输出:

3

Please note that the reason you were getting "None" as the output in your original code is because you were not making a return at the actual recursive call itself: **return** Persistence(result, counter) 请注意,您在原始代码中获得“ None”作为输出的原因是因为您没有在实际的递归调用本身上**return** Persistence(result, counter)**return** Persistence(result, counter)

So when you ran print(Persistence(333,0)) it was returning nothing resulting in the None . 因此,当您运行print(Persistence(333,0))它什么也没有返回,从而导致None

This question is better to learn about recursion than you may think. 要想了解递归,这个问题比您想象的要好。 But we won't muddy the waters by mixing recursion (functional style) with statements and side effects (imperative style). 但是,我们不会通过将递归(功能样式)与语句和副作用(命令式样式)混合使用来弄混。

It looks like you're trying to calculate multiplicative root and persistence. 看来您正在尝试计算乘法根和持久性。 Instead of putting all concerns of the computation into a single function, break it down into sensible parts - 与其将计算的所有关注点放在一个函数中,不如将其分解为明智的部分-

def digits (n = 0):
  if n < 10:
    return [ n ]
  else:
    return digits (n // 10) + [ n % 10 ]

def product (n = 0, *more):
  if not more:
    return n
  else:
    return n * product (*more)

def mult_root (n = 0):
  if n < 10:
    return [ n ]
  else:
    return [ n ] + mult_root (product (*digits (n)))

def mult_persistence (n = 0):
  return len (mult_root (n)) - 1

print (mult_persistence (333))
# 3

print (mult_root (333))
# [ 333, 27, 14, 4 ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM