Calculator with an Input - Python

1

I want to do a basic calculator in Python3 but I have only seen that it works using methods and conditions.

But is it possible that entering the whole operation in an Iput, obtain the same result?

Example:

             input("Ingresa tu operacion: )
                2*5
                10

Something more or less so just leave a message asking for the operation and automatically do it.

I hope to be clear

    
asked by Angel Judath Alvarez 15.02.2018 в 21:15
source

2 answers

0

what you can do is check each character to identify the operator. I made my own version of the program, check it out to see if it works. (EYE: It only works with an operand)

class Operador():
    NOOP = 0
    SUMA = 1
    RESTA = 2
    MULTIPLICACION = 3
    DIVISION = 4

entrada = input()
tamano = len(entrada)

operador = Operador.NOOP
i = 0
while operador == Operador.NOOP or i >= tamano:
    if entrada[i] == '+':
        operador = Operador.SUMA
    elif entrada[i] == '-':
        operador = Operador.RESTA
    elif entrada[i] == '*':
        operador = Operador.MULTIPLICACION
    elif entrada[i] == '/':
        operador = Operador.DIVISION
    i += 1

if(operador != Operador.NOOP):
    argumento1 = float(entrada[0:i-1])
    argumento2 = float(entrada[i:])
    if operador == Operador.SUMA:
        print (argumento1+argumento2)
    elif operador == Operador.RESTA:
        print (argumento1-argumento2)
    elif operador == Operador.MULTIPLICACION:
        print (argumento1*argumento2)
    elif operador == Operador.DIVISION:
        print (argumento1/argumento2)
else:
    print ("No se identifico el operador")
    
answered by 17.02.2018 / 06:31
source
0

Evaluating an expression as you mention is relatively simple, as NaCI has already mentioned, you can use eval which is base functionality:

from math import sqrt

valor = eval("2*3")
print(valor)
> 6

valor = eval("sqrt(4)")
print(valor)
> 2.0

But eval() does not evaluate arithmetic operations evaluates Python code, therefore it is a dangerous routine, if you are going to offer it to a user, you are opening the possibility of executing any code.

A more limited solution is to use some mathematical evaluator, there are several. Simply by way of example I can suggest py-expression-eval

The installation, in the usual way: pip install py_expression_eval

To execute it:

from py_expression_eval import Parser
parser = Parser()

valor = parser.parse('2 * 3').evaluate({})
print(valor)

Verify in PyPI , there are simpler evaluators and others more complex, the idea is always the same, offer a code evaluation more limited to the mathematical and minimize the problems due to the execution of undesired code.

    
answered by 17.02.2018 в 04:19