Thread: Newbie question

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    4
    Rep Power
    0

    Newbie question


    def func1(a,b,c):
    e = a + b/c
    return formatted(e)

    def func2(f,g,h,i):
    j = func1(f,g,h) + i
    return formatted(k)

    def func3(f,g,h,i):
    j = (f + g/h) + i
    return formatted(j)


    def formatted(a):
    return ("$%.2f" % a)

    When I run the below....

    print(func1(1,2,3))
    print(func2(1,2,3,4))
    print(func3(1,2,3,2))


    I get

    Traceback
    <module> D:\Python33\test.py 18
    func2 D:\Python33\test.py 6
    TypeError: Can't convert 'int' object to str implicitly


    If I run this

    print(func1(1,2,3))
    print(func3(1,2,3,2))

    it runs fine..

    >>>
    $1.67
    $3.67


    What Am I doing wrong, I need the func2 format to work especially with float as the last parameter.

    Thanks for looking.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    114
    Rep Power
    3
    You can't add a float to a string.

    Also, your func2 references a "k" variable does doesn't exist.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    4
    Rep Power
    0
    Hi I figured this out. I will post the solution in case it may help someone.

    The return value from func1 is a string. You can not add float or int to a string. The return has to be converted to a float.

    def func1(a,b,c):
    e = a + b/c
    return formatted(e)

    def func2(f,g,h,i):
    Code:
    j = float(func1(f,g,h)) + i

    return formatted(j)

    def func3(f,g,h,i):
    j = (f + g/h) + i
    return formatted(j)


    def formatted(a):
    return ("%.2f" % a)

    print(func1(1,2,3))
    print(func2(2,3,4,4))
    print(func3(1,2,3,2))

    This work fine.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    4
    Rep Power
    0
    Thanks sir, I think we were writing the answer at the same time.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    4
    Rep Power
    0
    Could you please tell me, how can I format the output like in my original post

    Thanks
  10. #6
  11. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,709
    Rep Power
    480
    Your original function contained a $ character.


    def formatted(a):
    return ("$%.2f" % a)
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo