I’m a programming newbie having difficulty with Python multiplication. I have code like this:
def getPriceDiscount():
price = int(input())
if price > 3000:
priceDiscount = price * 0.6
return priceDiscount
else:
return price
But when I execute it and type an input which is a decimal number like 87.94, I get the following error:
ValueError: invalid literal for int() with base 10: '87.94'
Isn’t the int() method able to convert the string ‘87.94’ into a number allowing me to multiply it by 0.6? What should I do to perform that conversion?
I’m using Python 3.2.2.
An
int(short for “integer”) is a whole number. Afloat(short for “floating-point number”) is a number with a decimal point.int()returns anintcreated from its input argument. You can use it to convert a string like"15"into theint15, or afloatlike12.059into theint12.float()returns afloatcreated from its input argument. You can use it to convert a string like"10.5"into thefloat10.5, or even anintlike12into thefloat12.0.If you want to force
priceto be an integer, but you want to accept a floating point number as typed input, you need to make the input afloatfirst, then convert it withint():Note that if you multiply an
intby afloatsuch as your discount factor, the result will be afloat.Also note that my example above doesn’t round the number — it just truncates the stuff after the decimal point. For example, if the input is
"0.6"thenpricewill end up being0. Not what you want? Then you’ll need to use theround()function on thefloatfirst.If you intended to use floating point calculations (which makes sense if we’re talking about a commodity price), then don’t perform the
intconversion. Just usefloat. You may still want to do some rounding. If you want to round to 2 decimal places, you can call round with the second argument as2:Finally, you might want to look into Python’s
decimalmodule, since there are limitations when using floating point numbers. See here for more information: http://docs.python.org/tutorial/floatingpoint.html