FOR WHILE LOOP Question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

FOR WHILE LOOP Question

Firstly below my code (that works): def power(num,power): j=0 while j <=power: for i in range(power): res=num**i print(str(num) + " at " + str(i) + " = " + str(res) ) j+=1 return res power(2,5) But, if I DON'T insert "return res" at the end, it repeats the output twice. Why? Thanks

19th Jul 2019, 2:38 PM
polargnome
4 Answers
+ 1
at the end of for loop j is 5. and condition j<=5 (j is less than or equal to 5) is still true. use j<power instead
19th Jul 2019, 2:59 PM
Taste
Taste - avatar
0
when it return the function end, also the loops inside the function. when return is removed, the loop executed again because the condition of the while loop still true.
19th Jul 2019, 2:41 PM
Taste
Taste - avatar
0
This is what I don't understand: if there is a "while j<=power" I expect the loop to stop when j=5 (so my last power is 4). After that, it should stop! But clearly I miss something....
19th Jul 2019, 2:53 PM
polargnome
0
Ok thanks Taste now I realize my mistake. I was looking at "i" while indeed I was not paying attention to "j". Anyway you helped me to wake up! Thanks
19th Jul 2019, 3:09 PM
polargnome