-3

I found the a code in a website and I do not quite understand how it works or finds the upper and lower Fibonacci boundaries of a given number.

I want to understand how the code runs with an example like with x = 6

def fib_intervall(x):
    """ returns the largest fibonacci
    number smaller than x and the lowest
    fibonacci number higher than x"""
    if x < 0:
        return -1
    (old,new, lub) = (0,1,0)
    while True:
        if new < x:
            lub = new 
            (old,new) = (new,old+new)
        else:
            return (lub, new)

while True:
    x = int(input("Your number: "))
    if x <= 0:
        break
    (lub, sup) = fib_intervall(x)
    print("Largest Fibonacci Number smaller than x: " + str(lub))
    print("Smallest Fibonacci Number larger than x: " + str(sup)
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • [https://stackoverflow.com/questions/1623039/python-debugging-tips](https://stackoverflow.com/questions/1623039/python-debugging-tips) - helps you debug your code and understand it by inspecting variables. SO is nu tutoring service, we do not "teach" coding. To understand the code, start it with 6, place breakpoints, and inspect variables. OR use pen and paper and "execute" the code on paper for yourself. – Patrick Artner May 18 '19 at 23:43
  • @PatrickArtner "start it with 6"? – Error - Syntactical Remorse May 19 '19 at 00:02
  • @Error-SyntacticalRemorse _I want to understand how the code runs with an example like with `x = 6`_ - yes. Start it with 6. Debug it. See what the code does. See what variables become. Print intermediate values. GROKE it. – Patrick Artner May 19 '19 at 08:26

1 Answers1

0

First of all you must examine each line of code and try to change some lines if you really want to understand.

For answer:

Step 1. You will go in to infinite while loop and 6 will be assigned to x.

Step 2. X<=0 is false, therefor fib_intervall(6) will be called, and then result will be assigned to lub,sub.

Step 3. inside fib_intervall:

{1 - if statement is false(6>0.

2 - old = 0 new = 1 lub = 0 assignments will be done.

3 - The other infinite loop will be executed:

new was 1 and 1<6 so if statement will be executed. old(0) will be new(1) and new will be old + new

[ old = 0 new = old + new.]

loop will continue as following

[ old = 1 new = 2]->[ old = 2 new = 3]->[ old = 3 new = 5]->[ old = 5 new = 8]

after last assignments new = 8 > 6 so else statement will be executed and function will return (5,8) and these are the fibonacci boundaries of 6.}

Step 4. 5 will be printed with lub variable. 8 will be printed with sup variable :

Largest Fibonacci Number smaller than x: 5

Smallest Fibonacci Number larger than x: 8

Dot.Volare
  • 118
  • 11
  • Thank you Crazy_39365, for taking time to explain. i get it now :). This was the first time that i came across an infinite while loop. Thank you Patrick Artner for the debugging link. – dinesh solanki May 19 '19 at 12:34