赋值

常规赋值 =

如 a = ‘yeah’

序列解包

序列解包(或可迭代对象解包):将一个序列(或任何可迭代对象)解包,并将得到的值存储到一系列变量中

用途

  1. 同时给多个变量赋值
  2. 交换多个变量的值
    1. a, b, c = 'x', 'y', 'z' ### a的值即为'x'
    2. t = (1, 2, 3)
    3. c, d, e = t ### c的值即为 1

    链式赋值

    链式赋值是一种快捷方式,用于将多个变量关联到同一个值

  1. x = y = somefunction()
  2. #上述代码与下面的代码等价:
  3. y = somefunction()
  4. x=y
  5. 这两条语句可能与下面的语句不等价:
  6. (之所以说“可能”不等价,与 python 自身数据存储的设计有关系而分别指向不同的对象)
  7. x = somefunction()
  8. y = somefunction()

增强赋值

如 x = x + 1, 可以写成 x += 1.

  1. >>> x = 2
  2. >>> x += 1
  3. >>> x *= 2
  4. >>> x ### 输出为 6

比较运算符、数据类型检查与同一性检查

python 的数据类型通常根据变量的值进行确定。 在交互器中我们也可以用内置的 type(obj)获取类型;程序中则可以使用isinstance()检查是否为某类的实例(但同时也破坏了其封装性) 另外在赋值后,如果需要检查两个对象是否相等,可以用双等号==/ !=;如果需要检查两个变量是否为用一个对象,可以用is/ is not

  1. >>> a = []
  2. >>> type(a) ### 输出为 <class 'list'>
  3. >>> a = [1,2,3]
  4. >>> b = [1,2,3]
  5. >>> a == b ### 输出为 True
  6. >>> a is b ### 输出为 False
  7. >>> a = 257
  8. >>> b = 257
  9. >>> a is b ### 输出为 False
  10. >>> a == b ### 输出为 True
  11. >>> a = 256; b = 256
  12. >>> a is b ### 输出为 True
  13. >>> a is not b ### 输出为 True
  14. >>> a = 10; b = 5; a > b
  15. def zero(num):
  16. if isinstance(num, int):
  17. if num == 0:
  18. raise EOFError("内容为空")
  19. else:
  20. print(num)
  21. return False
  22. else:
  23. raise ValueError("非数值类型")

条件

布尔值

标准值False和None、各种类型(包括浮点数、复数等)的数值0、空序列(如空 字符串、空元组和空列表)以及空映射(如空字典)都被视为假(False),而其他各种值都被视为真(True)

布尔运算的短路逻辑

假设表达式x and y才为真。因此如果x为假,这个表达式将立即返回假,而不关心y. 同理如 x or y

if 语句与 else 子句、elif 子句

  1. # 示例 1
  2. def test(a: list): ### 引用了3.6的特性,是期望接收list,但非法输入不会引起报错
  3. if a: ### 这个写法是PEP8风格,表示条件a为真。等价于 if a is True:
  4. print('get one list')
  5. else:
  6. print('oops!')
  7. print('cool') ### 不论条件判定是什么,都会执行。Python的代码块创建是根据缩进来的
  8. test([1, 2])
  9. test([])
  10. # 示例 2
  11. def judgement():
  12. try:
  13. age = int(input("what's your age: "))
  14. if 100 > age >= 18:
  15. print('已成年')
  16. elif 0 < age < 18:
  17. print('未成年')
  18. else:
  19. raise ValueError('输入不合法')
  20. except TypeError:
  21. raise ValueError('输入数字')

image.png

断言 assert

  1. >>> age = 10
  2. >>> assert 0 < age < 100
  3. >>> age = -1
  4. >>> assert 0 < age < 100, "age在0-100间"
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in <module>
  7. AssertionError: age0-100

循环

while与for

while 可用在如轮询的实现中 不同于其他语言如 Java 的 for 循环,Python中属于 foreach 的设计,语法上通常是 for … in…

  1. def while_case():
  2. lst = [None]
  3. print('The initial length is: ' + str(len(lst)))
  4. while 1 <= len(lst) < 10:
  5. lst.append(len(lst) + 1)
  6. print('Now the length is: ' + str(len(lst)))
  7. def while_case_2(statement):
  8. while statement is not None:
  9. print('content is %s' % statement)
  10. return statement
  11. def foreach_1():
  12. word = 'string'
  13. for i in word:
  14. print(i)
  15. def foreach_2():
  16. for i in range(10):
  17. print(i)
  18. def foreach_3():
  19. word = 'string'
  20. for i in range(len(word)):
  21. print(word[i])
  22. def foreach_4():
  23. mapping = {'k1': 'v1', 'k2': 'v2'}
  24. for k, v in mapping.items():
  25. print(k, v)

跳出循环 break, continue, return

break无需再迭代,直接跳出最近的循环
continue结束当前迭代,并跳转到下次的迭代开头。意味着跳过循环体中余下的语句,但不结束循环
return结束函数。意味着 return 之后的语句都不再执行

示例

轮询实现示例

  1. #!/usr/local/bin/py3
  2. # -*- coding:utf-8 -*-
  3. """
  4. @Interpreter: Python3.9
  5. @File: polling
  6. @Description:
  7. @Author: hailong.chen
  8. @Date: 2022/1/18 14:24
  9. @ModifiedBy:
  10. """
  11. from datetime import datetime, timedelta
  12. def polling(timeout=3):
  13. """timeout 时间内执行动作"""
  14. start = datetime.now()
  15. end = start + timedelta(seconds=+timeout)
  16. while 1:
  17. print("执行动作.....")
  18. current = datetime.now()
  19. print(current)
  20. if current >= end:
  21. print("动作执行...{timeout}s 超时结束".format(timeout=timeout))
  22. break
  23. print('结束轮询')
  24. return
  25. def polling_optimizely(timeout=3):
  26. """timeout (秒)时间内,每间隔0.5s执行一次动作"""
  27. start = datetime.now()
  28. current = datetime.now()
  29. _interval = 0.5
  30. end = start + timedelta(seconds=+timeout)
  31. while 1:
  32. print("%s 时间,执行动作....." % current)
  33. if current < end:
  34. current += timedelta(seconds=_interval)
  35. else:
  36. print("动作执行...{timeout}s 超时结束".format(timeout=timeout))
  37. break
  38. print('结束轮询')
  39. return
  40. polling()
  41. polling_optimizely()

获取两个列表的交集示例

  1. a = [1,2,3]
  2. b = [2,3,5]
  3. for i in a:
  4. if i in b:
  5. print(i)
  6. # 输出结果: 2,3

image.png

排序算法示例

冒泡排序示例

通常对于排序,可以直接用 sort(), sorted(), reverse() 等

  1. def do_sort():
  2. # 冒泡排序要排序n个数,由于每遍历一趟只排好一个数字,
  3. # 则需要遍历n-1趟,所以最外层循环是要循环n-1次,而
  4. # 每趟遍历中需要比较每归位的数字,则要在n-1次比较中
  5. # 减去已排好的第i位数字,即每趟循环要遍历是n-1-i次
  6. lst = [1, 4, 3, 5, 2]
  7. for i in range(len(lst)-1):
  8. for j in range(len(lst)-1-i):
  9. if lst[j] < lst[j+1]:
  10. lst[j], lst[j+1] = lst[j+1], lst[j] # 这里使用的是序列解包进行值互换
  11. print(lst)
  12. do_sort()