Python:打印一个简单的函数 [英] Python: Printing a simple function

查看:202
本文介绍了Python:打印一个简单的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python和编程有一个绝对的初学者,我刚刚接触到了函数。



我定义了两个简单的函数:

  def output1( ):
print你好,世界!

def output2():
printHello,there!

output1()
output2()

上面的脚本称为function.py,然后使用windows power shell运行脚本,并按照您的预期打印以下内容:

 你好,世界! 
你好,那里!

然而,当我修改脚本时:

  def output1():
printHello,world!

def output2():
printHello,there!

print output1()
print output2()

它打印:

 您好,世界! 

你好,那里!
None

出于好奇,为什么当我在output1和output2前加上print ?

解决方案

它的工作方式如下所示:

  print output1()

表示您要打印函数(即返回值)。

因为函数中没有返回值,所以默认为None。

  def output1():
printHello,world!
def output2():
printHello,there!
returnSomething

print output1()
print output2()

会导致:

 您好,世界! 

你好,那里!
某物


I'm an absolute beginner to Python and programming in general and I have just had my first exposure to functions.

I have define two simple functions below:

def output1():
   print "Hello, world!"

def output2():
   print "Hello, there!"

output1()
output2()

Having saved the above to a script called function.py, I then use the windows power shell to run the script, and it prints the following as you would expect:

Hello, world!
Hello, there!

However when I amend the script to:

def output1():
   print "Hello, world!"

def output2():
   print "Hello, there!"

print output1()
print output2()

It prints:

Hello, world!
None
Hello, there!
None

Out of curiosity why does it do this when I prefix output1 and output2 with print?

解决方案

It works like this, because:

print output1()

means that you want to print the RESULT of the function (ie. the value of return).

And because there is no return in your function, by default it's None.

def output1():
   print "Hello, world!"
def output2():
   print "Hello, there!"
   return "Something"

print output1()
print output2()

Would result in:

Hello, world!
None
Hello, there!
Something

这篇关于Python:打印一个简单的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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