简体   繁体   English

如何从函数中提取返回值并使用更新后的值?

[英]How do I extract a return value from a function and use the updated value?

I would like to get the return value from this function and assign it a variable if I put in "5" then we get 15 out but I want to keep using the updated variable afterwards in the next function.我想从这个函数中获取返回值并为其分配一个变量,如果我输入“5”然后我们得到 15,但我想在下一个函数中继续使用更新后的变量。 I would like to avoid joining the functions too.我也想避免加入这些功能。

To clarify, if you input this function then the result is 5+10 and 5+47.澄清一下,如果你输入这个函数,那么结果是 5+10 和 5+47。 What I want as an answer is 5+10 and then 15+47.我想要的答案是 5+10 然后是 15+47。

y = input("here you input your number: ") 

def this_is_function(x):
    return int(x) + 10

def this_is_function2(x):
    return int(x) + 47

this_is_function(y)
this_is_function2(y)

Currently you are ignoring the result of this_is_function (which is 15) and are just passing the same value y (which is 5) again to this_is_function2 .当前,您忽略了this_is_function (即 15)的结果,只是将相同的值y (即 5)再次传递给this_is_function2

Save the result of this_is_function in a variable instead, and pass it to this_is_function2 :this_is_function的结果保存在一个变量中,并将其传递给this_is_function2

z = this_is_function(y)        # z is 5 + 10 = 15 (y is still 5)
result = this_is_function2(z)  # result is 15 + 47

If you don't need the original y anymore, you can also reuse the y variable name instead of using a new name, z , for the intermediate result.如果您不再需要原始y ,您还可以重用y变量名称而不是使用新名称z来作为中间结果。

y = this_is_function(y)        # y is now 5 + 10 = 15 (no longer 5)
result = this_is_function2(y)  # result is 15 + 47

If you are wanting the input to the second function (equation) to be the output of the first, then you can do just that:如果您希望第二个函数(方程)的输入成为第一个函数的输出,那么您可以这样做:

y = input("here you input your number: ") 

def this_is_function(x):
    return int(x) + 10

def this_is_function2(x):
    return int(x) + 47

^leaving all this the same ^保留所有这些相同

Then using this:然后使用这个:

this_is_function2(this_is_function(y))

You can now see that the input to this_is_function2 is this_is_function(y) and the input to this_is_function is y您现在可以看到this_is_function2的输入是this_is_function(y)this_is_function的输入是y

So writing it as I would solve a math problem - and as python performs this when debugging:因此,像我解决数学问题一样编写它 - 并且在调试时 python 执行此操作:

this_is_funtion2(this_is_function(y))    # Original line
this_is_funtion2(this_is_function(5))    # y = 5
this_is_funtion2(15)                     # this_is_function(5) = 15
62                                       # this_is_function2(15) = 62

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

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