Home > Software engineering >  How to input a condition or a command from user in python?
How to input a condition or a command from user in python?

Time:04-22

Is there any way in python to input a condition from user? for example:

import numpy as np
m = np.array([0,1,2,3,4,5])
condition = input() # for example 'm > 50'
print( m [condition])  

I want a result of m[m>5] but I want to input this condition from user. Is there any way?

CodePudding user response:

Yes, there is a way. You can do it using the built-in eval() function but only if you can trust the input source. If you cannot, the user can supply harmful input that can corrupt your system. eval is known to be potentially very dangerous. eval takes its string argument, parses it and evaluates it as a Python expression. This can be an arbitrary Python expression. One concern is that Python permits users to access and delete system files (e.g. via the os module). So a bad-actor may supply dangerous data that you feed into eval, which could corrupt your system. This is why you need to be extra careful that you can trust the input source before supplying it to eval.

If you know, for example, that the condition will always be something like m ? x where ? is one of <, <=, >=, ==, >, then a safer approach is the following. You can first let the user input one of those options and check to make sure the user entered one of them. Then you can let the user enter the number x. You can then use eval to evaluate the concatenated string. For example,

import numpy as np

m = np.array([0,1,2,3,4,5])

select = {'<', '<=', '>', '>=', '=='}

sym = input("Enter one of <, <=, >, >=, ==: ")
if sym not in select:
    print("Invalid input")
    exit()
num = float(input("Enter number: "))

condition = eval('m '   sym   repr(num))
print(m[condition])

Example Session

Enter one of <, <=, >, >=, ==: >
Enter number: 3
[4 5]

Example Session

Enter one of <, <=, >, >=, ==: harmful_code
Invalid input

CodePudding user response:

You can do something similar with eval, I think:

x = 5
condition = input('condition: ')
if eval(condition):
    print('yes')

And than in input write like x==5 or x>2 etc. and it should work.

  • Related