I.条件语句(if-elif-else)
用于条件判断,其基本格式为:
if 条件句:
代码块
......
elif 条件句:
代码块
......
else:
代码块
注意:其中elif 和else的部分是不一定会使用到的。
例如:
x=10
#First case
if x>5:
print("Success!")
#Second case
if x>6:
print("Success!")
else:
print("Fail!")
x=5
#Third case
if x>6:
print("Success!")
elif x<=6 and x>0:
print("Fail!")
else:
print("Error!")
II.循环语句(for和while语句)
1,while语句
基本格式:
while 表达式:
代码
执行过程:
- 首先,判断表达式是否为真
- 如果为真,则执行代码
- 如果为假,则退出循环
注意:小心考虑条件的设置,否则会出现死循环。
i=1
while i<20:
if i%2==0:
print(i,end=" ")
i+=1
#output:2 4 6 8 10 12 14 16 18
进阶格式:
while 表达式:
代码1
else:
代码2
执行过程:
- 首先,判断表达式是否为真
- 如果为真,则执行代码1
- 如果为假,则执行代码2
i=20
while i%2==0:
print("True")
i-=1
else:
print("False")
i-=1
'''
Output:
True
False
'''
2,for语句
作用:for语句主要用来遍历可迭代对象;
可迭代对象:一般指容器内可被循环遍历获取内部所有元素;例如:字符串,列表等。
基本语法:
for item in iters:
代码
其中for和in都是关键字。
执行过程:
- 每次从iters中取一个对象
- 将取出对象赋值给item
- 执行代码1
- 继续重复1,直至items中的值取完
- 遍历结束,触发异常:StopIteration;for语句处理异常,然后结束
for item in "12":
print(item,end=" ")
'''
Output:
1 2
'''
重要函数:
- range():
作用:产生range对象,对象中每个元素为数字
基本格式:
range(stop)->range object
range(start,stop[, step])->range object
参数说明:start为起始值;stop为结束值,最大值为stop-1;step为步进值,为可选参数
例如:
#get numbers that are smaller than 10
for i in range(10):
print(i,end=" ")
#Output: 0 1 2 3 4 5 6 7 8 9
for i in range(0,10):
print(i,end=" ")
#Output: 0 1 2 3 4 5 6 7 8 9
#get even numbers that are smaller than 10
for i in range(0,10,2):
print(i,end=" ")
#Output: 0 2 4 6 8
- enumerate()
作用:将可迭代对象转换为enumerate对象。
基本格式:enumerate(iterable, start=0)(注意:start默认等于0)
enumerate对象内容:
未指定start:可迭代对象的索引和索引对应的内容
(0,iter[0]),(1,iter[1])......
指定start: (0+start,iter[0]),(1+start,iter[1])......
例如:
s="Hello!"
for i in enumerate(s):
print(i,end=" ")
#Output:(0, 'H') (1, 'e') (2, 'l') (3, 'l') (4, 'o') (5, '!')
for i in enumerate(s,2):
print(i,end=" ")
#Output:(2, 'H') (3, 'e') (4, 'l') (5, 'l') (6, 'o') (7, '!')
III. break和continue
两者都必须和循环语句结合使用。
1,break:
作用:跳出当前循环。
基本逻辑:(以while语句为例)当判断while语句的条件为真时,执行while语句内部的代码块。如果满足内部的if语句的条件,则执行if语句内的代码,遇到break语句后跳出循环,否则继续循环。
例如
while True:
i=int(input("Enter a number:"))
if i>1:
print("Success!")
break
'''
Output:
Enter a number:0
Enter a number:1
Enter a number:3
Success!
'''
2,continue:
作用:结束本次循环
基本逻辑:(以while语句为例)当判断while语句的条件为真时,执行while语句内部的代码块。如果满足内部的if语句的条件,则执行if语句内的代码,遇到continue语句后不再执行之后的代码,进行下一次循环。
例如:
i=0
while i<=20:
if i%2:
i+=1
print(i, end=" ")
i+=1
'''
Output:
0 2 4 6 8 10 12 14 16 18 20
'''
for语句类似。
IV.小结
- 条件语句if-elif-else
- 循环语句for和while
- range和enumerate函数的用法
- break和continue语句的用法和作用