1

What is the best way to achieve this:

user_input = ">"

if 2 user_input 3:
    print("yes")

I want to avoid writing another if statement:

if user_input == ">":
    if 2 > 3:
        print("yes")
Asocia
  • 5,935
  • 2
  • 21
  • 46
Raphael Hen
  • 83
  • 1
  • 6

6 Answers6

6

You can use operator module:

from operator import gt, lt
op_dict = {">": gt, "<": lt}
user_input = input("Enter comparison operator: ")
comp = op_dict[user_input]
if comp(2, 3):
    print("Yes")
Asocia
  • 5,935
  • 2
  • 21
  • 46
4

You could map user inputs to different functions, which then you can select and apply to your numbers.

Example:

commands = {
  ">" : lambda x, y : x > y,
  "<" : lambda x, y : x < y,
  ">=": lambda x, y : x >= y
}

user_selection = input() # say ">" is chosen
if commands[user_selection](2, 3):
    print("yes")
Cihan
  • 2,267
  • 8
  • 19
2

You can try this:

if user_input == ">":
    print("yes\n"*(2 > 3), end='')
Abhinav Goyal
  • 1,312
  • 7
  • 17
2

You can use eval to evaluate any expression.

As per you above code. The output can be achieved in below way.

user_input = ">"

if eval("2"+user_input+"3"):
    print("yes")
Surajit Mitra
  • 414
  • 8
  • 15
  • 4
    You can use `eval` but you shouldn't use `eval`. In 99,9% of all cases there is a better way. Read: [Eval really is dangerous.](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) – Matthias Jun 20 '20 at 09:29
1

So simple, if you wanna avoid another if statement just use and operator

user_input = ">"
n1 = 2
n2 = 3
if user_input == ">" and n1 > n2:
        print("yes")
Peyman Majidi
  • 1,777
  • 2
  • 18
  • 31
0

You can make use of the eval function to evaluate a string as a statement:

user_input = ">"
n1 = 2
n2 = 3

if eval(str(n1) + user_input + str(n2)):
   print("yes")
Alex
  • 795
  • 1
  • 7
  • 11