简体   繁体   English

打印 void function 执行 function

[英]Printing a void function executes function

I wrote a function that takes in a number and prints its square.我写了一个 function 接受一个数字并打印它的平方。 When I used the print function and passed the function-with 2 as its input- as the print function's argument, the output was 4 and 'None'.当我使用 print function 并将函数(输入为 2)作为 print 函数的参数传递时,output 为 4 且为“无”。

'None' I can understand, but why did Python execute the function and output 4 here? 'None'我能理解,但是为什么Python会在这里执行function和output 4? I had only used a print statement.我只使用了打印语句。

Presumably you have something like this:大概你有这样的事情:

>>> def square(n):
...   print(n ** 2)
... 
>>> print(square(2))
4
None

You don't have a return statement so python returns None .您没有返回语句,因此 python 返回None Try this instead:试试这个:

>>> def square(n):
...   return n ** 2
... 
>>> print(square(2))
4

The reason why the 4 got printed is becuase you called square() .打印4的原因是因为您调用square() Calling square had the side-effect of printing the square since that's what it's definition body says to do.调用 square 有打印正方形的副作用,因为这是它的定义正文所说的。

By placing the () next to the function, you called it.通过将()放在 function 旁边,您调用了它。 So it got executed.所以它被执行了。 The print statement around it caused the return value None to be printed, while inside it printed the square.它周围的 print 语句导致返回值None被打印,而它内部打印了正方形。

If you don't want to call the function, remove the () (and any parameters).如果您不想调用 function,请删除() (和任何参数)。

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

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