简体   繁体   English

Python对于范围(len(str))中的i:最后一次迭代不打印

[英]Python For i in range(len(str)): last iteration prints None

def fun(str):
    for i in range(len(str)):
        print(i)

string = 'abc'

print(fun(string))

print results are 打印结果是

0
1
2
None

if I change 如果我改变

for i in range(len(str)-1):

the last result is still None 最后的结果仍然是None

Why is this? 为什么是这样? And how do I stop it? 我该如何阻止它?

When you call print(fun('abc')) , you first call fun , which indeed prints 1 , 2 and 3 , once fun completes, you print its return value. 当你调用print(fun('abc'))你首先调用fun ,这的确打印123 ,一次fun完成,打印其返回值。 Since you didn't explicitly return anything, Python implicitly returns None for you. 由于您没有明确返回任何内容,因此Python会为您隐式返回None

To make a long story short - don't call print on fun , just call fun : 长话短说-不要将print称为fun ,只需调用fun

string = 'abc'

fun(string) # Here

You are getting 0, 1, 2 from the print statement in fun function while None is getting printed by: 您将从fun函数的print语句中获取0, 1, 2None的打印方式为:

print(fun(string))

Since, by default a python function returns None that's why you are getting it here. 由于默认情况下python函数返回None ,这就是为什么要在这里获取它。 You can directly call it without print statement. 您可以直接调用它,而无需打印语句。

fun(string)

this is because you use print(fun(string)) and you have a print statement inside your function. 这是因为您使用了print(fun(string)),并且函数中有一条print语句。 So it executes the print inside your function and another print with no return value from the function so None. 因此,它将在函数内部执行打印,并且在函数没有返回值的情况下执行另一次打印,因此执行None。

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

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