Link to home
Start Free TrialLog in
Avatar of cflo2382
cflo2382

asked on

How do I add a print statement to this function so that It prints "better" everytime it is calculated?

I am learning python through the online book "How to think like a computer scientist" I am stuck on Chapter 6, exercise 2:

Add a print statement to the sqrt function defined in section 6.14 that prints out better each time it is calculated. Call your modified function with 25 as an argument and record the results.

Here is 6.14:

def sqrt(n):
    approx = n/2.0
    better = (approx + n/approx)/2.0
    while better != approx:
        approx = better
        better = (approx + n/approx)/2.0
    return approx

I tried adding print better but it keeps saying better is not defined.
ASKER CERTIFIED SOLUTION
Avatar of HonorGod
HonorGod
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
print 'better: ' + better is a TypeError: can't add string and float
use
print 'better:', better
or
print 'better: ' + str(better)
mish33: Thanks.  I should have caught that.
Avatar of cflo2382
cflo2382

ASKER

thanks a lot guys! i went brain dead on that one for some reason.
No problem

Don't forget to accept 1, or more answers.
Thanks for the grade & points.

Good luck & have a great Thanksgiving.