Christian R. Christian R. - 4 months ago 8
Python Question

Calculator created with Python

I'm new here in this "world".
I tried to create a calculator with Python,here's the code.
When I try to run it,IDLE gives me errors,can you help me,please? :D

Header 1

print("Options")
print("Type 'add' to add two numbers")
print("Type'subtract' to subtract two numbers")
print("Type'multiply' to multiply two numbers")
print("Type'divide' to divide two numbers")
print("Type'quit' to exit")
user_input = input(": ")

if user_input == "quit":
break

elif user_input == "add" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)

elif user_input == "subtract" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is" + result)

elif user_input == "multiply" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)

elif user_input == "divide" :
num1 = float(input("Insert a number: "))
num2 = float(input("Insert another number: "))
result = str(num1+num2)
print("The answer is " + result)
else:
print("Unknown command")

Answer

Try this (you don't have loop so use exit() rather than break, also use the right operators for add, divide, sub-struct, multiply.

from __future__ import division # to support division
print("Options")
print("Type 'add' to add two numbers")
print("Type'subtract' to subtract two numbers")
print("Type'multiply' to multiply two numbers")
print("Type'divide' to divide two numbers")
print("Type'quit' to exit")
user_input = raw_input(": ")

if user_input == "quit":
   exit()  #break is uesd in loops

elif user_input == "add" :
   num1 = float(input("Insert a number: "))
   num2 = float(input("Insert another number: "))
   result = str(num1+num2)
   print("The answer is " + result)

elif user_input == "subtract" :
   num1 = float(input("Insert a number: "))
   num2 = float(input("Insert another number: "))
   result = str(num1-num2)
   print("The answer is" + result)

elif user_input == "multiply" :
   num1 = float(input("Insert a number: "))
   num2 = float(input("Insert another number: "))
   result = str(num1*num2)
   print("The answer is " + result)

elif user_input == "divide" :
   num1 = float(input("Insert a number: "))
   num2 = float(input("Insert another number: "))
   result = str(num1/num2)
   print("The answer is " + result)
else:
   print("Unknown command")
Comments