#๐Ÿ”’ My first code, I'm open to feedback!

7 messages ยท Page 1 of 1 (latest)

crystal bay
#
def calculator():
 print("---Calculator---")

 while True:
    try:
        n1 = float(input("First number:"))
        op = input("Operation (+, -, *, /) or 's' to exit:")
        if op.lower() == "s": 
           print("Goodbye!")
           break
        
        if op not in ["+", "-", "/", "*", "s"]: 
         print("Error: Invalid Operator")
         continue  
        
        n2 = float(input("Second number:"))
        
        if op == "+":
           print(f"Result: {n1 + n2}")
        elif op == "-":
           print(f"Result: {n1 - n2}")
        elif op == "/":
         print(f"Result: {n1 / n2}") if n2 != 0 else print("Error: Can't divide by zero")
        elif op == "*":
           print(f"Result: {n1 * n2}")
    except ValueError:
       print("Error: Please enter numeric values.")

calculator()```
south marlinBOT
#

@crystal bay

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

manic kestrel
thorn quest
#

im pretty sure the division by zero should be handled like this, im not sure your syntax is correct?

        elif op == "/":
         print(f"Result: {n1 / n2}" if n2 != 0 else "Error: Can't divide by zero")

otherwise it's pretty good, you got all the error handling, but as Fashoomp said, stay consistent with the indentation

lost finch
#

Also, you should try to put try/except around the smallest piece of code possible. So you should put one around only the n1 = line and one around only the n2 = line. Those are the only 2 lines which should reasonably raise a ValueError. If one happens somewhere else you want to know, and having a try/except around everything hides those.
@crystal bay

south marlinBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.