Jump to content

Python code help?

pipnina
Go to solution Solved by fizzlesticks,

You're looping over fn_current and fn but neither are being updated inside the loop, so it just looping forever.

I think my code should work, it doesn't produce an error or crash but takes up 25% of my CPU (1 full core) and does nothing after the user inputs a number...

def calculate(fn): #Defines a function called "calculate", accepts an argument called "fn"
    firstAdd, secondAdd = 0, 1
    result = 0
    fn_current = 1
    
    while(fn_current < fn):
        result = firstAdd + secondAdd
        firstAdd = secondAdd
        secondAdd = result

    return result;

calculate(int(input("Which fibonacci number do you want?\n")))

It's supposed to ask the user what fibonacci number they want, and return the result, I feel like it should work but mine has been frozen and using a full core of my CPU for at least 5 minutes now, I only asked for the 5th number...

Please help!

 

    ~pip

 

EDIT: I feel silly now, I forgot to make fn_current increase by one after every operation... But it still doesn't work (just spits out the same number I put in)

Link to comment
Share on other sites

Link to post
Share on other sites

12 hours ago, pipnina said:

EDIT: I feel silly now, I forgot to make fn_current increase by one after every operation... But it still doesn't work (just spits out the same number I put in)

 

It works for me... 

fib.PNG

Link to comment
Share on other sites

Link to post
Share on other sites

Just a tip about commenting: Don't comment about what a certain statement does, but what you are trying to achieve with a piece of code.

We all can see that you are declaring a function, but you should instead tell us what "calculate" function actually calculates.

Link to comment
Share on other sites

Link to post
Share on other sites

14 hours ago, fizzlesticks said:

You're looping over fn_current and fn but neither are being updated inside the loop, so it just looping forever.

I would normally put comments in that are more useful and less describing everything that happens... But the lecturer said that if we explain how the code works in the code we didn't have to write the essay lol. (The submitted version had a comment on every line haha)

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×