Jul-12-2018, 02:29 AM
What happens if you add $0.1 and $0.2?
If you operate with money, then use integer in the smallest money unit (cent), or use decimal.Decimal.
I have seen, that you're catching exceptions.
It's better to do only the operations in the try block, where may occur an exception.
Be more specific, if you catch an exception.
Example with your getBalance function.
If you operate with money, then use integer in the smallest money unit (cent), or use decimal.Decimal.
I have seen, that you're catching exceptions.
It's better to do only the operations in the try block, where may occur an exception.
Be more specific, if you catch an exception.
Example with your getBalance function.
def get_balance(): while True: try: balance = float(input("Enter an initial balance: $")) except ValueError: print("You must enter a valid float") continue if not balance > 1000: break else: print("Error: Higher than $1000") return balanceWhen using Decimal, there is a different Exception. Which one is easy to try it in the repl or reading the documentation.
from decimal import Decimal, InvalidOperation def get_balance_decimal(): while True: try: balance = Decimal(input("Enter an initial balance: $")) except InvalidOperation: print("You must enter a valid decimal") continue if not balance > 1000: break else: print("Error: Higher than $1000") return balance
print(get_balance() + get_balance())
Output:Enter an initial balance: $0.1
Enter an initial balance: $0.2
0.30000000000000004
print(get_balance_decimal() + get_balance_decimal())
Output:Enter an initial balance: $0.1
Enter an initial balance: $0.2
0.3
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!