Python基础语法.ipynb

注:下载附件ipynb文件到之前创建的da_learn文件,并在da_learn运行jupyter-lab.exe,点击打开即可进行交互式学习和练习哦!

mementopython3-english.pdf

1. 注释

注释就是告诉计算机,这行文字只是普通说明文字,不用执行

  1. # 开头的是单行注释
  2. """
  3. 多行字符串用三个引号
  4. 包裹,也常被用来做多
  5. 行注释
  6. """
  7. pass # 这行是空语句,一般用来占用一行备用或啥也不是
  8. a = 1 # 变量定义并赋值
  9. name="QQ" # 变量定义并赋值
  10. print("hello world!") # 打印函数,用于将传入的参数打印出来,以便观察
  11. print("hello %s!" % name) # 打印函数的参数格式化,以便动态修改打印的文字
  1. hello world!
  2. hello QQ!

2.基础数据类型和运算符

  1. """
  2. 1. 数值运算:
  3. + 加
  4. - 减
  5. * 乘
  6. / 除
  7. // 取整除
  8. % 模运算
  9. ** 乘方
  10. 2. 逻辑运算
  11. and 与
  12. or 或
  13. not 非
  14. > 大于
  15. >= 大于或等于
  16. < 小于
  17. <= 小于或等于
  18. 3. 字符串格式化
  19. + 拼接
  20. [num] 索引
  21. % 格式化
  22. %s 字符串 (采用str()的显示)
  23. %r 字符串 (采用repr()的显示)
  24. %c 单个字符
  25. %b 二进制整数
  26. %d 十进制整数
  27. %i 十进制整数
  28. %o 八进制整数
  29. %x 十六进制整数
  30. %e 指数 (基底写为e)
  31. %E 指数 (基底写为E)
  32. %f 浮点数
  33. %F 浮点数,与上相同
  34. %g 指数(e)或浮点数 (根据显示长度)
  35. %G 指数(E)或浮点数 (根据显示长度)
  36. %% 字符"%"
  37. format格式化
  38. "{} is a {}!".format("God", "girl")
  39. """
  40. pass
  1. # 整数运算
  2. a = 5 + 3 # 加
  3. print("5 + 3 = %d" % a)
  4. b = 5 - 3 # 减
  5. print("5 - 3 = %d" % b)
  6. c = 5 * 3 # 乘
  7. print("5 * 3 = %d" % c)
  8. d = 5 / 3 # 除
  9. print("5 / 3 = %d" % d)
  10. e = 5 // 3 # 除
  11. print("5 // 3 = %d" % e)
  12. f = 5 % 3 # 模运算
  13. print("5 %% 3 = %d" % f)
  14. g = 5 ** 3 # 乘方运算
  15. print("5 %% 3 = %d" % g)
  16. h = 5 * (2 + 1) - 1 # 优先级运算
  17. print("5 * (2 + 1) - 1 = %d" % h)
  1. 5 + 3 = 8
  2. 5 - 3 = 2
  3. 5 * 3 = 15
  4. 5 / 3 = 1
  5. 5 // 3 = 1
  6. 5 % 3 = 2
  7. 5 % 3 = 125
  8. 5 * (2 + 1) - 1 = 14
  1. # 浮点运算
  2. a = 5.0 + 3 # 加
  3. print("5.0 + 3 = %.2f" % a)
  4. b = 5.0 - 3 # 减
  5. print("5.0 - 3 = %.2f" % b)
  6. c = 5.0 * 3 # 乘
  7. print("5.0 * 3 = %.2f" % c)
  8. d = 5.0 / 3 # 除
  9. print("5.0 / 3 = %.2f" % d)
  10. e = 5.0 // 3 # 除
  11. print("5.0 // 3 = %.2f" % e)
  12. f = 5.0 % 3 # 模运算
  13. print("5.0 %% 3 = %.2f" % f)
  14. g = 5.0 ** 3 # 乘方运算
  15. print("5.0 %% 3 = %.2f" % g)
  16. h = 5.0 * (2 + 1) - 1 # 优先级运算
  17. print("5.0 * (2 + 1) - 1 = %.2f" % h)
  1. 5.0 + 3 = 8.00
  2. 5.0 - 3 = 2.00
  3. 5.0 * 3 = 15.00
  4. 5.0 / 3 = 1.67
  5. 5.0 // 3 = 1.00
  6. 5.0 % 3 = 2.00
  7. 5.0 % 3 = 125.00
  8. 5.0 * (2 + 1) - 1 = 14.00
  1. # 布尔值 与 逻辑运算
  2. # True False
  3. print("True: %s" % True)
  4. print("False: %s" % False)
  5. a = True and True
  6. print("True and True: %s" % a)
  7. b = True and False
  8. print("True and False: %s" % b)
  9. c = False and True
  10. print("False and True: %s" % c)
  11. d = False and False
  12. print("False and False: %s" % d)
  13. not_true = not True
  14. print("not True: %s" % not_true)
  15. not_false = not False
  16. print("not False: %s" % not_false)
  17. e = 1 == 1
  18. print("1 == 1: %s" % e)
  19. f = 1 != 1
  20. print("1 != 1: %s" % f)
  21. g = 1 == True
  22. print("1 == True: %s" % g)
  23. h = 1 != True
  24. print("1 != True: %s" % h)
  25. i = 0 == False
  26. print("0 == False: %s" % i)
  27. j = 0 != False
  28. print("0 != False: %s" % j)
  29. k = 5 > 3
  30. print("5 > 3: %s" % k)
  31. l = 5 >= 3
  32. print("5 >= 3: %s" % l)
  33. m = 3 < 5
  34. print("3 < 5: %s" % m)
  35. n = 3 <= 5
  36. print("3 <= 5: %s" % n)
  1. True: True
  2. False: False
  3. True and True: True
  4. True and False: False
  5. False and True: False
  6. False and False: False
  7. not True: False
  8. not False: True
  9. 1 == 1: True
  10. 1 != 1: False
  11. 1 == True: True
  12. 1 != True: False
  13. 0 == False: True
  14. 0 != False: False
  15. 5 > 3: True
  16. 5 >= 3: True
  17. 3 < 5: True
  18. 3 <= 5: True
  1. # 字符串运算
  2. a = "hello"
  3. b = " "
  4. c = "world"
  5. d = "!"
  6. s1 = a + b + c + d
  7. print("s1 = %s" % s1)
  8. e = s[0]
  9. f = s[4]
  10. g = s[-1]
  11. print("e = %s\nf = %s\ng = %s" % (e, f, g))
  12. s2 = "%s%s%s%s" % (a, b, c, d)
  13. print("s2 = %s" % s2)
  14. s3 = "{}{}{}{}".format(a, b, c, d)
  15. print("s3 = %s" % s3)
  16. s4 = "{0} {0}{1}{2}{3}".format(a, b, c, d)
  17. print("s4 = %s" % s4)
  1. s1 = hello world!
  2. e = h
  3. f = o
  4. g = !
  5. s2 = hello world!
  6. s3 = hello world!
  7. s4 = hello hello world!

