相关疑难解决方法(0)

Python比较运算符从左到右链接/分组?

运算符优先级的Python文档说明:

同一个框组中的操作员从左到右(除了比较,包括测试,它们都具有相同的优先级和从左到右的链 - 参见比较部分......)

这是什么意思?特别:

  1. "从同一个盒子组中的操作员从左到右(除了比较......)" - 做比较不是从左到右分组?

  2. 如果比较不是从左到右分组,那么他们做了什么呢?他们"链"而不是"群体"吗?

  3. 如果比较"链"而不是"组","链接"和"分组"之间有什么区别?

  4. 什么样的例子可以证明比较运算符从左到右而不是从右到左链接?

python comparison operator-precedence associativity

16
推荐指数
1
解决办法
2309
查看次数

Python中的链式比较实际上如何工作?

Python的文件进行比较说:

比较可以任意链接,例如,x < y <= z等同于x < y and y <= z,除了y仅评估一次(但在两种情况下z都没有被评估,当x < y发现是假的时).

这些SO问题/答案对这种用法有了更多的了解:

所以像(人为的例子):

if 1 < input("Value:") < 10: print "Is greater than 1 and less than 10"
Run Code Online (Sandbox Code Playgroud)

只要求输入一次.这是有道理的.还有这个:

if 1 < input("Val1:") < 10 < input("Val2:") < 20: print "woo!"
Run Code Online (Sandbox Code Playgroud)

只询问Val2 是否 Val1介于1和10之间,只打印"呜!" 如果 Val2也是10到20之间(证明它们可以'任意链接').这也是有道理的.

但我仍然很好奇这是如何在词法分析器/解析器/编译器(或其他)级别实际实现/解释的.

上面的第一个例子基本上是这样实现的:

x = input("Value:")
1 < x and x < 10: …
Run Code Online (Sandbox Code Playgroud)

python comparison-operators python-internals

9
推荐指数
1
解决办法
533
查看次数

==和比较的逻辑是什么?

所以我在寻找问题并遇到了这个最近的问题

答案很简单,但我注意到的一件事是它实际上确实返回了SPAM精确匹配

所以这段代码

text = 'buy now'

print(text == 'buy now' in text)  # True
Run Code Online (Sandbox Code Playgroud)

返回True,我不明白为什么

我试图通过将括号放在不同的地方来找出答案

text = 'buy now'

print(text == ('buy now' in text))  # False
Run Code Online (Sandbox Code Playgroud)

返回False

text = 'buy now'

print((text == 'buy now') in text) # TypeError
Run Code Online (Sandbox Code Playgroud)

提高TypeError: 'in <string>' requires string as left operand, not bool

我的问题是这里发生了什么以及为什么会这样?

聚苯乙烯

我在 Ubuntu 20.04 上运行 Python 3.8.10

python logic boolean python-3.x

1
推荐指数
1
解决办法
36
查看次数

Why is the integer not recognized to be more than 0?

Here's something taken out of my code to check if the value is greater than 0 and if it's a number:

while(1):
        n = input("Type a number of rolls to do, to try and get 3 of the same sides in a row.")
        if n.isdigit() and int(n) > 0 == True:
            n = int(n)
            break
        else:
            print("Select a proper integer.")
Run Code Online (Sandbox Code Playgroud)

For some reason if you enter a value that should stop the loop like 10, it's seen as a wrong …

python python-3.x

0
推荐指数
1
解决办法
55
查看次数