Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to make a mathematical opperation happen from a string input?

I just made a quick counter in phython were you just have to type in the following number, one by obe (as some of you might have seen on some discord servers)

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

This is the original code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading