This is the place for queries that don't fit in any of the other categories.

Function to Calculate Factorial Arrives at Correct Answer but 'returns' the wrong answer
in the below code the
Code: Select all
`print "inside the function", calculate_here`

shows me that the code does arrive at the correct answer
but then the final answer given (by 'return') is wrong
the problem seems to be the way "return calculate_here" works

Code: Select all
`print "Factorial attempt #2"def factorial(given_number):    calculate_here = given_number    while given_number > 0:        print "inside the function", calculate_here        calculate_here = calculate_here * (given_number - 1) # = 4 * 3;         given_number = given_number - 1 # = 3    return calculate_here    print "Factorial: 4! = 24. My answer = ",print factorial(4)#>>> 24 NOT 14print  "Factorial: 5! = 120. My answer = ",  factorial(5)#>>> 120 NOT 24print  "Factorial: 6! = 720. My answer = ", factorial(6)#>>> 720 NOT 35print ""print "Factorial attempt #3"def factorial(given_number):    index = 1    # calculate_here = given_number    while index <= given_number:        print "inside the function", calculate_here        calculate_here = index * (index + 1) # = 4 * 3;         index = index + 1 # = 3    return calculate_here    print "Factorial: 4! = 24. My answer = ",print factorial(4)#>>> 24 NOT 14print  "Factorial: 5! = 120. My answer = ",  factorial(5)#>>> 120 NOT 24print  "Factorial: 6! = 720. My answer = ", factorial(6)#>>> 720 NOT 35`
webmanoffesto

Posts: 6
Joined: Sat Apr 20, 2013 11:28 am

### Re: Function Returns Wrong Answer

The print of calculate_here is in your while loop right before it gets altered by the following line
Code: Select all
`calculate_here = calculate_here * (given_number - 1) # = 4 * 3`

so the value that gets returned will not be the same one as is printed.
Due to the reasons discussed here we will be moving to python-forum.io/ on October 1 2016
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.

Yoriz

Posts: 1672
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

### Re: Function Returns Wrong Answer

The problem is the loop calculates one more time than you want it to. If you change

calculate_here = calculate_here * (given_number - 1) # = 4 * 3;

to

if given_number>0: calculate_here = calculate_here * (given_number - 1) # = 4 * 3;

you'll see that it is ok.
___________________
Bob Rashkin

rrashkin

Posts: 35
Joined: Tue Feb 12, 2013 4:47 pm