有幸参加了阿里云举办的天池龙珠计划Python训练营。收获颇多。
每天记录一些自己之前的知识盲点,需经常温习。
一、assert 关键词
- `assert`这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出`AssertionError`的异常。
【例子】
【例子】
my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0
# AssertionError
【例子】在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。
assert 3 > 7
# AssertionError
二、for循环
get到了print()语句的深层用法。
【例子】
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key, value in dic.items():
print(key, value, sep=':', end=' ')
# a:1 b:2 c:3 d:4
【例子】
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key in dic.keys():
print(key, end=' ')
# a b c d
【例子】
dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
for value in dic.values():
print(value, end=' ')
# 1 2 3 4
三、next()的用法
- `next(iterator[, default])` Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration.
【例子】
e = (i for i in range(10))
print(e)
# <generator object <genexpr> at 0x0000007A0B8D01B0>
print(next(e)) # 0
print(next(e)) # 1
for each in e:
print(each, end=' ')
# 2 3 4 5 6 7 8 9
【例子】
s = sum([i for i in range(101)])
print(s) # 5050
s = sum((i for i in range(101)))
print(s) # 5050