r/PythonLearning • • Nov 09 '25

How can I improve?

Post image

I took Python at uni, but the topics were treated separately and we never got to put it all together, so I want to do small projects on my own to improve. Here's a little calculator I put together, critiques and tips are welcome. I'd like to practice some more, but idk what or where to start?

I hope this makes sense, English isn't my first language

163 Upvotes

60 comments sorted by

View all comments

1

u/luesewr Nov 09 '25

Personally, I like to keep my code very readable, some people might think it's a little too verbose, but I think writing it this way keeps it maintainable if you ever add more complicated logic to your operations. I also added a little extra logic to catch any errors that might occur when converting the user input to floats or trying dividing by zero:

def add(x, y):
    return x + y

def sub(x, y):
    return x - y

def mult(x, y):
    return x * y

def div(x, y):
    if y == 0.0:
        return "Can't divide by zero"
    return x / y

operation_lookup = {
    "+": add,
    "-": sub,
    "*": mult,
    "/": div,
}

try:
    num1=float(input("Enter a number: "))
except ValueError:
    print("Invalid numeric value")
    exit()

try:
    num2=float(input("Enter another number: "))
except ValueError:
    print("Invalid numeric value")
    exit()

operation = input("Enter an operation:(+,-,*,/) ")

if operation not in operation_lookup:
    print("Invalid operation")
    exit()

print(operation_lookup[operation](num1, num2))