Basic Calculator with python 3

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>

<In what way does your code behave incorrectly? Include ALL error messages.>

<What do you expect to happen instead?>
How would you make the code below to “restart” in case the else statement is executed? The console stops in my case when the else statement is executed but I want the code to start a fresh and prompt the user to type the given instructions and nothing else. What code should I add? Thanks

```python

#basic calculator
print (“OPTIONS”)
print (“Type ‘multiply’ to multiply two numbers”)
print (“Type ‘divide’ to devide two numbers”)
print (“Type ‘add’ to add two numbers”)
print (“Type ‘subtract’ to subtract two numbers”)
print (“Type ‘quit’ to Quit”)

user_input=input("")
if user_input==“quit”:
print (“quitting”)
elif user_input==“add”:
first_num=float(input(“First number”))
second_num=float(input(“Second number”))
result=str(first_num+second_num)
print (result)
elif user_input==“subtract”:
num1=float(input(“First number”))
num2=float(input(“Second number”))
result =str(num1-num2)
print (result)
elif user_input==“multiply”:
num1=float(input(“First number”))
num2=float(input(“Second number”))
result=num1*num2
print (result)
elif user_input==“divide”:
num1=float(input(“Denominator”))
num2=float(input(“Numerator”))
result=str(num1/num2)
print (result)

else:
if user_input not in “‘multiply’,‘divide’,‘add’,‘subtract’”:
print (“You didn’t print either ‘multiply’,divide’,‘add’ or ‘subtract’”)

<do not remove the three backticks above>

Here is a basic revision, though it can be further refactored…

options = """OPTIONS
Type 'multiply' to multiply two numbers
Type 'divide' to devide two numbers
Type 'add' to add two numbers
Type 'subtract' to subtract two numbers
Type 'quit' to Quit
"""
def command():
    global options
    print ("=" * 40)
    print (options)
    print (' ')
    return input("Command: ")

while True:
    user_input = command()
    if user_input == "quit":
        print ("quitting")
        break;
    elif user_input == "add":
        num1 = float(input("First number: "))
        num2 = float(input("Second number: "))
        result = num1 + num1
        print ("\n> {0} + {1} = {2}\n".format(num1, num2, result))
    elif user_input == "subtract":
        num1 = float(input("First number: "))
        num2 = float(input("Second number: "))
        result = num1 - num2
        print ("\n> {0} - {1} = {2}\n".format(num1, num2, result))
    elif user_input == "multiply":
        num1 = float(input("First number: "))
        num2 = float(input("Second number: "))
        result = num1 * num2
        print ("\n> {0} * {1} = {2}\n".format(num1, num2, result))
    elif user_input == "divide":
        num1 = float(input("Denominator: "))
        num2 = float(input("Numerator: "))
        result = num1 / num2
        print ("\n> {0} / {1} = {2}\n".format(num1, num2, result))
    else:
        print ("Input Error! Try again...")

I can see you’ve put in new codes that I am not quite familiar with.Could you please explain what this line does? [quote=“mtf, post:2, topic:47846”]
("\n> {0} + {1} = {2}\n".format(num1, num2, result))
[/quote]

why did you use command() as value of user_input? Thanks

So yoiu would ask this question.

This function returns a value, which is the user input. Input criteria and a prompt line are embedded.

1 Like

It is Python 3 string formatting.

Or take away…

options = ("=" * 40) + \
"""
OPTIONS
Type 'multiply' to multiply two numbers
Type 'divide' to devide two numbers
Type 'add' to add two numbers
Type 'subtract' to subtract two numbers
Type 'quit' to Quit

"""
input_error = "Input Error! Try again..."

def command():
    global options
    print (options)
    return input("Command: ")

def writeln(x1, x2, y):
    print ("\n> {0} + {1} = {2}\n".format(x1, x2, y))

def inputln(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print (input_error)       
while True:
    user_input = command()
    if user_input == "quit":
        print ("quitting")
        break;
    elif user_input == "add":
        num1 = inputln("Addend A: ")
        num2 = inputln("Addend B: ")
        writeln(num1, num2, num1 + num2)
    elif user_input == "subtract":
        num1 = inputln("Subtrahend A: ")
        num2 = inputln("Subtrahend B: ")
        writeln(num1, num2, num1 - num2)
    elif user_input == "multiply":
        num1 = inputln("Factor A: ")
        num2 = inputln("Factor B: ")
        writeln(num1, num2, num1 * num2)
    elif user_input == "divide":
        num1 = inputln("Dividend: ")
        while True:
            num2 = inputln("Divisor: ")
            if num2 != 0:
                break
            print (input_error)
        writeln(num1, num2, num1 / num2)
    else:
        print (input_error)

Hi, I’m totally lost in this one now.

That’s a drag. It’s supposed to be getting simpler, as that is what the refactoring is about.

But I see where I messed up. Working on a solution, as I hope you are, also.

Update…

New working code.

options = ("=" * 40) + \
"""
OPTIONS
Type 'multiply' to multiply two numbers
Type 'divide' to devide two numbers
Type 'add' to add two numbers
Type 'subtract' to subtract two numbers
Type 'quit' to Quit

"""
input_error = "Input Error! Try again..."

def command():
    global options
    print (options)
    return input("Command: ")

def writeln(x1, p, x2, y):
    print ("\n> {0} {1} {2} = {3}\n".format(x1, p, x2, y))

def inputln(prompt):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print (input_error)    
while True:
    user_input = command()
    if user_input == "quit":
        print ("quitting")
        break;
    elif user_input == "add":
        num1 = inputln("Addend A: ")
        num2 = inputln("Addend B: ")
        writeln(num1, "+", num2, num1 + num2)
    elif user_input == "subtract":
        num1 = inputln("Subtrahend A: ")
        num2 = inputln("Subtrahend B: ")
        writeln(num1, "-", num2, num1 - num2)
    elif user_input == "multiply":
        num1 = inputln("Factor A: ")
        num2 = inputln("Factor B: ")
        writeln(num1, "*", num2, num1 * num2)
    elif user_input == "divide":
        num1 = inputln("Dividend: ")
        while True:
            num2 = inputln("Divisor: ")
            if num2 != 0: break
            print (input_error)
        writeln(num1, "/", num2, num1 / num2)
    else:
        print (input_error)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.