赋值
常规赋值 =
序列解包
序列解包(或可迭代对象解包):将一个序列(或任何可迭代对象)解包,并将得到的值存储到一系列变量中
用途
- 同时给多个变量赋值
- 交换多个变量的值
a, b, c = 'x', 'y', 'z' ### a的值即为'x'
t = (1, 2, 3)
c, d, e = t ### c的值即为 1
链式赋值
链式赋值是一种快捷方式,用于将多个变量关联到同一个值
x = y = somefunction()
#上述代码与下面的代码等价:
y = somefunction()
x=y
这两条语句可能与下面的语句不等价:
(之所以说“可能”不等价,与 python 自身数据存储的设计有关系而分别指向不同的对象)
x = somefunction()
y = somefunction()
增强赋值
如 x = x + 1, 可以写成 x += 1.
>>> x = 2
>>> x += 1
>>> x *= 2
>>> x ### 输出为 6
比较运算符、数据类型检查与同一性检查
python 的数据类型通常根据变量的值进行确定。 在交互器中我们也可以用内置的
type(obj)
获取类型;程序中则可以使用isinstance()
检查是否为某类的实例(但同时也破坏了其封装性) 另外在赋值后,如果需要检查两个对象是否相等,可以用双等号==
/!=
;如果需要检查两个变量是否为用一个对象,可以用is
/is not
>>> a = []
>>> type(a) ### 输出为 <class 'list'>
>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a == b ### 输出为 True
>>> a is b ### 输出为 False
>>> a = 257
>>> b = 257
>>> a is b ### 输出为 False
>>> a == b ### 输出为 True
>>> a = 256; b = 256
>>> a is b ### 输出为 True
>>> a is not b ### 输出为 True
>>> a = 10; b = 5; a > b
def zero(num):
if isinstance(num, int):
if num == 0:
raise EOFError("内容为空")
else:
print(num)
return False
else:
raise ValueError("非数值类型")
条件
布尔值
标准值False和None、各种类型(包括浮点数、复数等)的数值0、空序列(如空 字符串、空元组和空列表)以及空映射(如空字典)都被视为假(False),而其他各种值都被视为真(True)
布尔运算的短路逻辑
假设表达式x and y才为真。因此如果x为假,这个表达式将立即返回假,而不关心y. 同理如 x or y
if 语句与 else 子句、elif 子句
# 示例 1
def test(a: list): ### 引用了3.6的特性,是期望接收list,但非法输入不会引起报错
if a: ### 这个写法是PEP8风格,表示条件a为真。等价于 if a is True:
print('get one list')
else:
print('oops!')
print('cool') ### 不论条件判定是什么,都会执行。Python的代码块创建是根据缩进来的
test([1, 2])
test([])
# 示例 2
def judgement():
try:
age = int(input("what's your age: "))
if 100 > age >= 18:
print('已成年')
elif 0 < age < 18:
print('未成年')
else:
raise ValueError('输入不合法')
except TypeError:
raise ValueError('输入数字')
断言 assert
>>> age = 10
>>> assert 0 < age < 100
>>> age = -1
>>> assert 0 < age < 100, "age在0-100间"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: age在0-100间
循环
while与for
while 可用在如轮询的实现中 不同于其他语言如 Java 的 for 循环,Python中属于 foreach 的设计,语法上通常是 for … in…
def while_case():
lst = [None]
print('The initial length is: ' + str(len(lst)))
while 1 <= len(lst) < 10:
lst.append(len(lst) + 1)
print('Now the length is: ' + str(len(lst)))
def while_case_2(statement):
while statement is not None:
print('content is %s' % statement)
return statement
def foreach_1():
word = 'string'
for i in word:
print(i)
def foreach_2():
for i in range(10):
print(i)
def foreach_3():
word = 'string'
for i in range(len(word)):
print(word[i])
def foreach_4():
mapping = {'k1': 'v1', 'k2': 'v2'}
for k, v in mapping.items():
print(k, v)
跳出循环 break, continue, return
break
无需再迭代,直接跳出最近的循环continue
结束当前迭代,并跳转到下次的迭代开头。意味着跳过循环体中余下的语句,但不结束循环return
结束函数。意味着 return 之后的语句都不再执行
示例
轮询实现示例
#!/usr/local/bin/py3
# -*- coding:utf-8 -*-
"""
@Interpreter: Python3.9
@File: polling
@Description:
@Author: hailong.chen
@Date: 2022/1/18 14:24
@ModifiedBy:
"""
from datetime import datetime, timedelta
def polling(timeout=3):
"""timeout 时间内执行动作"""
start = datetime.now()
end = start + timedelta(seconds=+timeout)
while 1:
print("执行动作.....")
current = datetime.now()
print(current)
if current >= end:
print("动作执行...{timeout}s 超时结束".format(timeout=timeout))
break
print('结束轮询')
return
def polling_optimizely(timeout=3):
"""timeout (秒)时间内,每间隔0.5s执行一次动作"""
start = datetime.now()
current = datetime.now()
_interval = 0.5
end = start + timedelta(seconds=+timeout)
while 1:
print("%s 时间,执行动作....." % current)
if current < end:
current += timedelta(seconds=_interval)
else:
print("动作执行...{timeout}s 超时结束".format(timeout=timeout))
break
print('结束轮询')
return
polling()
polling_optimizely()
获取两个列表的交集示例
a = [1,2,3]
b = [2,3,5]
for i in a:
if i in b:
print(i)
# 输出结果: 2,3
排序算法示例
冒泡排序示例
通常对于排序,可以直接用 sort(), sorted(), reverse() 等
def do_sort():
# 冒泡排序要排序n个数,由于每遍历一趟只排好一个数字,
# 则需要遍历n-1趟,所以最外层循环是要循环n-1次,而
# 每趟遍历中需要比较每归位的数字,则要在n-1次比较中
# 减去已排好的第i位数字,即每趟循环要遍历是n-1-i次
lst = [1, 4, 3, 5, 2]
for i in range(len(lst)-1):
for j in range(len(lst)-1-i):
if lst[j] < lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j] # 这里使用的是序列解包进行值互换
print(lst)
do_sort()