r/PythonLearning • • Jul 16 '25

Help Request Could it be simpler ?

Post image

I'm totally new to programming in general not only in Python so as according to the advises I received, many people told me to code instead of watching tutorials only and so I did, I made this simple calculator with instructions of course but could it be easier and simpler than this ?

178 Upvotes

61 comments sorted by

View all comments

1

u/Upstairs-Proposal-19 Jul 17 '25

A nicer version would use a dict and lambda's for the operations. That would make it easy to extend this with other operations as well:

operations = {
    "1": ("ADD", lambda x, y: x + y),
    "2": ("SUBTRACT", lambda x, y: x - y),
    "3": ("MULTIPLY", lambda x, y: x * y),
    "4": ("DIVIDE", lambda x, y: x / y if y != 0 else "Error: Division by zero")
}

print("Select an operation:")
for k, (name, _) in operations.items():
    print(f"{k}. {name}")

op = input("Choice: ")
if op in operations:
    try:
        x = float(input("First number: "))
        y = float(input("Second number: "))
        name, func = operations[op]
        print(f"{name} result = {func(x, y)}")
    except ValueError:
        print("Invalid number.")
else:
    print("Invalid choice.")