1 基础补漏

1 三元运算符

x, y = 4, 5

if x < y:
small = x
else:
small = y
相当于
small = x if x < y else y

详细解释:
使用 if else 实现三目运算符(条件运算符)的格式如下:
exp1 if contion else exp2
condition 是判断条件,exp1 和 exp2 是两个表达式。如果 condition 成立(结果为真),就执行 exp1,并把 exp1 的结果作为整个表达式的结果;如果 condition 不成立(结果为假),就执行 exp2,并把 exp2 的结果作为整个表达式的结果。

三目运算符的嵌套
Python 三目运算符支持嵌套,如此可以构成更加复杂的表达式。在嵌套时需要注意 if 和 else 的配对,例如:
a if a>b else c if c>d else d

应该理解为:
a if a>b else ( c if c>d else d )

2 is 和 is not (可变类型和不可变类型)
【例子】比较的两个变量均指向不可变类型。

a = “hello”
b = “hello”
print(a is b, a == b) # True True
print(a is not b, a != b) # False False
True True
False False
【例子】比较的两个变量均指向可变类型。

a = [“hello”]
b = [“hello”]
print(a is b, a == b) # False True
print(a is not b, a != b) # True False
False True
True False

3 数值类型传唤

转换为整型 int(x, base=10)
转换为字符串 str(object=’’)
转换为浮点型 float(x)
【例子】

print(int(‘520’)) # 520
print(int(520.52)) # 520
print(float(‘520.52’)) # 520.52
print(float(520)) # 520.0
print(str(10 + 10)) # 20
print(str(10.1 + 5.2)) # 15.3
520
520
520.52
520.0
20
15.3

4 if - elif - else 语句
if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
.
.
elif expressionN:
exprN_true_suite
else:
expr_false_suite
elif 语句即为 else if,用来检查多个表达式是否为真,并在为真时执行特定代码块中的代码。

5 断言
assert 关键词
assert这个关键词我们称之为“断言”,当这个关键词后边的条件为 False 时,程序自动崩溃并抛出AssertionError的异常。
【例子】

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

【例子】在进行单元测试时,可以用来在程序中置入检查点,只有条件为 True 才能让程序正常工作。

assert 3 > 7

6 while - else 循环
while 布尔表达式:
代码块
else:
代码块
当while循环正常执行完的情况下,执行else输出,如果while循环中执行了跳出循环的语句,比如 break,将不执行else代码块的内容。

【例子】

count = 0
while count < 5:
print("%d is less than 5" % count)
count = count + 1
else:
print("%d is not less than 5" % count)

0 is less than 5

1 is less than 5

2 is less than 5

3 is less than 5

4 is less than 5

5 is not less than 5

0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5

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

for i in range(2, 9): # 不包含9
print(i)

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]

[-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 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]

a = [(i, j) for i in range(0, 3) if i < 1 for j in range(0, 3) if j > 1]
print(a)

[(0, 2)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值