11 python基础--结构控制

11.1 结构分类

顺序结构、分支结构、循环结构

11.2 分支结构

单分支、二分支、多分支
11.2.1 单分支
guess = eval(input(''))
if guess == 99:
    print('猜对了')
11.2.2 二分支
guess = eval(input(''))
if guess == 99:
    print('猜对了')
else:
    print('猜错了')
##紧凑结构:<表达式1> if <条件> else <表达式2>
guess = eval(input(''))
print('猜{}了'.format('对' if guess == 99 else '错'))
11.2.3 多分支
条件判断:>    >=   <   <=   !=  ==
条件组合:and   or   not   
score = eval(input('请输入分数:'))
if score >= 0:
  if   score >= 90:
    grade = 'A'
  elif score >= 80:
    grade = 'B'
  elif score >= 70:
    grade = 'C'
  elif score >= 60:
    grade = 'D'
  elif score >= 0:
    grade = 'E'
  print('成绩为{}'.format(grade))
else:
  print('您的输入有误')

11.2.4 异常处理
try......except.....
while True:
    try:
        x = int(input('请输入一个数字:'))
        print(x)
    except:                        ##  可替换为except ValueError:
        print('您的输入有误')

score = eval(input('请输入分数:'))
try:
  if   score >= 90:
    grade = 'A'
  elif score >= 80:
    grade = 'B'
  elif score >= 70:
    grade = 'C'
  elif score >= 60:
    grade = 'D'
  elif score >= 0:
    grade = 'E'
  print('成绩为{}'.format(grade))
except:
  print('您的输入有误')

try......except.....else....finally...
正常执行的程序在try下面执行normal excute block执行块中执行,在执行中如果发生了异常,则中断当前normal execute block 调到异常处理中开始执行,如果没有异常则会执行else中的语句(前提是有else语句),finally语句是最后一步总会执行的语句
try:
  normal excute block
except A:
  Except A handle
except B:
  Except B handle
except:
  other exception handle
else:
  if no exception,get here
finally:
  print(hello world)

11.3 循环结构

11.3.1 遍历循环
for..... in .....  可遍历字符串、列表、文件
for i in ('hello'):
    print(i,end='')

for i in range(1,10,2):         ## range()函数
    print(i,end= '')

## 99乘法口诀表
for j in range(1,10):
    for i in range(1,j):
        print('%d*%d=%d\t'%(i,j,i*j), end='')
    print(' ')
11.3.2 条件循环
while.....
a = 5
while a >= 0:
    print(a,end= ' ')
    a -=1

11.3.3 循环控制保留字
break:跳出并结束当前整个循环,执行循环后的语句
continue:结束档次循环,继续执行后续循环
for i in range(10):
    if i ==6:
        break
    print(i,end= '')
>012345

for i in range(10):
    if i == 6:
        continue
    print(i, end='')
>012345789

猜你喜欢

转载自blog.csdn.net/qq_25672165/article/details/85059339