I was writing a pounds to dollars converter program. I encountered some problems multiplying the two numbers.
pounds = input('Number of Pounds: ')
convert = pounds * .56
print('Your amount of British pounds in US dollars is: $', convert)
Can anyone tell me the code to correct this program?
To multiply decimals, first multiply as if there is no decimal. Next, count the number of digits after the decimal in each factor. Finally, put the same number of digits behind the decimal in the product.
Python Multiplication – Arithmetic Operator Python Multiplication Operator takes two operands, one on the left and other on the right, and returns the product of the these two operands. The symbol used for Python Multiplication operator is * .
Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.
Use the multiplication operator to multiply an integer and a float in Python, e.g. my_int * my_float . The multiplication result will always be of type float .
In Python 3 input
will return a string. This is basically equivalent of raw_input
in Python 2. So, you need to convert that string to a number before performing any calculation. And be prepared for "bad input" (i.e: non-numeric values).
In addition, for monetary values, it is usually not a good idea to use floats. You should use decimal
to avoid rounding errors:
>>> 100*.56
56.00000000000001
>>> Decimal('100')*Decimal('.56')
Decimal('56.00')
All of that lead to something like that:
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")
Producing:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With