I was trying a simple recursive problem in python and was stumped by the for-loop-esq implementation in python. The implementation uses the range(x,y,z) function.
Here is the code in python:
num = 25
f1 = 0
f2 = 1
for num in range(1,num,1):
num = f1 + f2
f1 = f2
f2 = num
print("num is : ", num)
Same code in java:
int num = 25;
int f1 = 0;
int f2 = 1;
for(int i = 1; i < num; i++){
num = f1 + f2;
f1 = f2;
f2 = num;
}
System.out.println("# at 25 is : " + num);
The java implementation will never spit out the right answer (75025) because num is overwritten in the first line of the for-loop (num = f1 + f2).
Where as in python, the code executes and delivers the right answer. How come? Does python implement some sort of i counter under the hood?
I'm using the pyCharm debugger to test this.
javaandpython, why do you need to change a variable that shoud be used to control the loop? if you want to execute 25 times, don't change the variable. If you want a more "flexible" loop, usewhileinstead