Python真相解读

Python truth interpretation

我正在上Python课程,以下是示例代码片段;我明白了:

# A program that reads a sequence of numbers
# and counts how many numbers are even and how many are odd.
# The program terminates when zero is entered.

odd_numbers = 0
even_numbers = 0

# Read the first number.
number = int(input("Enter a number or type 0 to stop: "))

# 0 terminates execution.
while number != 0:
    # Check if the number is odd.
    if number % 2 == 1:
        # Increase the odd_numbers counter.
        odd_numbers += 1
    else:
        # Increase the even_numbers counter.
        even_numbers += 1
    # Read the next number.
    number = int(input("Enter a number or type 0 to stop: "))

# Print results.
print("Odd numbers count:", odd_numbers)
print("Even numbers count:", even_numbers)

然后这部分出现在课程中:

Try to recall how Python interprets the truth of a condition, and note that these two forms are equivalent:

while number != 0: and while number:.

我在上面的代码中替换了 while number:,代码运行正常。

我不明白为什么 while number: 意味着 while number !=0

谁能给我解释一下?谢谢!

它与真值和假值有关,在 article 中有更好的解释。

基本上,当您使用 whileif 运算符时,您是在布尔上下文中计算该值,0 被视为虚假值,因此它计算为 False.

in Python False0 有点相同,对于 True1。正如上面评论中提到的@Matiis。

while number

或任何看起来像这样的东西,意味着 这个 变量 都不等于 FalseNone,同样适用于if

if number

正如另一位用户所说,这具有相同结果的原因是因为在 while 循环的上下文中 0 被解释为 False,而除 0 之外的任何内容都被解释为 True。

因此,当数字不是 0 时,while numberwhile number != 0 都为真。

同时期待一个布尔值 和 bool(0) returns 假

bool(0)
False

bool(10)
True

0 != 0
False

10 != 0
True

这就是为什么

while number != 0

相同
while number