Home python How to make a console calculator on Python?

How to make a console calculator on Python?




I want to make a calculator on Python. When I look at the Internet how to make a calculator on Python. I come across the calculators by type Enter the first, enter the second operator. How can I do so so that you can simply write 2 + 2 and get the answer?

Answer 1, Authority 100%

Here is the most functional calculator:

print ("" Result: ", Eval (Input (" Enter: ")))

But to use it is very dangerous

Answer 2, Authority 44%

at the top level level works Read-EVAL Print Loop (REPL) .

Read reads a string and breaks it on tokens – minimal elements having an independent value. The simplest way to split onto the tokens is a regular expression that will allocate the characters of operations ‘+ – * / ()’ and numbers.

print Prints the answer.

Eval The tokens sequences calculates the value. For calculation used Algorithm of the Sorting Station .
Shunting-Yard Algorithm – more detailed presentation, in English.

The algorithm of the sorting station translates the usual algebraic (it is also called infix) entry in Reverse Polish notation (postfix record). Several examples:

1 - 2 - & gt; 12 -
1 - 2 * 3 - & gt; 1 2 3 * -
(1 - 2) * 3 - & gt; 1 2 - 3 *

Postfix recording costs without brackets. Calculate the value of the expression in such a record can be using a stack. To write 1 2 3 * - The sequence of actions will be like this:

token stack comment
   [] At the beginning of the stack is empty
1 [1] number 1 put on the stack
2 [1 2] number 2 put on the stack
3 [1 2 3] number 3 put on the stack
* [1 6] Select two numbers from the stack and put back their work back
- [-5] Choose from the stack two numbers and put their difference ago

Java can be put in a hundred lines. On Python I think that fifty enough.

Answer 3, Authority 22%

You can try to equate to a numeric variable before it gives an exception due to + or operator, then save it into the strengthening variable, and then the next number is simply to save to the numeric variable, and then simply the condition if the string variable is equal to + or minus, then we perform an operation with result = num1 + num2.
Something like this.

Answer 4, Authority 22%

def f (inp):
  res = []
  N = 0.
  For i in Range (Len (INP)):
    IF InP [i] in ("+", "-", "*", "/"):
      Res.APPEND (INT (INP [N: I]))
      RES.APPEND (INP [I])
      n = i + 1
  Return Res.

This code separates the string into parts, for example 5 * 6/7 it will turn into [5, "*", 6, "/", 7]

Answer 5, Authority 22%

Here is the most functional calculator:

import os
OS.System ("BC")

and use not dangerous.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions