为什么 while 循环中的缩进会产生问题?

Why the indentation in the while loop create problem?

我想在 Python 中用 while 循环创建一个 1 到 14 的列表,没有 5 和 10,但它出现了缩进问题。为什么缩进会产生 while 循环问题?

下面是我之前和之后的代码

之前的代码:

total = 0
number = 1
while number <= 15:
    if number%5 == 0:
        number += 1
        continue
    print("%3d"%(number), end = "")
total += number
number += 1
print("\ntotal = %d"%(total))

之后的代码
total = 0
number = 1
while number <= 15:
    if number%5 == 0:
        number += 1
        continue
    print("%3d"%(number), end = "")
    total += number
    number += 1
print("\ntotal = %d"%(total))

我希望结果是 1 2 3 4 6 7 8 9 11 12 13 14 总计 = 90

这样做你可能更容易理解

total = 0
number = 0
while number <= 15:
    #If number is not divisible by 5, add it to total
    if number%5 != 0:
        total+=number
    #Always increment the number
    number += 1
    print("%3d"%(number), end = "")
print("\ntotal = %d"%(total))
#  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16
#total = 90

Python 中的缩进不仅仅是为了可读性,它还创建了一个新的代码块,查看 Here 了解更多信息。 在第一个发布的代码行中:

total += number
number += 1

不在while区。所以它不会在循环的每次迭代中执行,而是在循环完成后执行。

Python 取决于缩进以了解循环中 运行 的语句块。

换句话说,相同的缩进 = 相同的块

我会说为块添加评论,直到您对它们感到满意为止!

while number <= 15:
    # LOOP BLOCK STARTS HERE

    if number%5 == 0:
        # IF BLOCK STARTS HERE

        number += 1
        continue

        # IF BLOCK ENDS HERE

    print("%3d"%(number), end = "")
    total += number
    number += 1

    # LOOP BLOCK ENDS HERE

print("\ntotal = %d"%(total))

如果您不将语句缩进到同一块,Python 会将它们视为不同的块。