Python Forum
Started coding yesterday. Please review "Basic Calculator" I made.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Started coding yesterday. Please review "Basic Calculator" I made.
#1
I started learning to code yesterday and figured I'd use python because of it's relative ease of use. Here is my version of the "Basic Calculator". I have surface knowledge of a few things, "variables", "print statements", "functions". Can I get some constructive feedback? Please and thank you!

def calculator1():
    global num1, num2, op

    try:
        num1 = float(input("Enter First Number: "))
    except:
        print("Invalid, Enter First Number Again")
        calculator1()

    op = input("Enter An Arithmetic Operator: ")
    calculator2()


def calculator2():
    global num2
    try:
        num2 = float(input("Enter Second Number: "))
    except:
        print("Invalid Number, Enter Second Number Again")
        calculator2()

    if op == "+":
        print("")
        print(str(num1) + " + " + str(num2) + " = " + str(num1 + num2))
        print("")
    elif op == "-":
        print("")
        print(str(num1) + " - " + str(num2) + " = " + str(num1 - num2))
        print("")
    elif op == "*":
        print("")
        print(str(num1) + " * " + str(num2) + " = " + str(num1 * num2))
        print("")
    elif op == "/":
        print("")
        print(str(num1) + " / " + str(num2) + " = " + str(num1 / num2))
        print("")
    else:
        print("Invalid Operator")
        print("")
    calculator1()


calculator1()
Reply
#2
Here is an enhanced program with a few remarks
def calculator1():
    # Use a loop to avoid recursion (calculator1() calling
    # itself indefinitely for no reason)
    while True:
        try:
            num1 = float(input("Enter First Number: "))
        except Exception: # better than "except:" alone
            print("Invalid, Enter First Number Again")
        else:
            break
 
    op = input("Enter An Arithmetic Operator: ")
    return num1, op # Use return to avoid global variables
 
 
def calculator2(num1, op): # use parameters to avoid global variables

    while True:
        try:
            num2 = float(input("Enter Second Number: "))
        except Exception:
            print("Invalid Number, Enter Second Number Again")
        else:
            break
 
    if op == "+":
        print("")
        print(str(num1) + " + " + str(num2) + " = " + str(num1 + num2))
        print("")
    elif op == "-":
        print("")
        print(str(num1) + " - " + str(num2) + " = " + str(num1 - num2))
        print("")
    elif op == "*":
        print("")
        print(str(num1) + " * " + str(num2) + " = " + str(num1 * num2))
        print("")
    elif op == "/":
        print("")
        print(str(num1) + " / " + str(num2) + " = " + str(num1 / num2))
        print("")
    else:
        print("Invalid Operator")
        print("")
 
while True:  # use a loop to avoid repeating the program with recursion
    num1, op = calculator1()
    calculator2(num1, op)
Reply
#3
Wow, thanks Mod. Exactly what I was looking for! Appreciate it!
Reply
#4
You actually don't need 3 questions, you can string them into one:

def calculator1():
    global num1, num2, op
 
    equation = input("Enter an equation: ")
    try:
        answer = eval(equation) #This is the cool part, eval can actually take string input and do arithmetic operations with it.
        print("Your answer is: ", answer)
    except:
        print("ERROR: INVALID")

calculator1()

Also, on line 21, why do you put except Exception? That is not necessary, except by itself catches all exceptions.
Reply
#5
BitPythoner Wrote:Also, on line 21, why do you put except Exception? That is not necessary, except by itself catches all exceptions.
Normally in this context, the exception to catch is ValueError because this is the exception thrown when a conversion to float fails. I didn't want to enter these technical details because @blueconsole is a begginner and there are so many other things to learn.

There is a subtle difference between except: alone and except Exception:, the former catches KeyboardInterrupt but the latter doesn't, because KeyboardInterrupt is not an Exception.
>>> isinstance(KeyboardInterrupt(), Exception)
False
>>> try:
...     raise KeyboardInterrupt
... except:
...     pass
... 
>>> try:
...     raise KeyboardInterrupt                                                              
... except Exception:
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt
>>> 
In certain environments, it may be impossible to exit the program with a ^C on the keyboard if you write except alone. That said, it is not the sole reason not to use except alone. My belief is that one should always specialize the caught exception as much as possible because it makes programs easier to debug.
Reply
#6
Please avoid suggesting the use of eval. Obviously it will (try to) evaluate any string as a Python expression and isn't something you should have to use often if at all. For someone learning the language though, using it means they miss out on the important aspects of the exercise - solving the problem and figuring out how to use the language features to implement that solution.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  First time python user - Calculator code review Steamy 1 2,177 Jul-22-2020, 05:59 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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