why this code will print 0 | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

why this code will print 0

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

2nd May 2017, 8:17 AM
Paavan Gupta
Paavan Gupta - avatar
5 Answers
+ 6
In the first iteration of the loop, i is 0 and this will be printed. Then the return statement is called and the function execution stops.
2nd May 2017, 8:37 AM
Tob
Tob - avatar
+ 5
range(n) is composed of all the whole numbers between 0 included and n exluded : ie range(10) is composed of 10 numbers : 1,2,3....,8,9 so in your code, in your function the i in the for loop will take all this value one per one, ob tge first iteration i=0 then i=1 etc... but on the first iteration i=0 then you have print(i) so 0 is output and then you have the return statement that is the end of the function. So when pytgon reads return he finishes the function. So the for loop will never repeat because of the return statement. If you want all your values printed, then you have to set the return keyword after the for loop and not inside (with the right number of instrumentations)
2nd May 2017, 10:49 AM
Glozi30
Glozi30 - avatar
0
sorry but can you tell more clearly
2nd May 2017, 9:22 AM
Paavan Gupta
Paavan Gupta - avatar
0
Thanks I finnaly understand!!!!!!! Thanks a lot inded!!!!!! For real, my man!!!
19th Jun 2019, 12:47 AM
tucooperacion
tucooperacion - avatar
- 1
ok now i got it thank you to both of you for helping me
2nd May 2017, 10:53 AM
Paavan Gupta
Paavan Gupta - avatar