How can i make a calculator by Python? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
0

How can i make a calculator by Python?

15th Aug 2021, 2:43 PM
Farhan Mozumder
Farhan Mozumder - avatar
6 Respostas
+ 4
1. Input needed data such as operation and operands; 2. Calculate a result; 3. Output the result.
15th Aug 2021, 2:50 PM
JaScript
JaScript - avatar
+ 2
Aravind Shetty you should at least check with a regex if the input is indeed a valid expression or malicious code
15th Aug 2021, 3:31 PM
Angelo
Angelo - avatar
0
while True: try: inp = input() except: inp = "" if inp == "exit" or "": break exec("print({0})".format(inp))
15th Aug 2021, 3:14 PM
Aravind Shetty
Aravind Shetty - avatar
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
15th Aug 2021, 3:16 PM
Angelo
Angelo - avatar
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.
15th Aug 2021, 4:48 PM
Aravind Shetty
Aravind Shetty - avatar
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")
16th Aug 2021, 4:16 PM
Priyanshukumar Lamba
Priyanshukumar Lamba - avatar