一、选择语句if、else与elif
单分支
if 判断语句:
执行语句1 #执行语句前缩进表示该语句属于if的结构中
执行语句2
...
# 如果缩进的语法不严格遵守,容易导致程序崩溃
双分支
if 判断语句:
执行语句
...
else:
执行语句
...
多分支
if 判断语句:
执行语句
...
elif 判断语句:
执行语句
...
else:
执行语句
...
示例:
# 单分支
ageStr = input("Input your age:")
age = int(ageStr)
if age > 10:
print("age:{}".format(age))
# -------------------------------------------
# 双分支
numStr = input("Input your data:")
num = int(numStr)
if num > 100:
print("num > 100")
else:
print("num <= 100")
# --------------------------------------------
# 多分支
dayStr = input("Input a number:")
day = int(dayStr)
if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
elif day == 4:
print("Thursday")
elif day == 5:
print("Friday")
elif day == 6:
print("Saturday")
elif day == 7:
print("Sunday")
二、while循环语句
while 判断语句: # 当判断语句为False时结束
执行语句1 # 缩进表示该执行语句在while结构中
执行语句2
...
示例(猜拳游戏):
import random # 导入随机数模块
count = 1
personScore, computerScore = 0, 0
while count <= 5:
print("当前得分Person:Computer 为 {} : {}".format(personScore, computerScore))
person = int(input('请出手:[0:石头 1:剪刀 2:布]: ')) # 数据类型转换
computer = random.randint(0, 2) # 取0~2的随机int型整数
if person==0 and computer==1:
print("你赢得一分")
count += 1
personScore += 1
elif person==0 and computer==2:
print("电脑赢得一分")
count += 1
computerScore += 1
elif person==1 and computer==0:
print("电脑赢得一分")
count += 1
computerScore += 1
elif person==1 and computer==2:
print("你赢得一分")
count += 1
personScore += 1
elif person==2 and computer==0:
print("你赢得一分")
count += 1
personScore += 1
elif person==2 and computer==1:
print("电脑赢得一分")
count += 1
computerScore += 1
elif person==computer:
print("平局,不计分")
print("最终比分 Person:Computer")
print(" {} : {}".format(personScore, computerScore))
if personScore>computerScore:
print("你胜利了!")
else:
print("电脑获胜了!")
三、for循环语句
语法
for 变量名 in 数据容器(集合):
执行语句
...
# 变量代表容器中的每一项数据,循环就是遍历容器中的每一项数据
# 变量名可以自定义且只能在该循环结构中使用
示例:
class = ' TaiZhou电子与信息工程学院 ' # 字符串本身就是一个容器
for item in class:
print(item)
pass # 空语句,不做任何操作
range函数
生成一个数据集合列表,语法为
range(起始值,终止值,步长)
# 该集合包含初始值,最大为终止值-1,即左闭右开
# 不设置步长代表默认步长为1
range()函数常用在for循环中
示例:
sum = 0
for item in range(1,11,2):
sum += item
print("item: %d" % item)
print("总和sum: %d" % sum)
pass
break
退出整个循环
continue
结束本次循环,进行下一次循环
四、特殊结构
for-else
or循环后面接一个else结构
只有当for循环被break终止时,else中的语句才不会运行
示例:
account = 'lzh'
password = '123'
for i in range(3):
zh = input("输入账号:")
mm = input("输入密码:")
if account == zh and password == mm:
print("账号登录成功!")
break # break若执行则不执行else中的语句
# 只要for循环不被break终止,则执行else中的语句
else:
print("账号登录超过三次!")
while-else
while循环后面接一个else结构
和for-else一样,只要while循环中执行了break,else的语句就不执行