How to multiply decimal numbers in Python

I wrote a program to convert pounds to dollars. I ran into some problems multiplying two numbers.

pounds = input('Number of Pounds: ')
convert = pounds * .56
print('Your amount of British pounds in US dollars is: $', convert)

Can someone tell me the code to fix this program?

+4
source share
3 answers

In Python 3, the inputstring will return. This is basically equivalent raw_inputin Python 2. So, before doing any calculations, you need to convert this string to a number. And be prepared for "bad entries" (that is, non-numeric values).

In addition, floats are generally not recommended for monetary values. You should use decimalto avoid rounding errors:

>>> 100*.56
56.00000000000001
>>> Decimal('100')*Decimal('.56')
Decimal('56.00')

- :

import decimal

try:
    pounds = decimal.Decimal(input('Number of Pounds: '))
    convert = pounds * decimal.Decimal('.56')
    print('Your amount of British pounds in US dollars is: $', convert)
except decimal.InvalidOperation:
    print("Invalid input")

:

sh$ python3 m.py
Number of Pounds: 100
Your amount of British pounds in US dollars is: $ 56.00

sh$ python3 m.py
Number of Pounds: douze
Invalid input
+8
def main():
    pounds = float(input('Number of Pounds: '))
    convert = pounds * .56
    print('Your amount of British pounds in US dollars is: $', convert) 

main()

, . .

+1

,

convert = pound * 56 / 100
-1
source