sanhutrees 发表于 2017-5-6 09:59:51

Learn Python The Hard Way学习(33)

下面学习一个新的循环,while循环,如果while的布尔表达式一直是True,那么会不断的重复执行代码块。



等等,我们不是在学习一个新的术语吗?用冒号结束一行语句,然后开始新的代码段,使用缩进区别这些代码段,好吧,这就是python的语言结构,如果你还是很明白,回去多练习前面的for,if和函数。




后面我们会有一些练习让你记住这些结构,就像前面记住布尔表达式一样。




回到While循环,刚开始它和if一样,进入代码段执行,只是while循环执行完代码段后会回到这个代码段的顶部,重复执行,直到while的布尔判断为False为止。




这里有个问题:while循环有可能一直不会停止,不过你还是希望循环最终能够停止的。




为了解决这个问题,我们列出了一下规则:


[*]不到万不得已不要使用while,可以用for代替。
[*]仔细检查你的while声明,确保有条件让它返回False。
[*]如果有怀疑的话,在代码段的头部和底部打印变量的值来判别。

下面看我是怎么做的:



i = 0
numbers = []

while i < 6:
print "At the top i is %d" % i
numbers.append(i)

i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i

print "The numbers: "

for num in numbers:
print num






运行结果

root@he-desktop:~/mystuff# python ex33.py

At the top i is 0

Numbers now:

At the bottom i is 1

At the top i is 1

Numbers now:

At the bottom i is 2

At the top i is 2

Numbers now:

At the bottom i is 3

At the top i is 3

Numbers now:

At the bottom i is 4

At the top i is 4

Numbers now:

At the bottom i is 5

At the top i is 5

Numbers now:

At the bottom i is 6

The numbers:

0

1

2

3

4

5






加分练习

1. 把这个while循环写到一个函数中,用一个变量传递6这个值。

def while_function(i):
j = 0
numbers = []
while j < i:
numbers.append(j)
j += 1

return numbers

numbers = while_function(6)






2. 使用这个函数打印不同的数字。




3. 添加一个参数到函数中,让它可以根据这个参数修改增量值,就是i=i+1这里。

def while_function(i, increment):
j = 0
numbers = []
while j < i:
numbers.append(j)
j += increment

return numbers

numbers = while_function(6, 2)






4. 使用上面的函数运行一下。




5. 使用for循环和range函数实现上面的代码。

def for_function(i, increment):
numbers = []
for j in range(0, i, increment):
numbers.append(j)
return numbers

numbers = for_function(6, 2)






如果你调试代码的时候进入了无限循环,可以用ctrl+c退出。
页: [1]
查看完整版本: Learn Python The Hard Way学习(33)