0

I'm trying to convert a variable whose value changes however the value is usually to one decimal place e.g. 0.5. I'm trying to change this variable to 0.50. I'm using this code but when I run the program it says TypeError: Can't convert 'float' object to str implicitly

Here is my code:

while topup == 2:
    credit = credit + 0.5
    credit = str(credit)
    credit = '%.2f' % credit
    print("You now have this much credit £", credit)
    vending(credit)
4
  • That's not the error I'm getting. What version of Python are you using? Commented Oct 9, 2014 at 17:45
  • The error is actually that you're passing a string in '%.2f' % credit TypeError: a float is required for python 3 and TypeError: float argument required, not str for python 2. Commented Oct 9, 2014 at 17:49
  • @Kevin I'm using Python 3.4 Commented Oct 9, 2014 at 17:53
  • @IsaacGSivaa Not a duplicate, though the OP might notice that as well. Commented Oct 9, 2014 at 21:06

1 Answer 1

1
while topup == 2:
    credit = float(credit) + 0.5
    credit = '%.2f' % credit
    print("You now have this much credit £", credit)
    vending(credit)

the problem is you cannot float format a string

"%0.2f"%"3.45"  # raises error

instead it expects a number

"%0.2f"%3.45   # 0k
"%0.2f"%5   # also ok

so when you call str(credit) it breaks the format string right below (that incidentally also casts credit back to a string)

incidentally you should really only do this when you print

credit = 1234.3
print("You Have : £%0.2f"%credit)

in general you want your credit to be a numeric type so that you can do math with it

Sign up to request clarification or add additional context in comments.

1 Comment

Is there anyway I can solve my problem any other way by not using str(credit)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.