Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Calculator Help..?
#5
You can use an exception to achieve this.

With the code that you have used, I would do this.


print("Select An Operator")
print("Addition:        +")
print("Subtraction:     -")
print("Multiplication:  *")
print("Division:        /")

operator = input("Enter Choice (+,-,*,/:) ")

number = int(input("Please enter a number: "))
number2 = int(input("Please enter a second number: "))

try:
 if operator == '+':
     print(number + number2)
 elif operator == '-':
     print(number - number2)
 elif operator == '*':
     print(number * number2)
 elif operator == '/':
     print(number / number2)
 else: print("ERROR!")
except: print("ERROR!")
This code will "try" to do the task, and will output "ERROR" if an error is returned as we have used an exception.

If I was writing a calculator, I would just write something like this:


try:print(eval(input("Enter the equation")))
except:print("Error")
It takes input like 5*3, evaluates it and outputs the result. If there is an error in the process, "Error" will be outputted.

I hope this helps!
Reply


Messages In This Thread
Calculator Help..? - by hentera - Apr-20-2017, 04:56 PM
RE: Calculator Help..? - by Kebap - Apr-20-2017, 05:02 PM
RE: Calculator Help..? - by nilamo - Apr-20-2017, 05:09 PM
RE: Calculator Help..? - by Larz60+ - Apr-20-2017, 05:20 PM
RE: Calculator Help..? - by Josh - Apr-20-2017, 06:13 PM
RE: Calculator Help..? - by nilamo - Apr-20-2017, 06:22 PM

Forum Jump:

User Panel Messages

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