0

I am learning Python and I have problems with data types convertions. When I run the program it says: "Can't convert 'float' object to str implicitly". I'm using the latest version of Python by the way.

I am just trying to make basic math operations.

Here's my code:

Quantity=input("PLEASE INSERT NUMBERS OF SHIRTS TO BUY:\n")
Tax=0.12

Price = 100*Quantity
Total = Price + Tax
3
  • float(Quantity) before using it. Commented Nov 28, 2014 at 0:23
  • @PadraicCunningham Also Tax is a float so it can't be added to the Price string without converting it first - Total = Price + str(Tax) say Commented Nov 28, 2014 at 0:29
  • I just saw the Tax part, just use quantity= float(input("PLEASE INSERT NUMBERS OF SHIRTS TO BUY:\n")) Commented Nov 28, 2014 at 0:30

1 Answer 1

3

The problem is that when you read in the input from the user, it is stored in the Quantity variable as a string. You need to convert the variable Quantity to a float, by using the code below.

quantity=input("PLEASE INSERT NUMBERS OF SHIRTS TO BUY:\n")
tax=0.12

price = 100*float(quantity)
total = price + tax

NOTE: I changed your variable to begin with a lowercase character. This is common coding practice. Classes usually being with a capital character, variables begin with a lowercase character.

As Zeiss Ikon stated below, the tax calculation is incorrect. I kept it as it to clearly solve the original question. This is fixed in the calculation below

total = price * (1.0 + tax)
Sign up to request clarification or add additional context in comments.

6 Comments

100 * Quantity does not cause a runtime error, it would make Price equal to 100 repetitions of the the string Quantity
I was going off what @JoseMiguelCab stated. He said he was receiving a run-time error when trying to run his original code. If it wasn't the statement 100 * Quantity, what was it?
Ok the error makes more since now. Can you explain why the error isn't happening when 100 * Quantity line is executed. Is Quantity being converted to an int?
I assume that's 12% sales tax (or VAT) rather than a flat 12 cents on any amount, right? So you'd want total = price * (1.0 + tax) or, to round to nearest cent, follow with total = float (int(total * 100 + 0.5))/100
Yes @ZeissIkon, I noticed this as well after I posted the answer, although the question that OP asked was asking to solve the error, not fix his math, so I didn't touch on this issue. I suppose I'll edit my Answer to let him know of his fault.
|

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.