Search code examples
pythonmathcounter

Is it possible to perform a mathematical operation based on a string input?


I just made a quick counter in Python where you just have to type in the following numbers, one by one (as some of you might have seen on some Discord servers)

I wanted to make it more interesting by adding the possibility of typing mathematical operations in the input, so that if the next number is 3 you can type 2+1, but it didn't go well.

This is the original code:

contador = 0
operaciones = ["+","-","*","/"]

while True:
    if contador == 0:
        numero = int(input("¡Comenzamos! Estamos en 0: "))
        if numero == contador + 1:
            contador = numero
        else:
            print("¡Has perdido!")
            break

    numero = int(input("Introduce el siguiente número: "))
    if numero == contador + 1:
        contador = numero
    else:
        print("¡Has perdido!")
        break

When running it, this is the error message I get: invalid literal for int() with base 10: '2+1'
Then I tried changing the inputs to string instead of int, but it just wouldn't work.


Solution

  • You can use the eval() function:

    print(eval('2 + 1'))
    

    will print 3!

    Also, it works to convert strings to other types of variables!

    By the way, it can be very dangerous if you put a string of functions that can, for example, delete your files, so be careful.