Python Forum
Criticism on one of my first completed programs in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Criticism on one of my first completed programs in Python
#5
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.

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 balance
When 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!
Reply


Messages In This Thread
RE: Criticism on one of my first completed programs in Python - by DeaD_EyE - Jul-12-2018, 02:29 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Tkinter Tic Tac Toe With Enhanced Features - Completed adt 2 2,993 Dec-10-2019, 06:22 AM
Last Post: adt
  my earliest completed script Skaperen 0 2,037 Mar-08-2019, 09:50 PM
Last Post: Skaperen
  [link]Creating-a-repo-for-your-completed-scripts metulburr 0 7,686 Aug-29-2018, 01:19 PM
Last Post: metulburr
  completed module: validip.py Skaperen 8 7,535 Jan-04-2017, 06:39 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020