Reputation: 91
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?
Upvotes: 9
Views: 46577
Reputation: 52000
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
Upvotes: 15
Reputation: 2060
def main():
pounds = float(input('Number of Pounds: '))
convert = pounds * .56
print('Your amount of British pounds in US dollars is: $', convert)
main()
If you are using input, you are inputing a string. You want to input a floating number for this questions.
Upvotes: 0