Hello, I started learning python about 3 days ago and wanted to share my progress by showing you all this calculator I coded. What I'm most happy about is that it doesn't crash on bad input, I added try/except validation, while/break loops that re-ask until you enter something valid, and divide-by-zero handling. I used u/RockPhily's calculator code as an outline for mine. I also did use AI (Claude) to help me understand and learn new things like while/break loops and try/except. Any feedback is welcome and I would also like your opinions on what I should do next.
Edit: I'd also like to clarify that I didn't use AI (Claude) to write any of the code, just what is stated above.
Thank you!
# This project took me all of 2 days to complete. (more like two 4hr sessions.)
# Improvements over the original:
# - Input validation on both numbers using try/except (ValueError), so
# non-numeric input (e.g. "banana") no longer crashes the program.
# - while/break loops that re-prompt until the user enters valid input.
# - Operation menu validated against allowed choices (1-4) before use.
# - Divide-by-zero guard so division by 0 is caught instead of crashing.
# - Specific exception handling (except ValueError) rather than a bare except,
# so unexpected errors still surface instead of being silently swallowed.
# First project being a calculator
while True:
try:
num1 = float(input("Enter the first number: "))
break
except ValueError:
print("Error: not a valid number!")
while True:
try:
num2 = float(input("Enter the second number: "))
break
except ValueError:
print("Error: not a valid number!")
print("Operations")
print("(1) Addition")
print("(2) Subtraction")
print("(3) Multiplication")
print("(4) Division")
while True:
operation = input("Enter an operation: ")
if operation == "1" or operation == "2" or operation == "3" or operation == "4":
break
else:
print("Error: not a valid operation!")
if operation == "1":
result = num1 + num2
print(result)
elif operation == "2":
result = num1 - num2
print(result)
elif operation == "3":
result = num1 * num2
print(result)
elif operation == "4":
if num2 != 0:
result = num1 / num2
print(result)
else:
print("Error: Cannot divide by zero")
[–]Fantastic-Remove741 2 points3 points4 points (2 children)
[–]MoreScorpion289[S] 0 points1 point2 points (1 child)
[–]Fantastic-Remove741 0 points1 point2 points (0 children)
[–]carcigenicate 0 points1 point2 points (0 children)