What does return do in Python when it's typed alone? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

What does return do in Python when it's typed alone?

For example, in def print_nums(x): for i in range(x): print(i) return print_nums(10)

12th Feb 2019, 3:39 PM
Kashif Nawaz
Kashif Nawaz - avatar
3 Answers
+ 1
return just ends your function. So already in i==0 the function will terminate and the rest of the loop will never be executed. Unless you move return to the same indentation level as the for loop. But that would be pointless, because a function returns automatically when it reaches its end. You will normally use a single return in a function to stop its execution when a certain condition is reached, when you want to prevent it running on to its end. So you could compare it to the break in a for loop in this case. Oh yeah, and the simple return statement will still return something: None.
12th Feb 2019, 3:45 PM
HonFu
HonFu - avatar
0
The output of that code comes 0, I'm confused why is that.
12th Feb 2019, 4:21 PM
Kashif Nawaz
Kashif Nawaz - avatar
0
Because you loop over a range of ten that starts with zero, and only the zero is printed, then the function is returned from already.
12th Feb 2019, 5:12 PM
HonFu
HonFu - avatar