Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
cacul in variable
#1
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
Reply
#2
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: ")))
Reply
#3
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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020