Python Help | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Python Help

Explain this please: def f(n): x = y = 1.0 for i in range(1,n): x, y=y, x+y return y/x print(f(3))

24th Dec 2019, 9:55 AM
A.H. Majumder 🇧🇩
A.H. Majumder 🇧🇩 - avatar
5 Answers
+ 9
Looks like you got lots of good advice, but this might also help. https://code.sololearn.com/cTRK2QlwEZ0F/?ref=app
24th Dec 2019, 10:22 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 8
I think the function gives this: https://en.m.wikipedia.org/wiki/Golden_ratio The higher the number of the arg, the more accurate.
24th Dec 2019, 10:12 AM
HonFu
HonFu - avatar
+ 8
Print the variable <x> and <y> before the loop and inside loop body. The output should give you a clear view how the code works def f(n): x = y = 1.0 print(f"Before loop x = {x} y = {y}") loop = 1 for i in range(1, n): x, y = y, x + y print(f"Loop iteration {loop}, x = {x} y = {y}") loop += 1 return y / x print("Result", f(3))
24th Dec 2019, 10:12 AM
Ipang
+ 7
If the function would return y instead of y/x, I guess the program would find the n+1 element in fibonacci sequence 🤔. That would mean the program calculates the division of 2 consecutive fibonacci numbers
24th Dec 2019, 10:11 AM
molang
molang - avatar
+ 7
In beginnig: x = 1.0 y = 1.0 When i = ... then the variable values changed to ... : i = 0: x = 1.0 (x = y ---> x = 1.0) y = 2.0 (y = x + y ---> y = 1.0 + 1.0 ---> y = 2.0) i = 1: x = 2.0 (x = y ---> x = 2.0 y = 4.0 (y = x + y ---> y = 2.0 + 2.0 ---> y = 4.0) i = 2: x = 4.0 (x = y ---> x = 4.0) y = 8.0 (y = x + y ---> y = 4.0 + 4.0 ---> y = 8.0) Then y / x was returned: return y/x (y/x ---> 8.0 / 4.0 ---> 2.0) 2.0 was returned.
24th Dec 2019, 10:14 AM
Seb TheS
Seb TheS - avatar