Python Forum

Full Version: cacul in variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
hello,
I'd like to do an operation in a variables like

1.calcul = input("enter a calculation: ")
2.x = 1
3.print(calcul)

>>>enter a calculation: 4x+1
>>>4x+1

4x+1 is not the response I'm waiting for
I wait 5
is it possible???
thank you in advance
Yes. The calculation must be valid Python (so 4x+1 will not work, where 4*x+1 will), but the eval() function will do the calculation.

I understand that there are a number of concerns about using this relating to security, but for personal use should be ok.

print(eval(input("Enter calc: ")))
I just want to reiterate that eval is EXTREMELY DANGEROUS and it allows a user of your script to execute arbitrary code (e.g. crash your computer, turn it into a bot, etc.). If you're just running the script on your laptop, it's probably fine, but if you put this code on a webserver you'd be in trouble.