0
How can i make a calculator by Python?
6 Réponses
+ 4
1. Input needed data such as operation and operands;
2. Calculate a result;
3. Output the result.
+ 2
Aravind Shetty you should at least check with a regex if the input is indeed a valid expression or malicious code
0
while True:
try:
inp = input()
except:
inp = ""
if inp == "exit" or "":
break
exec("print({0})".format(inp))
0
Before making a calculator in algebraic notation (e.g.: "2*(3+4)"),
try building one in RPN (e.g.: "2 3 4 + *")
From left to right, push every number in a stack-like data structure and every operator takes the first 2 values from the stack and pushes the result
At the end, if the expression is valid, the stack shell remain with only 1 value, which is the result
0
Yeah, you are right. But I just posted simple code. Just my idea. You can extend it if you want. You can also import math module and use logarithms and trigonometric functions.
0
def add(x,y):
return x+y
def subtract (x,y):
return x-y
def multiply(x,y):
return x*y
def divide (x,y):
return x/y
Print ("select operation")
Print ("1.add",\n"2.subtract,"\n"3.multiply",\n"4.divide")
#Take input from the user
choice = input("Enter choice (1/2/3/4):")
num1 = int(input("Enter first number:"))
num2 = int(input ("Enter second number:"))
If choice == '1':
Print (num1,"+",num2, "=",add(num1,num2))
elif choice == '2': # Same print like first
#. Don't forget to change the operators
elif choice == '3':
# Same print like first
#. Don't forget to change the operator
elif choice == '4':
# Same print like first
#. Don't forget to change the operator
else:
Print ("invalid output")