Search code examples
python-3.xlistfunctioninput

How to obtain a condition as an user input in python


Below is a code that I've being working on recently and it's aim is to obtain a condition (arithmetic or comparison) from the user as an input and check if it's legitimate for a set of pre-defined values.

The problem being that I can't find a way to convert the string input.

enter image description here

Below is what I want but with user input:

enter image description here

PS: I'm vastly inexperience :(.

I tried playing with the 'operator' module but still wasn't able to get anything.

enter image description here

The code would seem junky and I apologize for the mistakes in advance :)


Solution

  • you can simply use eval() function in python to convert your condition that is in format of string into the boolean condition which will act according to what you want, here is a code sample:

    # sample of using eval()
    a, b = 0, 2
    str_condition = "a+b > 0" # in the string format
    
    # convert it to boolean condition format
    print(eval(str_condition)) # answer: True
    

    Apply it with your user's input condition

    a = 5
    b = 9
    
    str_condition = input('enter condition: ')
    print('convert string to boolean condition:',str_condition)
    print('result from using eval:', eval(str_condition))
    

    the result of using eval() is

    enter condition: a+b == 14
    convert string to boolean condition: a+b == 14
    result from using eval: True
    

    try to use it with your code, hope this help !