【问题标题】:Why is the function printing the first two lines before calling it?为什么函数在调用它之前打印前两行?
【发布时间】:2020-07-09 13:37:13
【问题描述】:

对 python 非常陌生,我正在学习定义和调用函数。

def function4(x): 然后将其输出定义为变量m 时,它会在我调用它之前打印函数的前两行。然后当我调用该函数时,它只显示return 值。我的印象是除非专门调用function4(x),否则在def function4(x): 下缩进的任何内容都不会被执行?

例子:

def function4(x):
    print(x)
    print("still in this function")
    return 3*x

m = function4(5)

print("BREAK")
print(m)

输出:

    5
    still in this function
    BREAK
    15

    Process finished with exit code 0

感谢您的宝贵时间!

【问题讨论】:

  • 但是......你确实打电话给它,就在那里:m = function4(5)
  • 是的,C.Nivs 为我回答了这个问题,并帮助我理解了我的错误。感谢您的意见,我感谢这个社区!

标签: python python-3.x function return


【解决方案1】:

你是对的,这个函数在你调用它之前不会执行。不过,您在这里调用它:

m = function4(5)

所以您的打印语句在正确的位置执行。您将m 设置为function4(5) 返回的值。

print 不调用任何东西。它只是打印你给控制台的字符串表示形式:

# a simple function to demonstrate
def f(x):
    print("I am ", x)
    return x

# I have not called f yet
print('Hello! ')

# I have printed the *function* f, but I still have not called it
# note the lack of parentheses
print('Here is a function: ', f)

print('We will call it now!')

# *Now* I am calling the function, as noted by the parentheses
x = f(1)

print('I have returned a value to x: ', x)

它将执行以下操作:

Hello!
Here is a function:  <function f at 0x7fa958141840>
We will call it now!
I am  1
I have returned a value to x:  1

【讨论】:

  • 好吧,也许这就是我没有得到的。我想通过添加m = function4(5) 只是说m 现在将成为function4(5) 的输出。我认为调用m 的唯一方法是像我在下面所做的那样:print(m)
  • 它确实做到了这一点,我认为您只是将调用函数的位置放在错误的位置。通过执行m = function4(5),您将名称m 分配给值function4(5),其计算结果为15。这发生在分配给m的过程中
  • 好的,这就是我感到困惑的地方。我以为我在输入m = function4(5)只是设置了m 变量我没有意识到我正在调用它并且同时将它设置为一个变量.
  • 是的!调用函数的唯一方法是使用括号。如果您希望m 可调用,您可以执行m = function4 之类的操作,因为这不会调用该函数,所以现在mfunction4 的另一个名称,为您提供执行m(5) 的能力,再次评估为15
  • 啊!就在那里!好的好的,我现在明白了!我只需要在轮子上涂一点油脂就可以让它们转动。当我应该将变量设置为函数名称(不调用它)时,我不小心调用了该函数。非常感谢,这正是我不明白的!你是我 20 年 3 月 28 日当天的英雄!我对社区太陌生了,无法给你点赞,但请知道我做到了!
【解决方案2】:

首先,如果你想知道你的代码是如何工作的,我强烈建议你使用http://pythontutor.com/javascript.html#mode=edit,如果你是 Python 新手,这非常有用。

那么,对于您的代码,您在声明m 变量时调用了该函数,这就是为什么首先出现两个print 语句的原因。 返回值只有在你打印函数时才会出现,这就是为什么会出现数字 15,因为你在写 print(m) 时已经打印了它。

希望这可以帮助你,Goobye 然后祝你好运!

【讨论】:

  • 另外,我没有意识到print(m) 只会显示函数的return 部分。谢谢你。
猜你喜欢
  • 1970-01-01
  • 2013-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 2019-10-01
  • 2018-09-01
  • 1970-01-01
相关资源
最近更新 更多