请教:Python测试代码运行输出中‘None’的来源
为什么你的Python代码输出会多一个
None? 嘿,这个问题其实挺典型的,我来给你理清楚背后的原因~
首先看你的代码:
def test(arg1, arg2): print "arg1: %r, arg2: %r" %(arg1, arg2) print test("Hello", "World")
核心原因:函数默认返回None + 嵌套的print调用
这里其实发生了两件独立的操作:
- 函数的默认返回规则:在Python里,任何函数如果没有显式写
return语句指定返回值,都会默认返回None——这是Python的内置规则,所有函数必须有返回结果,没指定就返回这个代表“空”的特殊值。 - 嵌套
print的执行逻辑:你写的print test("Hello", "World")是两步操作:- 第一步:调用
test("Hello", "World"),函数内部的print语句会输出arg1: 'Hello', arg2: 'World'。 - 第二步:把
test函数的返回值(也就是默认的None)传给外层的print,所以print会再输出这个None。
- 第一步:调用
解决办法
有两种简单的方式去掉多余的None:
方式1:直接调用函数,去掉外层的print
def test(arg1, arg2): print "arg1: %r, arg2: %r" %(arg1, arg2) test("Hello", "World") # 直接调用,不用套print
这样执行后就只会输出arg1: 'Hello', arg2: 'World'。
方式2:让函数返回字符串,按需打印
如果需要后续复用这个输出内容,可以让函数返回字符串,再在外层打印(或者只返回不内部打印):
def test(arg1, arg2): # 先把内容存成字符串 output_str = "arg1: %r, arg2: %r" %(arg1, arg2) return output_str # 外层打印返回的字符串 print test("Hello", "World")
这样输出同样是正确的,没有多余的None。
内容的提问来源于stack exchange,提问作者Fred
相关产品推荐
相关产品推荐

