python基础-task03异常处理

1.条件语句

  • if语句
if 2 > 1 and not 2 > 3:
    print('Correct Judgement!')
  • if-else语句
hi = 6
if hi > 2:
    if hi > 7:
        print('好棒!好棒!')
else:
    print('切~')
  • if-eif-else语句
temp = input('请输入成绩:')
source = int(temp)
if 100 >= source >= 90:
    print('A')
elif 90 > source >= 80:
    print('B')
elif 80 > source >= 60:
    print('C')
elif 60 > source >= 0:
    print('D')
else:
    print('输入错误!')

2.assert 关键词

assert:“断言”
当这个关键词后边的条件为 False 时,程序自动崩溃并抛出AssertionError的异常。

my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0

# AssertionError

3.while语句

  • while语句
  • while-else语句
    如果while循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容。
count = 0
while count < 5:
    print("%d is  less than 5" % count)
    count = 6
    break
else:
    print("%d is not less than 5" % count)

4. for语句

  • for语句
for 迭代变量 in 可迭代对象:
    代码块
  • for-else语句
for 迭代变量 in 可迭代对象:
    代码块
else:
    代码块

5.range() 函数

range([start,] stop[, step=1])
  • 这个BIF(Built-in functions)有三个参数,其中用中括号括起来的两个表示这两个参数是可选的。
  • step=1 表示第三个参数的默认值是1。
  • range 这个BIF的作用是生成一个从start参数的值开始到stop参数的值结束的数字序列,该序列包含start的值但不包含stop的值。

6.enumerate()函数

enumerate(sequence, [start=0])
  • sequence – 一个序列、迭代器或其他支持迭代对象。
  • start – 下标起始位置。
  • 返回 enumerate(枚举) 对象。
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
lst = list(enumerate(seasons, start=1))  # 下标从 1 开始
print(lst)
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

enumerate()与 for 循环的结合使用

for i, a in enumerate(A)
    do something with a

用 enumerate(A) 不仅返回了 A 中的元素,还顺便给该元素一个索引值 (默认从 0 开始)。此外,用 enumerate(A, j) 还可以确定索引起始值为 j。

7.break&contine&pass

  • break
  • contine
    continue终止本轮循环并开始下一轮循环。
  • pass
    pass是空语句,不做任何操作,只起到占位的作用,其作用是为了保持程序结构的完整性。尽管pass语句不做任何操作,但如果暂时不确定要在一个位置放上什么样的代码,可以先放置一个pass语句,让代码可以正常运行。

8.推导式

  • 列表推导式
[ expr for value in collection [if condition] ]
x = [-4, -2, 0, 2, 4]
y = [a * 2 for a in x]
print(y)
# [-8, -4, 0, 4, 8]
x = [i ** 2 for i in range(1, 10)]
print(x)
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
x = [(i, i ** 2) for i in range(6)]
print(x)

# [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x)

# [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]
  • 元祖推导式
( expr for value in collection [if condition] )
  • 字典推导式
{ key_expr: value_expr for value in collection [if condition] }
  • 集合推导式
{ expr for value in collection [if condition] }

练习题1:

编写一个Python程序来查找那些既可以被7整除又可以被5整除的数字,介于1500和2700之间。

for i in range(1,100):
    if i%5==0 and i%7==0:
        print(i+"能被5和7整除")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值