python学习笔记8(Loops)

Week7
Charpter5
5.1 Loops and iterations(循环与迭代)
知识点1: While循环

n = 6
while n > 0:
    print(n)
    print('check it')
    n = n - 1
print('Loop out')
print(n)

输出结果为:
6
check it
5
check it
4
check it
3
check it
2
check it
1
check it
Loop out
0

知识点2: 跳出循环-break
例如:

while True:
    line = input('>>')
    if line == 'done':
        break
    print(line)
print('Done!')

输出结果为:

asdaa
asdaa

sdfsd
sdfsd

done
Done!


注意:break是跳出当前循环!调到模块最后一行的后一行。(往下跳),与continue形成对比。

知识点3: 跳到当前循环的顶部,continue

while True:
    line = input('>>')
    if line[0] == '#':
        continue
    elif line == 'done':
        break
    print(line)
print('Done!')

输出结果为:

qwe
qwe

#Hello
Hello
Hello

done
Done!

但是前提条件是该循环下面没有别的循环了,因为其根本上是跳出当前循环,跳到下一个循环。

知识点4: Definite loop定环,就是for循环

friends = ['Gary' , 'Tom' , 'Curry']
for friend in friends:
    print(friend)
print('Done!')

输出结果为:
Gary
Tom
Curry
Done!
for主要用于字符串、数组等。

知识点5: 举出的几个for的用处,例如数个数,求和,求平均数,筛选出符合要求的数,找出最大的数,找出最小的数等等。

知识点6: 引出了另一种类型的变量,就是Boolean型,只有True和False

知识点7: 引出了另一种类型的variable,就是None,例如:

smallest = None  #相当于是一个flag value
for value in [2,5,35,23,678,54,12 , 0 , -3]:
    if smallest is None:   #判断是第一次进for循环,可以理解为启动,触发。
        smallest = value
    elif value < smallest:
        smallest = value
print(smallest)
print('Done')

一般来说比较大小会在第一个给smallest附一个值,但是这个值不具有普遍性,所以采用None
注意,这里的is,和 “==” 很相似,但是要比其强很多。
同理,也有is not
一般来说,当后面是True,False或None时,应该使用is和is not
而双等号就是一个普通的数学上的东西。

猜你喜欢

转载自blog.csdn.net/weixin_43593303/article/details/89106673