python - 如何通过参数传递大于或小于号?

标签 python

如果可以通过参数传递 >= 符号:如下所示:

def example():
   num1 = 0
   num2 = 5
   sign1 = >=
   sign2 = <=

   test(num1, num2, sign1, sign2)

def test(num1, num2, sign1):
    while num1 sign1 0 and num2 sign2 5:
       print('whatever')
       num1+=1
       num2-=1

显然这不是我真正想做的;我只是想知道这是否可能......

最佳答案

是的,可以使用operator模块。然而,它们被视为函数而不是字符串,这正是它们在您最初的尝试中出现的样子。

from operator import le, ge

def example():
   num1 = 0
   num2 = 5
   sign1 = ge
   sign2 = le


def test(num1, num2, sign1, sign2):
    while sign1(num1, 0) and sign2(num2, 5):
       print('whatever')
       num1+=1
       num2-=1

关于python - 如何通过参数传递大于或小于号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59620349/

相关文章:

python - PVLIB - 如何使用耦合逆变器正确定义系统规模

Python theano : how does the R-operation work?

python - 计算 k 均值并绘制散点图

python - 如何将zip文件中的文件复制到某个目录?

python - 如何使用列表来避免一遍又一遍地重复 'and/or' 运算符?

Eclipse 中的 Python 分析

python - 为什么这个指令不起作用?

python - 从可能丢失的 dict 值初始化 Python 变量

python - 压缩文件路径中的所有文件

python - 在 SQL 中编写多个 LIKE 子句的另一种方法