【问题标题】:Python - Error with boolean condition(?)Python - 布尔条件错误(?)
【发布时间】:2017-12-07 00:13:52
【问题描述】:

嗨,

我正在尝试获取 return_3return_6return_9 以检查是否从 all_return_values_func 返回的总值> 大于 20。问题是当我运行脚本 return_3 时,它会立即打印“返回值的总数太高”。

all_return_values_func/return_value 为何在第一次运行 return_3 时计算为 20 以上?

脚本的重点是从每个 return_3/return_6/return_9 脚本开始,并将这些函数中的每一个添加到函数 all_return_values_func 中,然后检查函数值是否高于 20在函数 return_value

from sys import exit
import time

def all_return_values_func():
    combined_return_values = return_3() + return_6() + return_9()
    return combined_return_values

def return_value(i):
    if i > 20:
        print "The value is above 20"
        time.sleep(2)
        exit()



def return_3():

    return_value(all_return_values_func)    
    print "Returns integer value: 3 and then jumps to function: return_6"
    time.sleep(2)
    return_6()
    return 3


def return_6():

    return_value(all_return_values_func)    
    print "Returns integer value: 6 and then jumps to function: return_9"
    time.sleep(2)
    return_9()
    return 6

def return_9():

    return_value(all_return_values_func)
    print "Returns integer value: 9"
    time.sleep(2)
    return_3()
    return 9

return_3()

干杯,

西蒙

【问题讨论】:

  • return_value(all_return_values_func) 将函数all_return_values_func 传递给return_value,而不是all_return_values_func() 的返回值。
  • 它无法工作:P 1:return_value(all_return_values_func) - 你在传递函数引用?进而 ?将其与数字比较?这里的递归次数这么高?所有函数都将调用all_return_values_func?这也称自己?
  • “返回 x 然后跳转到函数 y”在 Python 中是不可能发生的。

标签: python return


【解决方案1】:

问题出在这里:

return_value(all_return_values_func)

您没有调用all_return_values_func,所以在return_value() 中,您正在比较函数本身 是否大于20。在您使用的Python 2.x 中,这始终是true:任何函数都大于任何整数。 (这种比较在 Python 3.x 中引发了一个错误,这大大降低了神秘性。)

解决办法是实际调用函数:

return_value(all_return_values_func())

但是,这并不是真正的解决方案,因为调用该函数会导致程序进入递归循环。 all_return_values_func() 调用 return_3() 调用 all_return_values_func() 调用 return_3() 调用 all_return_values_func()...当堆栈达到 1000 次调用深度时,Python 将抛出 RuntimeError

您的程序似乎没有做任何有用的事情,甚至没有多大意义。也许在继续之前解决这个问题。

【讨论】:

    猜你喜欢
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    • 1970-01-01
    • 2015-11-09
    • 2015-10-10
    相关资源
    最近更新 更多