3. 集合运算

  1. # 列表 可改变的序列
  2. # 定义一个空列表
  3. ls = []
  4. print("空列表ls:", ls)
  5. # 定义一个非空列表
  6. ls = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  7. print("非空列表ls:", ls)
  8. print("列表长度 ls:", len(ls))
  9. # 列表追加元素
  10. ls.append(10)
  11. print("列表追加元素后 ls:", ls)
  12. # 从列表末尾删除元素
  13. ls.pop()
  14. print("从列表末尾删除元素后 ls:", ls)
  15. # 按照索引获取列表元素
  16. print("ls 第1个元素:", ls[0])
  17. print("ls 第2个元素:", ls[1])
  18. print("ls 最后1个元素:", ls[-1])
  19. # 越界访问列表元素
  20. # ls[4]
  21. # 切片
  22. a = ls[0:5]
  23. print("ls 切片[0:5]:", a)
  24. b = ls[:5]
  25. print("ls 切片[:5]:", b)
  26. c = ls[5:9]
  27. print("ls 切片[5:9]:", c)
  28. c = ls[5:]
  29. print("ls 切片[5:]:", c)
  30. d = ls[5:-1]
  31. print("ls 切片[5:-1]:", d)
  32. e = ls[0:5:1]
  33. print("ls 切片[0:5:1]:", e)
  34. f = ls[0:5:2]
  35. print("ls 切片[0:5:2]:", f)
  36. del ls[5]
  37. print("ls 删除第6个元素:", ls)
  38. ls1 = [1, 2]
  39. ls2 = [3, 4]
  40. ls3 = ls1 + ls2
  41. print("列表拼接 ls3:", ls3)
  42. ls1.extend(ls2)
  43. print("列表扩展 ls1:", ls1)
  44. is_in_list = 4 in ls3
  45. print("判断元素是否在列表中 4 in ls3:", is_in_list)
  46. #
  1. 空列表ls: []
  2. 非空列表ls: [1, 2, 3, 4, 5, 6, 7, 8, 9]
  3. 列表长度 ls: 9
  4. 列表追加元素后 ls: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  5. 从列表末尾删除元素后 ls: [1, 2, 3, 4, 5, 6, 7, 8, 9]
  6. ls 1个元素: 1
  7. ls 2个元素: 2
  8. ls 最后1个元素: 9
  9. ls 切片[0:5]: [2, 3, 4, 5]
  10. ls 切片[:5]: [1, 2, 3, 4, 5]
  11. ls 切片[5:9]: [6, 7, 8, 9]
  12. ls 切片[5:]: [6, 7, 8, 9]
  13. ls 切片[5:-1]: [6, 7, 8]
  14. ls 切片[0:5:1]: [1, 2, 3, 4, 5]
  15. ls 切片[0:5:2]: [1, 3, 5]
  16. ls 删除第6个元素: [1, 2, 3, 4, 5, 7, 8, 9]
  17. 列表拼接 ls3: [1, 2, 3, 4]
  18. 列表扩展 ls1: [1, 2, 3, 4]
  19. 判断元素是否在列表中 4 in ls3: True
  1. # 元组 不可改变的序列
  2. tup = (1, 2, 3, 4, 5, 6, 7, 8, 9)
  3. # 元组一旦生成则内部元素不可改变
  4. # tup[0] = 0
  5. print("tup 长度:", len(tup))
  6. print("tup 第1个元素:", tup[0])
  7. print("tup 最后1个元素:", tup[-1])
  8. a = tup[0:5]
  9. print("tup 切片[0:5]:", a)
  10. tup1 = (1, 2)
  11. tup2 = (3, 4)
  12. tup3 = tup1 + tup2
  13. print("切片拼接 tup3:", tup3)
  14. is_in_tup = 4 in tup3
  15. print("判断元素是否在元组中 4 in tup3:", is_in_tup)
  16. a, b, c, d = tup3
  17. print("解构元素 a: %d, b: %d, c: %d, d:%d" % ( a, b, c, d))
  1. tup 长度: 9
  2. tup 1个元素: 1
  3. tup 最后1个元素: 9
  4. tup 切片[0:5]: (1, 2, 3, 4, 5)
  5. 切片拼接 tup3: (1, 2, 3, 4)
  6. 判断元素是否在元组中 4 in tup3: True
  7. 解构元素 a: 1, b: 2, c: 3, d:4
  1. # 字典 键值对数据结构
  2. empty_dict = {}
  3. print("空字典:", empty_dict)
  4. filled_dict = {"one": 1, "two": 2, "three": 3}
  5. print("非空字典:", filled_dict)
  6. a = filled_dict["one"]
  7. print('字典取值 filled_dict["one"]:', a)
  8. b = filled_dict.get("one")
  9. print('字典取值 filled_dict.get("one"):', b)
  10. # flled_dict["nine"] # 获取不存在的键值会报错
  11. c = filled_dict.get("nine")
  12. print('字典取值 filled_dict.get("nine"):', c)
  13. d = filled_dict.get("nine", 9)
  14. print('字典取值 filled_dict.get("nine", 9):', d)
  15. filled_dict["four"] = 4
  16. print('字典插入新的键值对 filled_dict["four"]:', filled_dict)
  17. filled_dict.setdefault("five", 5)
  18. print('字典插入新的键值对 filled_dict.setdefault("five", 5):', filled_dict)
  19. filled_dict.setdefault("five", 0)
  20. print('字典插入新的键值对 filled_dict.setdefault("five", 0):', filled_dict)
  21. del filled_dict["four"]
  22. del filled_dict["five"]
  23. print('字典删除键值对 filled_dict:', filled_dict)
  24. m = {"four": 4, "five": 5}
  25. filled_dict.update(m)
  26. print('字典更新 filled_dict:', filled_dict)
  27. is_in_dict = "nine" in filled_dict
  28. print('判断是否在字典中:', is_in_dict)
  29. keys = filled_dict.keys()
  30. print('字典中的所有键(key):', keys)
  31. values = filled_dict.values()
  32. print('字典中的所有值(value):', values)
  1. 空字典: {}
  2. 非空字典: {'one': 1, 'two': 2, 'three': 3}
  3. 字典取值 filled_dict["one"]: 1
  4. 字典取值 filled_dict.get("one"): 1
  5. 字典取值 filled_dict.get("nine"): None
  6. 字典取值 filled_dict.get("nine", 9): 9
  7. 字典插入新的键值对 filled_dict["four"]: {'one': 1, 'two': 2, 'three': 3, 'four': 4}
  8. 字典插入新的键值对 filled_dict.setdefault("five", 5): {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
  9. 字典插入新的键值对 filled_dict.setdefault("five", 0): {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
  10. 字典删除键值对 filled_dict: {'one': 1, 'two': 2, 'three': 3}
  11. 字典更新 filled_dict: {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
  12. 判断是否在字典中: False
  13. 字典中的所有键(key): dict_keys(['one', 'two', 'three', 'four', 'five'])
  14. 字典中的所有值(value): dict_values([1, 2, 3, 4, 5])
  1. # 集合
  2. empty_set = set()
  3. print("空集合:", empty_set)
  4. filled_set = {1, 2, 3, 4, 5, 4, 3, 2, 1}
  5. print("非空集合:", filled_set)
  6. filled_set.add(6)
  7. print("集合添加元素:", filled_set)
  8. filled_set.remove(6)
  9. print("集合删除元素:", filled_set)
  10. other_set = {3, 4, 5, 6, 7}
  11. a = filled_set & other_set
  12. print("集合 交集:", a)
  13. b = filled_set | other_set
  14. print("集合 并集:", b)
  15. c = filled_set - other_set
  16. print("集合 差集:", c)
  1. 空集合: set()
  2. 非空集合: {1, 2, 3, 4, 5}
  3. 集合添加元素: {1, 2, 3, 4, 5, 6}
  4. 集合删除元素: {1, 2, 3, 4, 5}
  5. 集合 交集: {3, 4, 5}
  6. 集合 并集: {1, 2, 3, 4, 5, 6, 7}
  7. 集合 差集: {1, 2}

4.流程控制

  1. # 分支判断
  2. # 单分支判断
  3. name = "QQ"
  4. if name != "":
  5. print("hello %s!" % name)
  6. # 双分支判断
  7. is_true = True
  8. if is_true:
  9. print("good!")
  10. else:
  11. print("bad!")
  12. # 多分支判断
  13. score = 66
  14. if score >= 80:
  15. print("优秀")
  16. elif score >= 60:
  17. print("及格")
  18. else:
  19. print("不及格")
  1. hello QQ!
  2. good!
  3. 及格
  1. # 循环
  2. # for循环
  3. sum = 0
  4. for i in range(1, 11):
  5. print("for count: %d" % i)
  6. sum += i
  7. print("1-10的数字之和: %d" % sum)
  8. # while循环
  9. sum = 0
  10. i = 10
  11. while i > 0:
  12. sum += i
  13. print("while count: %d" % i)
  14. i -= 1
  15. print("10-1的数字之和: %d" % sum)
  1. for count: 1
  2. for count: 2
  3. for count: 3
  4. for count: 4
  5. for count: 5
  6. for count: 6
  7. for count: 7
  8. for count: 8
  9. for count: 9
  10. for count: 10
  11. 1-10的数字之和: 55
  12. while count: 10
  13. while count: 9
  14. while count: 8
  15. while count: 7
  16. while count: 6
  17. while count: 5
  18. while count: 4
  19. while count: 3
  20. while count: 2
  21. while count: 1
  22. 10-1的数字之和: 55

5. 函数

  1. # 将常用的代码块整理为函数,可以让代码更加整洁,可重复利用
  2. # 加法函数
  3. def sum(a, b):
  4. return a + b
  5. sum_int = sum(1, 3)
  6. print("sum_int:", sum_int)
  7. sum_str = sum("hello ", "world!")
  8. print("sum_str:", sum_str)
  9. sum_list = sum([1,2], [3, 4])
  10. print("sum_list:", sum_list)
  11. # 任意连续整数之和
  12. def sum_start_to_end(start, end):
  13. if not isinstance(start, int) or not isinstance(end, int):
  14. print("错误的起止参数类型: start: %s, end: %s" % (type(start), type(end)))
  15. return None
  16. if start > end:
  17. print("错误的起止参数: start: %s, end: %s" % (start, end))
  18. return None
  19. sum = 0
  20. for i in range(start, end+1):
  21. sum += i
  22. return sum
  23. start = 1
  24. end = 100
  25. c = sum_start_to_end(start, end)
  26. print("sum %d to %d sum: %d:" % (start, end, c))
  1. sum_int: 4
  2. sum_str: hello world!
  3. sum_list: [1, 2, 3, 4]
  4. sum 1 to 100 sum: 5050:

6. 类

  1. # 类是代码对现实世界的抽象和模拟,同时可以对代码进行封装和管理
  2. class Animal(object):
  3. name = None
  4. def __init__(self, name):
  5. self.name = name
  6. def breathe(self):
  7. print("%s breathe" % self.name)
  8. @staticmethod
  9. def grunt():
  10. print("*grunt*")
  11. class Human(Animal):
  12. def __init__(self, name):
  13. super(Human, self).__init__(name)
  14. #self.name = name
  15. def say(self, msg):
  16. print("{name} say: {message}".format(name=self.name, message=msg))
  17. a = Human("Jack")
  18. a.grunt()
  19. a.breathe()
  20. a.say("hello")
  1. *grunt*
  2. Jack breathe
  3. Jack say: hello

7.模块

  1. # 模块是文件级别的代码组织和管理方式,可以把常用的代码封装成一个模块便于代码复用,通常一个模块可以包含很多函数或者类
  2. # 官方提供的数学计算模块
  3. import math # 直接引入模块使用
  4. a = 16
  5. b = math.sqrt(a)
  6. print("%s 的开方结果:%s" % (a, b))
  7. from math import ceil, floor # 引入模块中的部分函数使用
  8. c = 3.7
  9. d = ceil(c)
  10. e = floor(c)
  11. print("%s 向上取证的结果: %s" % (c, d))
  12. print("%s 向下取证的结果: %s" % (c, e))
  13. import math as m # 引入模块并重命名使用
  14. print("math 模块的常量圆周率: %s" % m.pi)
  15. # 自定义模块
  16. # 示例1 单文件模块
  17. """
  18. #tree
  19. .
  20. ├── main.py
  21. ├── service.py
  22. # cat service.py
  23. #!/usr/bin/python
  24. # -*- coding: UTF-8 -*-
  25. def coffee_service():
  26. print("you call coffee service!")
  27. # cat main.py
  28. #!/usr/bin/python
  29. # -*- coding: UTF-8 -*-
  30. import service
  31. if __name__ == "__main__":
  32. service.coffee_service()
  33. """
  34. pass
  35. # 多文件模块示例
  36. """
  37. #tree
  38. .
  39. ├── main.py
  40. └── robot
  41. ├── __init__.py
  42. ├── robot1.py
  43. └── robot2.py
  44. #cat robot/robot1.py
  45. #!/usr/bin/python
  46. # -*- coding: UTF-8 -*-
  47. def robot1_action():
  48. print("I'm in robot1!")
  49. #cat robot/robot2.py
  50. #!/usr/bin/python
  51. # -*- coding: UTF-8 -*-
  52. def robot2_action():
  53. print("I'm in robot2!")
  54. #cat robot/__init__.py
  55. #!/usr/bin/python
  56. # -*- coding: UTF-8 -*-
  57. if __name__ == '__main__':
  58. print '作为主程序运行'
  59. else:
  60. print 'robot模块初始化'
  61. #cat main.py
  62. #!/usr/bin/python
  63. # -*- coding: UTF-8 -*-
  64. # 导入robot包
  65. from robot.robot1 import robot1_action
  66. from robot.robot2 import robot2_action
  67. robot1_action()
  68. robot2_action()
  69. """
  70. pass
  1. 16 的开方结果:4.0
  2. 3.7 向上取证的结果: 4
  3. 3.7 向下取证的结果: 3
  4. math 模块的常量圆周率: 3.141592653589793