0

Does anyone know why this code prints None?

def string_length(string): length=0 for char in string: length+=1 print(string_length("Python"))

28th Dec 2019, 2:46 PM
Esteban Rueda
Esteban Rueda - avatar
8 Answers
+ 3
Esteban Rueda check this code once for better understanding.. https://code.sololearn.com/cpFmWem330wL/?ref=app
28th Dec 2019, 3:04 PM
Lakshmipathi
Lakshmipathi - avatar
+ 6
The function has no return value. In Python, every function not returning anything returns None. Write return length at the bottom of your function, then it should work.
28th Dec 2019, 2:49 PM
HonFu
HonFu - avatar
+ 2
Why did you change your function? It worked the way it was! Just add the return line and you're good to go.
28th Dec 2019, 3:04 PM
HonFu
HonFu - avatar
+ 1
Thank you!! Where am I supposed to place the return length? Because It has been resulting in an indentation error for me.
28th Dec 2019, 2:58 PM
Esteban Rueda
Esteban Rueda - avatar
+ 1
at the end of the function block, aligned with the rest of it.
28th Dec 2019, 2:59 PM
HonFu
HonFu - avatar
0
There is no return function..so
28th Dec 2019, 2:58 PM
Lakshmipathi
Lakshmipathi - avatar
0
Esteban Rueda that's based on your requirement.. keep return outside the loop..like "return length" for getting the length of the string
28th Dec 2019, 2:59 PM
Lakshmipathi
Lakshmipathi - avatar
0
def string_length(string): length=0 for char in string: print(string_length("Python")) return length
28th Dec 2019, 3:02 PM
Esteban Rueda
Esteban Rueda - avatar