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")
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")
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")
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")
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")
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")
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")