Python 为什么while循环中的缩进会产生问题?
我想用Python中的while循环创建一个1到14的列表,其中不包含5和10,而这似乎是一个缩进问题。为什么缩进会产生while循环问题 下面是我之前和之后的代码 之前的代码:Python 为什么while循环中的缩进会产生问题?,python,python-3.x,while-loop,indentation,Python,Python 3.x,While Loop,Indentation,我想用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 numbe
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
数字=1
而数字这样做可能更容易理解
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
total=0
数字=0
虽然Python中的数字缩进不仅仅是为了可读性,它还创建了一个新的代码块,请查看更多信息。
在第一个发布的代码中,行:
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))
第一个代码中的while numbertotal+=number
和number+=1
直到while循环完成后才被执行,而在第二个代码块中,它们与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))