Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用用户输入作为比较运算符?_Python - Fatal编程技术网

Python 如何使用用户输入作为比较运算符?

Python 如何使用用户输入作为比较运算符?,python,Python,实现这一目标的最佳方式是什么: user_input = ">" if 2 user_input 3: print("yes") 我希望避免编写另一个if语句: if user_input == ">": if 2 > 3: print("yes") user_input = ">" n1 = 2 n2 = 3 if eval(str

实现这一目标的最佳方式是什么:

user_input = ">"

if 2 user_input 3:
    print("yes")
我希望避免编写另一个if语句:

if user_input == ">":
    if 2 > 3:
        print("yes")
user_input = ">"
n1 = 2
n2 = 3

if eval(str(n1) + user_input + str(n2)):
   print("yes")
您可以使用操作员模块:

您可以使用操作员模块:


您可以将用户输入映射到不同的函数,然后您可以选择并应用到您的数字

例如:

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

您可以将用户输入映射到不同的函数,然后您可以选择并应用到您的数字

例如:

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")
您可以尝试以下方法:

if user_input == ">":
    print("yes\n"*(2 > 3), end='')
您可以尝试以下方法:

if user_input == ">":
    print("yes\n"*(2 > 3), end='')
可以使用eval函数将字符串作为语句进行求值:

if user_input == ">":
    if 2 > 3:
        print("yes")
user_input = ">"
n1 = 2
n2 = 3

if eval(str(n1) + user_input + str(n2)):
   print("yes")
可以使用eval函数将字符串作为语句进行求值:

if user_input == ">":
    if 2 > 3:
        print("yes")
user_input = ">"
n1 = 2
n2 = 3

if eval(str(n1) + user_input + str(n2)):
   print("yes")

很简单,如果你想避免另一个if语句,只需使用and运算符


很简单,如果你想避免另一个if语句,只需使用and运算符


可以使用eval对任何表达式求值

按照你上面的代码。输出可以通过以下方式实现

user_input = ">"

if eval("2"+user_input+"3"):
    print("yes")

可以使用eval对任何表达式求值

按照你上面的代码。输出可以通过以下方式实现

user_input = ">"

if eval("2"+user_input+"3"):
    print("yes")
使用和操作员!!如果用户输入==>和2>3:使用and运算符!!如果用户输入==>和2>3:您可以使用eval,但不应该使用eval。在99.9%的情况下,有更好的方法。阅读:你可以使用eval,但不应该使用eval。在99.9%的情况下,有更好的方法。阅读: