python_day3 【if、循环、异常】

1、分支结构
单分支 if…:
二分支 if… : else… : 【还有更加简洁的表达方式: 表达式1 if 条件 else 表达式2】

【任何非零的数值、非空的数据类型都等价于True,0等价于False】

多分支
if … :
elif …:

else …:

a = eval(input("输入数字:"))
#单分支
if a%2==1 :
    print("该数是一个奇数")
print("end1")

#二分支
if a%2==1 :
    print("该数是一个奇数")
else :
    print("该数是个偶数")
print("end2")

#多分支
if a>=6 and a<=10 :
    print("优秀")
elif a<6 and a>=3 :
    print("良好")
else:
    print("合格")
print("end3")
输出结果为:
输入数字:5
该数是一个奇数
end1
该数是一个奇数
end2
良好
end3

2、循环结构
a、遍历循环:可以是字符串、文件、range()函数或者组合数据类型
for 循环变量 in 遍历结构 :
语句块
辅助:break 【跳出当前循环】和 continue 【结束当前档次循环】

for i in range(1,5):
    print(i,end=' ')
print("end1")

string = "abcdef"
for a in string:
    if a=="d" :
        break
    print(a,end=' ')
print("end2")

for a in string:
    if a=="d" :
        continue
    print(a,end=' ')
print("end3")
输出结果为:
1 2 3 4 end1
a b c end2
a b c e f end3

【扩展模式】
for 循环变量 in 遍历结构:
语句块1
else:
语句块2
【for循环正常执行后,else才会执行】
break时,for循环属于非正常执行,else不执行

string = "abcdef"
for a in string:
    if a=="d" :
        break
    print(a,end=' ')
else:print("end2")
输出结果为:
a b c

continue时,for循环只跳出了符合if条件的那一次循环,正常执行完了,所以else语句执行

for a in string:
    if a=="d" :
        continue
    print(a,end=' ')
else:print("end3")
输出结果为:
a b c e f end3

b、无限循环
while 条件 :
语句块

n = 2
while n<10:
    print(n)
    n +=2
输出结果为:
2
4
6
8

【扩展模式】——同for中的扩展模式一样
while 条件:
语句块1
else:
语句块2

3、异常处理
try:
语句块1【正常执行的内容】
except:
语句块2【发生异常时执行的内容】

while True:
    try:
        a = eval(input("输入一个数字:"))
        break
    except:
        print("是输入数字!")
print("该数字为:{}".format(a))
当输入的是一个数字时:
输入一个数字:5
该数字为:5

当输入的不是一个数字时:
输入一个数字:4sd
是输入数字!
输入一个数字:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值