如何仅从Python中的函数获取返回值? [英] How to get just the return value from a function in Python?

查看:72
本文介绍了如何仅从Python中的函数获取返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过Python学习编程,我想知道是否有可能仅获得函数的返回值而不是函数的其他部分.这是代码:

I'm trying to learn programming through Python and I like to know if it's possible to get just the return value of a function and not its other parts. Here's the code:

比方说,这是主要功能:

variable_a = 5

while variable_a > 0 :            
    input_user = raw_input(": ") 
    if input_user == "A":    
            deduct(variable_a)
            variable_a = deduct(variable_a)    
    else:
        exit(0)

然后是扣除功能:

def deduct(x):     
    print "Hello world!"  
    x = x - 1  
    return x

发生的事情是,它进行计算并进行扣除,直到 variable_a 达到 0.然而,Hello world!"被打印两次,我想是因为 variable_a = deduct(variable_a)(如果我错了,请纠正我).所以我在想,是否可以只捕获deduct()的返回值,而不捕获其余的值?这样,在这种情况下,经过deduct()之后,variable_a的纯值将为2(没有"Hello world!").

What happens is that, it does the calculation and deduct until variable_a reaches 0. However, "Hello world!" gets printed twice, I think because of variable_a = deduct(variable_a) (correct me if I'm wrong). So I was thinking, can I just capture the return value of deduct() and not capture the rest? So that in this instance, after going through deduct(), variable_a would just have a plain value of 2 (without the "Hello world!").

我想念东西吗?:?

编者注:我删除了空白行,因此可以将其粘贴到REPL.

Editor's note: I remove the blank lines, so it can be pasted to REPL.

推荐答案

打印"Hello world"是一种所谓的副作用-该功能产生的某种结果未反映在返回值中.您要问的是如何调用该函数两次,一次产生副作用,一次捕获函数返回值.

The printing of "Hello world" is what's known as a side effect - something produced by the function which is not reflected in the return value. What you're asking for is how to call the function twice, once to produce the side effect and once to capture the function return value.

实际上,您根本不必两次调用它-一次足以产生两个结果.只需捕获一次调用中的返回值即可:

In fact you don't have to call it twice at all - once is enough to produce both results. Simply capture the return value on the one and only call:

if input_user == "A":
    variable_a = deduct(variable_a)
else: 

这篇关于如何仅从Python中的函数获取返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