Search code examples
pythonpython-2.7inputraw-input

forcing a program to calculate an input


I was wondering if I could force the program to calculate an input before converting it to an integer. for example my code is

    shift=int(raw_input("input the shift you want "))

If I was to input 4**2 which should then in theory equal 16 however as the raw input is a string this cannot happen. I would like to know if there was force the program to calculate the input meaning if I inputted a calculation then the program would work it out instead of just converting it to an integer and causing an error.


Solution

  • If you don't mind being terribly unsafe, you can use eval, which accepts a single string argument as input, and executes it as Python code:

    shift = eval(raw_input("input the shift you want "))
    

    And here is an explanation of why you shouldn't do this in any kind of production code.

    A better option is to actually build a proper parser to behave like a calculator. There are plenty of resources for this floating around SO and elsewhere online.