0

User enters an input like this: 4*3**2 Is there anyway to perform this, as a python code (not string)? I mean something like this:

x = input('Enter a operation: ') # 4*3**2
print('Answer is:', x) # expect: 'Answer is: 36'
DANIEL1475
  • 15
  • 4

1 Answers1

3

You could use eval:

x = input('Enter a operation: ')
print('Answer is:', eval(x))

But the problem is that eval is unsafe and inefficient, see this for more information.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
  • Hmm. But if someone could see ```eval()``` it could turn out to be really dangerous –  Aug 17 '21 at 06:24
  • @Sujay I mentioned that under – U13-Forward Aug 17 '21 at 06:25
  • its insecure, because user can enter other thing and reveal my code, (is it correct?) so what if I use if statement to limit user and let him just use some special characters, like 1-9 and * and / and + and - ....? – DANIEL1475 Aug 17 '21 at 13:12