比较可以任意链接,例如,
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) 所以我在寻找问题并遇到了这个最近的问题
答案很简单,但我注意到的一件事是它实际上确实返回了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
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 …