Python 打印命令行参数时没有额外输出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3953233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:32:19  来源:igfitidea点击:

Extra output none while printing an command line argument

pythonfunction

提问by CuriousMind

It's my day 1 of learning python. so it's a noob question for many of you. See the following code:

这是我学习 Python 的第一天。所以对你们中的许多人来说这是一个菜鸟问题。请参阅以下代码:

#!/usr/bin/env python

import sys

def hello(name):
    name = name + '!!!!'
    print 'hello', name

def main():
    print hello(sys.argv[1])


if __name__ == '__main__':
    main()

when I run it

当我运行它时

$ ./Python-1.py alice
hello alice!!!!
None

Now, I have trouble understanding where this "None"came from?

现在,我很难理解这"None"是从哪里来的?

采纳答案by Thomas Wouters

Count the number of printstatements in your code. You'll see that you're printing "hello alice!!!"in the hellofunction, andprinting the result of the hellofunction. Because the hellofunction doesn't return a value (which you'd do with the returnstatement), it ends up returning the object None. Your printinside the mainfunction ends up printing None.

计算print代码中语句的数量。你会看到,你打印"hello alice!!!"hello功能,打印结果hello功能。因为hello函数不返回值(你会用return语句来做),它最终返回 object None。您的print内部main函数最终会打印None

回答by Sujoy

Change your

改变你的

def main():
    print hello(sys.argv[1])

to

def main():
    hello(sys.argv[1])

You are explicitly printing the return value from your hello method. Since you do not have a return value specified, it returns Nonewhich is what you see in the output.

您正在显式打印 hello 方法的返回值。由于您没有指定返回值,因此它返回None您在输出中看到的内容。