一、选择结构
1、if-else结构
if 条件: #没有括号,直接用冒号结尾
满足条件时要做的事情1 #注意缩进
满足条件时要做的事情2
满足条件时要做的事情3
...(省略)...
else:
不满足条件时要做的事情1
不满足条件时要做的事情2
不满足条件时要做的事情3
...(省略)...
其中的条件一般为关系(比较)运算符,可参考https://mp.csdn.net/editor/html/115433933
关键词:无括号、有冒号、缩进,可只有if
2、if--elif-else
score = 77
if score>=90 and score<=100:
print('本次考试,等级为A')
elif score>=80 and score<90:
print('本次考试,等级为B')
elif score>=70 and score<80:
print('本次考试,等级为C')
elif score>=60 and score<70:
print('本次考试,等级为D')
elif score>=0 and score<60:
print('本次考试,等级为E')
关键词:最后else可以没有,和1中只有if一个道理;elif
3、if嵌套
chePiao = 1 # 用1代表有车票,0代表没有车票
daoLenght = 9 # 刀子的长度,单位为cm
if chePiao == 1:
print("有车票,可以进站")
if daoLenght < 10:
print("通过安检")
print("终于可以见到Ta了,美滋滋~~~")
else:
print("没有通过安检")
print("刀子的长度超过规定,等待警察处理...")
else:
print("没有车票,不能进站")
print("亲爱的,那就下次见了,一票难求啊~~~~(>_<)~~~~")
二、循环结构while和for循环
1、while循环
i = 0
while i<5:
print("当前是第%d次执行循环"%(i+1))
print("i=%d"%i)
i+=1
#encoding=utf-8
i = 1
sum = 0
while i<=100:
if i%2 == 0:
sum = sum + i
i+=1
print("1~100的累积和为:%d"%sum)
以上为计算1~100之间偶数的累积和while程序。
2、for循环
for循环的格式:
for 临时变量 in 列表或者字符串等:
循环满足条件时执行的代码
其实for的用法还有很多,后面会在实例中看到。
3、break与continue
-
break的作用:用来结束整个循环
-
continue的作用:用来结束本次循环,紧接着执行下一次的循环
-
break/continue只能用在循环中,除此以外不能单独使用
-
break/continue在嵌套循环中,只对最近的一层循环起作用
if、while、for等其他语句可以随意组合,这样往往就完成了复杂的功能。