I need to read the comparison operators from the keyboard. But I can't figure out how to take an operator from the list and compare something. Tell me please.
l =[] while True: s = str(input('Введите(>,<,==,>=,<=): ')) if not s: break l.append(s) I need to read the comparison operators from the keyboard. But I can't figure out how to take an operator from the list and compare something. Tell me please.
l =[] while True: s = str(input('Введите(>,<,==,>=,<=): ')) if not s: break l.append(s) You can use the operator module to find the corresponding function by the sign of the operator:
import operator op2f = { '<': operator.lt, '<=': operator.le, '==': operator.eq, '!=': operator.ne, '>=': operator.ge, '>': operator.gt } To compare a, b numbers using the operators entered:
a, b = 1, 2 L = [op2f[op](a, b) for op in iter(lambda: input('Введите(>,<,==,>=,<=): '), '')] It is possible through eval
a, b = 1, 2 while True: s = str(input('Введите(>,<,==,>=,<=): ')) expr = str(a) + s + str(b) print(expr, eval(expr)) Run:
Введите(>,<,==,>=,<=): > 1>2 False Введите(>,<,==,>=,<=): < 1<2 True Введите(>,<,==,>=,<=): == 1==2 False Введите(>,<,==,>=,<=): >= 1>=2 False Введите(>,<,==,>=,<=): <= 1<=2 True But the @jfs way is safer. In the case of eval any command can be passed to you, and it will be executed. Use at your own risk.
set(s) <= set('!<=>') <=> set(s) <= set('!<=>') - insolorSource: https://ru.stackoverflow.com/questions/807795/
All Articles