一、if语句
if语句由关键字if、判断条件和冒号组成,if语句和从属于该语句的代码段可组成选择结构。
if 条件表达式:
代码块
若if语句的判断条件成立(判断条件的布尔值为True),执行之后的代码段;若if语句的判断条件不成立(判断条件的布尔值为False),跳出选择结构,继续向下执行。
二、 if-else语句
if 判断条件:
代码块1
else:
代码段2
age = 18
if age >= 18:
print('你已成年!')
else:
print('你未成年!')
# 通过身份证号判断性别:
sfz = input("请输入身份证号码:")
sex = sfz[-2]
sexx = int(sex) % 2
if sexx == 0:
print("是女生!")
else:
print("是男生!")
你已成年!
执行if-else语句时,若判断条件成立,执行if语句之后的代码段1;若判断条件不成立,执行else语句之后的代码段2。
三、if-elif-else语句
if 判断条件1:
代码段1
elif 判断条件2:
代码段2
elif 判断条件3:
代码段3
...
else:
代码段n
holiday_name = '植树节'
if holiday_name == '情人节':
print('买礼物,买花,买包,买化妆品')
elif holiday_name == '愚人节':
print('吃饭')
else:
print('不过节')
不过节
执行if-elif-else语句时,若if条件成立,执行if语句之后的代码段1;若if条件不成立,判断elif语句的判断条件2:条件2成立则执行elif语句之后的代码段2,否则继续向下执行。以此类推,直至所有的判断条件均不成立,执行else语句之后的代码段。
四、 if嵌套
if 判断条件1: # 外层条件
代码段1
if 判断条件2: # 内层条件
代码段2
...
# 性别 1 男 0 女
gender = 0
# 成绩(秒)
score = 9
# 依据男女进行分组
if gender == 1:
print('进入男生组')
# 男生合格成绩为10秒
if score <= 10:
print('男生成绩合格')
else:
print('男生成绩不合格')
else:
print('进入女生组')
# 女生合格成绩为15秒
if score <= 15:
print('女生成绩合格')
else:
print('女生成绩不合格')
进入女生组
女生成绩合格
a=[1,2,4,7,9,8,3]
d=len(a)
for i in range(d):
if max(a) == a[i]:
a[0], a[i] = a[i], a[0]
if min(a) == a[i]:
a[-1], a[i] = a[i], a[-1]
print(a)
[9, 2, 4, 7, 3, 8, 1]
执行if嵌套时,若外层判断条件(判断条件1)的值为True,执行代码段1,并对内层判断条件(判断条件2)进行判断:若判断条件2的值为True,则执行代码段2,否则跳出内层条件结构,顺序执行外层条件结构中内层条件结构之后的代码;若外层判断条件的值为False,直接跳过条件语句,既不执行代码段1,也不执行内层的条件结构。
五、while语句
while语句一般用于实现条件循环,该语句由关键字while、循环条件和冒号组成,while语句和从属于该语句的代码段组成循环结构。
while 条件表达式:
代码块
# while的基本使用
i = 1
while i <= 3:
print(i)
i += 1
1
2
3
# 求最大公约数
def gcd(x, y):
while y:
t = x % y
x = y
y = t
return x
print(gcd(4,6))
2
break
跳出整个while循环
result = 0
i = 1
while i <= 7:
result += i
i += 1
if i > 5:
break
print("result=", result)
result= 15
continue
i = 0
while i <= 6:
i += 1
if i == 3:
continue
# continue不执行满足条件的循环
# 跳出该次循环后继续执行后面的条件
print(i)
1
2
4
5
6
7
#猜数小游戏
print("This is the third question:")
import random
d = random.randint(1, 100)
count=0
print("下面是猜数字游戏环节!")
while True:
count+=1
if 3-count<0:
print("3次机会用完了,重新开始!!")
break
number=int(input("请输入一个1-100以内的数字:"))
if number > d:
print("你猜的数字太大了!还有{0:d}次机会!".format(3-count))
elif number < d:
print("你猜的数字太小了!还有{0:d}次机会!".format(3-count))
else:
print("恭喜你!你猜对啦!!")
print()
六、for语句
for语句一般用于实现遍历循环。遍历指逐一访问目标对象中的数据,例如逐个访问字符串中的字符;遍历循环指在循环中完成对目标对象的遍历。
for 临时变量 in 目标对象:
代码块
for i in range(5):
if i == 5:
exit()
print(i)
print('nice')
0
1
2
3
4
nice
# for循环打印99乘法表
print("This is the second question:")
for c in range(1, 10):
for b in range(1, c+1):
print('{}*{}={:<5d}'.format(c, b, c*b), end='')
print()
print()
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81