当我在看书的时候,我发现了这个例子.

def apply_discount(product, discount):
    price = int(product['price'] * (1.0 - discount))
    assert 0 <= price <= product['price']
    return price

我以前从未见过语法0 <= price <= product['price'],很明显,它在测试价格,应该是>= 0<= product['price'].我测试了这个功能,它按预期工作.我想做更多关于语法0 <= price <= product['price']的测试.

a = 7
if 0 << a << 10:
    print('a is greater than or equal to 0 and less than or equal to 10')
else:
    print('a is not greater than or equal to 0 and less than or equal to 10')

它总是打印a is not greater than or equal to 0 and less than or equal to 10张.为什么会这样?0 << a << 10到底起什么作用?

推荐答案

<<是移位运算符,您需要使用<<=:

a = 7
if 0 <= a <= 10:
    print('a is greater than or equal to 0 and less than or equal to 10')
else:
    print('a is not greater than or equal to 0 and less than or equal to 10')

Python相关问答推荐

在Windows上启动新Python项目的正确步骤顺序

如何将桌子刮成带有Se的筷子/要求/Beautiful Soup ?

通过交换 node 对链接列表进行 Select 排序

在Pandas 日历中插入一行

返回nxon矩阵的diag元素,而不使用for循环

类型错误:输入类型不支持ufuncisnan-在执行Mann-Whitney U测试时[SOLVED]

为什么带有dropna=False的groupby会阻止后续的MultiIndex.dropna()工作?

如何找到满足各组口罩条件的第一行?

如何过滤包含2个指定子字符串的收件箱列名?

mypy无法推断类型参数.List和Iterable的区别

ConversationalRetrivalChain引发键错误

Python避免mypy在相互引用中从另一个类重定义类时失败

提高算法效率的策略?

Polars map_使用多处理对UDF进行批处理

处理Gekko的非最优解

从源代码显示不同的输出(机器学习)(Python)

使用polars. pivot()旋转一个框架(类似于R中的pivot_longer)

删除特定列后的所有列

你能把函数的返回类型用作其他地方的类型吗?'

Polars定制函数返回多列