主要内容
- if 控制
- for 循环
- range()函数
- break,continu 语句
- pass
if控制
当进行多个条件判断时,可以使用 if ... elif ... elif ... else
elif 其它判断条件。
else 所有条件都不执行。
>>> x = int(input("Please enter an integer: "))Please enter an integer: 42>>> if x < 0:... x = 0... print('Negative changed to zero')... elif x == 0:... print('Zero')... elif x == 1:... print('Single')... else:... print('More')...More
for循环
可以对 list,string等类型进行for循环。
>>> #List中添加一些字符串:... words = ['cat', 'window', 'defenestrate']>>> for w in words:... print(w, len(w))...cat 3window 6defenestrate 12
>>> for w in words[:]: # 循环过程中可以对List中的元素进行修改... if len(w) > 6:... words.insert(0, w) # 将w 复制一份放到 words的第一位 【0 表示words 索引】...>>> words['defenestrate', 'cat', 'window', 'defenestrate']
range() 函数
迭代生成一组数字,默认从0开始,每个累加1,到n-1 结束。
>>> for i in range(5):... print(i)...01234
也可以指定生成。
range(5, 10) # 5开始,累加1,最后一个数字小于105, 6, 7, 8, 9range(0, 10, 3) # 0开始,累加3,最后一个值小于100, 3, 6, 9range(-10, -100, -30) # -10开始,累加-30,负数累加最后不能小于或等于 -100-10, -40, -70
工作中最常与for循环一起遍历List等数据。
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']>>> for i in range(len(a)):... print(i, a[i])...0 Mary1 had2 a3 little4 lamb
range()生成List 数据
>>> list(range(5))[0, 1, 2, 3, 4]
break ,continue
在for循环或者while循环中,使用break 直接跳出循环,不再往下执行。
>>> for n in range(2, 10):... for x in range(2, n):... if n % x == 0:... print(n, 'equals', x, '*', n//x)... break... else:... # loop fell through without finding a factor... print(n, 'is a prime number')...2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49 equals 3 * 3
continue 会中断当前迭代,然后继续运行下一个迭代,而不是把这个迭代全部中断
>>> for num in range(2, 10):... if num % 2 == 0:... print("Found an even number", num)... continue... print("Found a number", num)Found an even number 2Found a number 3Found an even number 4Found a number 5Found an even number 6Found a number 7Found an even number 8Found a number 9
pass
作为占位符使用,什么不会执行
>>> while True:... pass # 按下快捷键 Ctrl+c (Windows 操作系统) 或 Command+c(Mac系统)终止...
定义一个class时
>>> class MyEmptyClass:... pass...
函数中使用时
>>> def initlog(*args):... pass # Remember to implement this!...
