0.安装与准备

0-1 安装

1. Python

https://www.python.org Python 3.10.4

2. IDE

Vs code / Pycharm

0-2 准备

  • 中英文字符 ()- () …
  • 编码规则 utf-8

1.入门

1-1 基础语法

1. 标志符

1) 规则

  • 第一个字符必须是字母表中字母或下划线 _
  • 标识符的其他的部分由字母、数字和下划线组成。
  • 标识符对大小写敏感。

2) 保留字

1
2
3
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

2 注释

1
2
3
4
5
6
7
8
9
10
11
12
13
# 第一个注释
# 第二个注释

'''
第三注释
第四注释
'''

"""
第五注释
第六注释
"""
print ("Hello, Python!")

3. 行与缩进

  • 缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。

  • 多行语句

  • ```python

    Python 通常是一行写完一条语句,但如果语句很长,我们可以使用反斜杠 \ 来实现多行语句

    total = item_one + \

        item_two + \
        item_three
    

    在 [], {}, 或 () 中的多行语句,不需要使用反斜杠 \

    total = [‘item_one’, ‘item_two’, ‘item_three’,

        'item_four', 'item_five']
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72

    - Python 可以在同一行中使用多条语句,语句之间使用分号 **;** 分割



    ### 4. 类型

    #### 1) 数字(Number)类型

    - int(整数)
    - bool(布尔)
    - float(浮点数)
    - complex(复数)

    #### 2.) 字符串(String)类型

    - Python 中单引号 `'`和双引号 `"` 使用完全相同。
    - 使用三引号(`'''` 或 *`"""`)可以指定一个多行字符串。
    - 转义符 `\`。
    - 反斜杠可以用来转义,使用 `r`让反斜杠不发生转义。 如 `r"this is a line with \n"` 则 `\n` 会显示,并不是换行。
    - 按字面意义级联字符串,如 `"this " "is " "string"` 会被自动转换为`this is string`。
    - 字符串可以用 `+` 运算符连接在一起,用 `*` 运算符重复。
    - Python 中的字符串有两种索引方式,从左往右以 `0` 开始,从右往左以 `-1` 开始。
    - Python 中的字符串不能改变。
    - Python 没有单独的字符类型,一个字符就是长度为 `1` 的字符串。
    - 字符串的截取的语法格式如下:**变量[头下标:尾下标:步长]**

    ### 5. print 输出

    - **print** 默认输出是换行的,如果要实现不换行需要在变量末尾加上 `end=""`

    - ###### `print( "hello world!", end=" " )`

    ### 6. import

    - 在 python 用 import 或者 from...import 来导入相应的模块。
    - 将整个模块(somemodule)导入,格式为: `import somemodule`
    - 从某个模块中导入某个函数,格式为: `from somemodule import somefunction`
    - 从某个模块中导入多个函数,格式为: `from somemodule import firstfunc, secondfunc, thirdfunc`
    - 将某个模块中的全部函数导入,格式为: `from somemodule import \*`

    ## 1-2 基本数据类型

    ### 1. 标准数据类型

    Python3 的六个标准数据类型中:

    - **不可变数据(3 个):**Number(数字)、String(字符串)、Tuple(元组)
    - **可变数据(3 个):**List(列表)、Dictionary(字典)、Set(集合)

    ### 2. 赋值

    1) 等号(=) —> 赋值

    2) 连续赋值 `a = b = c = 1`

    ### 3. Number(数字)

    - int、float、bool、complex(复数)

    - 内置的 type() 函数可以用来查询变量所指的对象类型

    - ```python
    # type()
    >>> a, b, c, d = 20, 5.5, True, 4+3j
    >>> print(type(a), type(b), type(c), type(d))
    <class 'int'> <class 'float'> <class 'bool'> <class 'complex'>

    # isinstance
    >>> a = 111
    >>> isinstance(a, int)
    True
  • 可用 del 与聚集删除一些对象的引用

    • ```python
      del var
      del var_a, var_b
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10

      - 两种除法

      - **/** 返回一个浮点数,**//** 返回一个整数。

      - ```python
      >>> 2 / 4 # 除法,得到一个浮点数
      0.5
      >>> 2 // 4 # 除法,得到一个整数
      0

4. String(字符串)

  • 字符串截取

    • img
  • 注意

    • 1、反斜杠可以用来转义,使用r可以让反斜杠不发生转义。
    • 2、字符串可以用+运算符连接在一起,用*运算符重复。
    • 3、Python中的字符串有两种索引方式,从左往右以0开始,从右往左以-1开始。
    • 4、Python中的字符串不能改变。

5. List(列表)

  • 注意
    • 1、List写在方括号之间,元素用逗号隔开。
    • 2、和字符串一样,list可以被索引和切片。
    • 3、List可以使用+操作符进行拼接。
    • 4、List中的元素是可以改变的。
  • 如果第三个参数为负数表示逆向读取

6. Tuple(元组)

  • 元组(tuple)与列表类似,不同之处在于元组的元素不能修改。元组写在小括号 () 里,元素之间用逗号隔开

  • 构造包含 0 个或 1 个元素的元组比较特殊,所以有一些额外的语法规则

    • ```python
      tup1 = () # 空元组
      tup2 = (20,) # 一个元素,需要在元素后添加逗号
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41

      - 注意

      - 1、与字符串一样,元组的元素不能修改。
      - 2、元组也可以被索引和切片,方法一样。
      - 3、注意构造包含 0 或 1 个元素的元组的特殊语法规则。
      - 4、元组也可以使用+操作符进行拼接。

      ### 7. Set(集合)

      - 可以使用大括号 **{ }** 或者 **set()** 函数创建集合

      - 注意:创建一个空集合必须用 **set()** 而不是 **{ }**,因为 **{ }** 是用来创建一个空字典。

      - e.g.

      - ```python
      sites = {'Google', 'Taobao', 'Runoob', 'Facebook', 'Zhihu', 'Baidu'}

      print(sites) # 输出集合,重复的元素被自动去掉

      # 成员测试
      if 'Runoob' in sites :
      print('Runoob 在集合中')
      else :
      print('Runoob 不在集合中')


      # set可以进行集合运算
      a = set('abracadabra')
      b = set('alacazam')

      print(a)

      print(a - b) # a 和 b 的差集

      print(a | b) # a 和 b 的并集

      print(a & b) # a 和 b 的交集

      print(a ^ b) # a 和 b 中不同时存在的元素

8. Dictionary(字典)

  • 字典是一种映射类型,字典用 { } 标识,它是一个无序的 键(key) : 值(value) 的集合。

  • 键(key)必须使用不可变类型。

  • 在同一个字典中,键(key)必须是唯一的。

  • e.g.

    • ```python

      !/usr/bin/python3

      dict = {}
      dict[‘one’] = “1 - 菜鸟教程”
      dict[2] = “2 - 菜鸟工具”

      tinydict = {‘name’: ‘runoob’,’code’:1, ‘site’: ‘www.runoob.com’}

    print (dict['one'])       # 输出键为 'one' 的值
    print (dict[2])           # 输出键为 2 的值
    print (tinydict)          # 输出完整的字典
    print (tinydict.keys())   # 输出所有键
    print (tinydict.values()) # 输出所有值

    # answer
    1 - 菜鸟教程
    2 - 菜鸟工具
    {'name': 'runoob', 'code': 1, 'site': 'www.runoob.com'}
    dict_keys(['name', 'code', 'site'])
    dict_values(['runoob', 1, 'www.runoob.com'])
    
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

### 9. 数据类型转换

| 函数 | 描述 |
| ------------------------------------------------------------ | --------------------------------------------------- |
| [int(x [,base\])](https://www.runoob.com/python3/python-func-int.html) | 将x转换为一个整数 |
| [float(x)](https://www.runoob.com/python3/python-func-float.html) | 将x转换到一个浮点数 |
| [complex(real [,imag\])](https://www.runoob.com/python3/python-func-complex.html) | 创建一个复数 |
| [str(x)](https://www.runoob.com/python3/python-func-str.html) | 将对象 x 转换为字符串 |
| [repr(x)](https://www.runoob.com/python3/python-func-repr.html) | 将对象 x 转换为表达式字符串 |
| [eval(str)](https://www.runoob.com/python3/python-func-eval.html) | 用来计算在字符串中的有效Python表达式,并返回一个对象 |
| [tuple(s)](https://www.runoob.com/python3/python3-func-tuple.html) | 将序列 s 转换为一个元组 |
| [list(s)](https://www.runoob.com/python3/python3-att-list-list.html) | 将序列 s 转换为一个列表 |
| [set(s)](https://www.runoob.com/python3/python-func-set.html) | 转换为可变集合 |
| [dict(d)](https://www.runoob.com/python3/python-func-dict.html) | 创建一个字典。d 必须是一个 (key, value)元组序列。 |
| [frozenset(s)](https://www.runoob.com/python3/python-func-frozenset.html) | 转换为不可变集合 |
| [chr(x)](https://www.runoob.com/python3/python-func-chr.html) | 将一个整数转换为一个字符 |
| [ord(x)](https://www.runoob.com/python3/python-func-ord.html) | 将一个字符转换为它的整数值 |
| [hex(x)](https://www.runoob.com/python3/python-func-hex.html) | 将一个整数转换为一个十六进制字符串 |
| [oct(x)](https://www.runoob.com/python3/python-func-oct.html) | 将一个整数转换为一个八进制字符串 |

## 1-3 推导式

### 1. 列表(list)推导式

- 格式

- ```python
[表达式 for 变量 in 列表]
[out_exp_res for out_exp in input_list]
或者
[表达式 for 变量 in 列表 if 条件]
[out_exp_res for out_exp in input_list if condition]

# 注释
# ·out_exp_res:列表生成元素表达式,可以是有返回值的函数。
# ·for out_exp in input_list:迭代 input_list 将 out_exp 传入到 out_exp_res 表达式中。
# ·if condition:条件语句,可以过滤列表中不符合条件的值。
  • e.g.

    • ```python

      过滤掉长度小于或等于3的字符串列表,并将剩下的转换成大写字母:

      names = [‘Bob’,’Tom’,’alice’,’Jerry’,’Wendy’,’Smith’]
      new_names = [name.upper() for name in names if len(name)>3]
      print(new_names)
      [‘ALICE’, ‘JERRY’, ‘WENDY’, ‘SMITH’]

      计算 30 以内可以被 3 整除的整数:

      multiples = [i for i in range(30) if i % 3 == 0]
      print(multiples)
      [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]

      1
      2
      3
      4
      5
      6
      7

      ### 2. 字典(dict)推导式

      - ```python
      { key_expr: value_expr for value in collection }
      # 或
      { key_expr: value_expr for value in collection if condition }
  • e.g.

    • ```python
      listdemo = [‘Google’,’Runoob’, ‘Taobao’]

      将列表中各字符串值为键,各字符串的长度为值,组成键值对

      newdict = {key:len(key) for key in listdemo}
      newdict
      {‘Google’: 6, ‘Runoob’: 6, ‘Taobao’: 6}

      1
      2
      3
      4
      5
      6
      7
      8
      9



      ### 3. 集合(set)推导式

      - ```python
      { expression for item in Sequence }

      { expression for item in Sequence if conditional }
  • e.g.

    • ```python
      a = {x for x in ‘abracadabra’ if x not in ‘abc’}
      a
      {‘d’, ‘r’}
      type(a)
      1
      2
      3
      4
      5
      6
      7

      ### 4. 元组(tuple)推导式

      - ```python
      (expression for item in Sequence )

      (expression for item in Sequence if conditional )
  • e.g.

    • ```python

      a = (x for x in range(1,10))
      a
      at 0x7faf6ee20a50> # 返回的是生成器对象

      tuple(a) # 使用 tuple() 函数,可以直接将生成器对象转换成元组
      (1, 2, 3, 4, 5, 6, 7, 8, 9)

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      115
      116
      117
      118
      119
      120
      121
      122
      123
      124
      125
      126
      127
      128
      129
      130
      131
      132
      133
      134
      135
      136
      137
      138
      139
      140
      141
      142
      143
      144
      145
      146
      147
      148
      149
      150
      151
      152
      153
      154
      155
      156
      157
      158
      159
      160
      161
      162
      163
      164
      165
      166
      167
      168
      169
      170
      171
      172
      173
      174
      175
      176
      177
      178
      179
      180
      181
      182
      183
      184
      185
      186
      187
      188
      189
      190
      191
      192
      193
      194
      195
      196
      197



      ## 1-4 运算符

      ### 1. 算术运算符

      | 运算符 | 描述 | 实例 |
      | ------ | ----------------------------------------------- | ------------------ |
      | + | 加 - 两个对象相加 | a + b 输出结果 31 |
      | - | 减 - 得到负数或是一个数减去另一个数 | a - b 输出结果 -11 |
      | * | 乘 - 两个数相乘或是返回一个被重复若干次的字符串 | a * b 输出结果 210 |
      | / | 除 - x 除以 y | b / a 输出结果 2.1 |
      | % | 取模 - 返回除法的余数 | b % a 输出结果 1 |
      | ** | 幂 - 返回x的y次幂 | a**b 为10的21次方 |
      | // | 取整除 - 向下取接近商的整数 | 9//2 为4 |

      ### 2. 比较运算符

      | 运算符 | 描述 | 实例 |
      | :----- | :----------------------------------------------------------- | :-------------------- |
      | == | 等于 - 比较对象是否相等 | (a == b) 返回 False。 |
      | != | 不等于 - 比较两个对象是否不相等 | (a != b) 返回 True。 |
      | > | 大于 - 返回x是否大于y | (a > b) 返回 False。 |
      | < | 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。 | (a < b) 返回 True。 |
      | >= | 大于等于 - 返回x是否大于等于y。 | (a >= b) 返回 False。 |
      | <= | 小于等于 - 返回x是否小于等于y。 | (a <= b) 返回 True。 |

      ### 3. 赋值运算符

      | 运算符 | 描述 | 实例 |
      | :----- | :----------------------------------------------------------- | :----------------------------------------------------------- |
      | = | 简单的赋值运算符 | c = a + b 将 a + b 的运算结果赋值为 c |
      | += | 加法赋值运算符 | c += a 等效于 c = c + a |
      | -= | 减法赋值运算符 | c -= a 等效于 c = c - a |
      | *= | 乘法赋值运算符 | c *= a 等效于 c = c * a |
      | /= | 除法赋值运算符 | c /= a 等效于 c = c / a |
      | %= | 取模赋值运算符 | c %= a 等效于 c = c % a |
      | **= | 幂赋值运算符 | c **= a 等效于 c = c ** a |
      | //= | 取整除赋值运算符 | c //= a 等效于 c = c // a |
      | := | 海象运算符,可在表达式内部为变量赋值。**Python3.8 版本新增运算符**。 | 在这个示例中,赋值表达式可以避免调用 len() 两次:`if (n := len(a)) > 10: print(f"List is too long ({n} elements, expected <= 10)")` |

      ### 4. 位运算符

      | 运算符 | 描述 | 实例 |
      | :----- | :----------------------------------------------------------- | :----------------------------------------------------------- |
      | & | 按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0 | (a & b) 输出结果 12 ,二进制解释: 0000 1100 |
      | \| | 按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1。 | (a \| b) 输出结果 61 ,二进制解释: 0011 1101 |
      | ^ | 按位异或运算符:当两对应的二进位相异时,结果为1 | (a ^ b) 输出结果 49 ,二进制解释: 0011 0001 |
      | ~ | 按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1。**~x** 类似于 **-x-1** | (~a ) 输出结果 -61 ,二进制解释: 1100 0011, 在一个有符号二进制数的补码形式。 |
      | << | 左移动运算符:运算数的各二进位全部左移若干位,由"<<"右边的数指定移动的位数,高位丢弃,低位补0。 | a << 2 输出结果 240 ,二进制解释: 1111 0000 |
      | >> | 右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,">>"右边的数指定移动的位数 | a >> 2 输出结果 15 ,二进制解释: 0000 1111 |

      ### 5. 逻辑运算符

      | 运算符 | 逻辑表达式 | 描述 | 实例 |
      | :----- | :--------- | :----------------------------------------------------------- | :---------------------- |
      | and | x and y | 布尔"与" - 如果 x 为 False,x and y 返回 x 的值,否则返回 y 的计算值。 | (a and b) 返回 20。 |
      | or | x or y | 布尔"或" - 如果 x 是 True,它返回 x 的值,否则它返回 y 的计算值。 | (a or b) 返回 10。 |
      | not | not x | 布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 | not(a and b) 返回 False |

      ### 6. 成员运算符

      | 运算符 | 描述 | 实例 |
      | :----- | :------------------------------------------------------ | :------------------------------------------------ |
      | in | 如果在指定的序列中找到值返回 True,否则返回 False。 | x 在 y 序列中 , 如果 x 在 y 序列中返回 True。 |
      | not in | 如果在指定的序列中没有找到值返回 True,否则返回 False。 | x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。 |

      ### 7. 身份运算符

      | 运算符 | 描述 | 实例 |
      | :----- | :------------------------------------------ | :----------------------------------------------------------- |
      | is | is 是判断两个标识符是不是引用自一个对象 | **x is y**, 类似 **id(x) == id(y)** , 如果引用的是同一个对象则返回 True,否则返回 False |
      | is not | is not 是判断两个标识符是不是引用自不同对象 | **x is not y** , 类似 **id(x) != id(y)**。如果引用的不是同一个对象则返回结果 True,否则返回 False。 |

      - id()函数用于获取对象内存地址。
      - is 与 == 区别
      - is 用于判断两个变量引用对象是否为同一个
      - == 用于判断引用变量的值是否相等。

      ## 1-5 数字(Number)

      ### 1. 数学函数

      | 函数 | 返回值 ( 描述 ) |
      | :----------------------------------------------------------- | :----------------------------------------------------------- |
      | [abs(x)](https://www.runoob.com/python3/python3-func-number-abs.html) | 返回数字的绝对值,如abs(-10) 返回 10 |
      | [ceil(x)](https://www.runoob.com/python3/python3-func-number-ceil.html) | 返回数字的上入整数,如math.ceil(4.1) 返回 5 |
      | cmp(x, y) | 如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。 **Python 3 已废弃,使用 (x>y)-(x<y) 替换**。 |
      | [exp(x)](https://www.runoob.com/python3/python3-func-number-exp.html) | 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045 |
      | [fabs(x)](https://www.runoob.com/python3/python3-func-number-fabs.html) | 返回数字的绝对值,如math.fabs(-10) 返回10.0 |
      | [floor(x)](https://www.runoob.com/python3/python3-func-number-floor.html) | 返回数字的下舍整数,如math.floor(4.9)返回 4 |
      | [log(x)](https://www.runoob.com/python3/python3-func-number-log.html) | 如math.log(math.e)返回1.0,math.log(100,10)返回2.0 |
      | [log10(x)](https://www.runoob.com/python3/python3-func-number-log10.html) | 返回以10为基数的x的对数,如math.log10(100)返回 2.0 |
      | [max(x1, x2,...)](https://www.runoob.com/python3/python3-func-number-max.html) | 返回给定参数的最大值,参数可以为序列。 |
      | [min(x1, x2,...)](https://www.runoob.com/python3/python3-func-number-min.html) | 返回给定参数的最小值,参数可以为序列。 |
      | [modf(x)](https://www.runoob.com/python3/python3-func-number-modf.html) | 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。 |
      | [pow(x, y)](https://www.runoob.com/python3/python3-func-number-pow.html) | x**y 运算后的值。 |
      | [round(x [,n\])](https://www.runoob.com/python3/python3-func-number-round.html) | 返回浮点数 x 的四舍五入值,如给出 n 值,则代表舍入到小数点后的位数。**其实准确的说是保留值将保留到离上一位更近的一端。** |
      | [sqrt(x)](https://www.runoob.com/python3/python3-func-number-sqrt.html) | 返回数字x的平方根。 |

      ### 2. 随机数函数

      | 函数 | 描述 |
      | :----------------------------------------------------------- | :----------------------------------------------------------- |
      | [choice(seq)](https://www.runoob.com/python3/python3-func-number-choice.html) | 从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9中随机挑选一个整数。 |
      | [randrange ([start,\] stop [,step])](https://www.runoob.com/python3/python3-func-number-randrange.html) | 从指定范围内,按指定基数递增的集合中获取一个随机数,基数默认值为 1 |
      | [random()](https://www.runoob.com/python3/python3-func-number-random.html) | 随机生成下一个实数,它在[0,1)范围内。 |
      | [seed([x\])](https://www.runoob.com/python3/python3-func-number-seed.html) | 改变随机数生成器的种子seed。如果你不了解其原理,你不必特别去设定seed,Python会帮你选择seed。 |
      | [shuffle(lst)](https://www.runoob.com/python3/python3-func-number-shuffle.html) | 将序列的所有元素随机排序 |
      | [uniform(x, y)](https://www.runoob.com/python3/python3-func-number-uniform.html) | 随机生成下一个实数,它在[x,y]范围内。 |

      ### 3. 三角函数

      | 函数 | 描述 |
      | :----------------------------------------------------------- | :------------------------------------------------ |
      | [acos(x)](https://www.runoob.com/python3/python3-func-number-acos.html) | 返回x的反余弦弧度值。 |
      | [asin(x)](https://www.runoob.com/python3/python3-func-number-asin.html) | 返回x的反正弦弧度值。 |
      | [atan(x)](https://www.runoob.com/python3/python3-func-number-atan.html) | 返回x的反正切弧度值。 |
      | [atan2(y, x)](https://www.runoob.com/python3/python3-func-number-atan2.html) | 返回给定的 X 及 Y 坐标值的反正切值。 |
      | [cos(x)](https://www.runoob.com/python3/python3-func-number-cos.html) | 返回x的弧度的余弦值。 |
      | [hypot(x, y)](https://www.runoob.com/python3/python3-func-number-hypot.html) | 返回欧几里德范数 sqrt(x*x + y*y)。 |
      | [sin(x)](https://www.runoob.com/python3/python3-func-number-sin.html) | 返回的x弧度的正弦值。 |
      | [tan(x)](https://www.runoob.com/python3/python3-func-number-tan.html) | 返回x弧度的正切值。 |
      | [degrees(x)](https://www.runoob.com/python3/python3-func-number-degrees.html) | 将弧度转换为角度,如degrees(math.pi/2) , 返回90.0 |
      | [radians(x)](https://www.runoob.com/python3/python3-func-number-radians.html) | 将角度转换为弧度 |

      ## 1-6 字符串(String)

      ### 1. 字符串运算符

      | 操作符 | 描述 | 实例 |
      | :----- | :----------------------------------------------------------- | :------------------------------ |
      | + | 字符串连接 | a + b 输出结果: HelloPython |
      | * | 重复输出字符串 | a*2 输出结果:HelloHello |
      | [] | 通过索引获取字符串中字符 | a[1] 输出结果 **e** |
      | [ : ] | 截取字符串中的一部分,遵循**左闭右开**原则,str[0:2] 是不包含第 3 个字符的。 | a[1:4] 输出结果 **ell** |
      | in | 成员运算符 - 如果字符串中包含给定的字符返回 True | **'H' in a** 输出结果 True |
      | not in | 成员运算符 - 如果字符串中不包含给定的字符返回 True | **'M' not in a** 输出结果 True |
      | r/R | 原始字符串 - 原始字符串:所有的字符串都是直接按照字面的意思来使用,没有转义特殊或不能打印的字符。 原始字符串除在字符串的第一个引号前加上字母 **r**(可以大小写)以外,与普通字符串有着几乎完全相同的语法。 | `print( r'\n' ) print( R'\n' )` |
      | % | 格式字符串 | 请看下一节内容。 |

      ### 2. 字符串格式化

      | 符 号 | 描述 |
      | :----- | :----------------------------------- |
      | %c | 格式化字符及其ASCII码 |
      | %s | 格式化字符串 |
      | %d | 格式化整数 |
      | %u | 格式化无符号整型 |
      | %o | 格式化无符号八进制数 |
      | %x | 格式化无符号十六进制数 |
      | %X | 格式化无符号十六进制数(大写) |
      | %f | 格式化浮点数字,可指定小数点后的精度 |
      | %e | 用科学计数法格式化浮点数 |
      | %E | 作用同%e,用科学计数法格式化浮点数 |
      | %g | %f和%e的简写 |
      | %G | %f 和 %E 的简写 |
      | %p | 用十六进制数格式化变量的地址 |

      - 格式化操作符辅助指令

      | 符号 | 功能 |
      | :---- | :----------------------------------------------------------- |
      | * | 定义宽度或者小数点精度 |
      | - | 用做左对齐 |
      | + | 在正数前面显示加号( + ) |
      | <sp> | 在正数前面显示空格 |
      | # | 在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X') |
      | 0 | 显示的数字前面填充'0'而不是默认的空格 |
      | % | '%%'输出一个单一的'%' |
      | (var) | 映射变量(字典参数) |
      | m.n. | m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话) |

      ### 3. f-string

      - **f-string** 格式化字符串以 **f** 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去

      ```python
      >>> name = 'Runoob'
      >>> f'Hello {name}' # 替换变量
      'Hello Runoob'
      >>> f'{1+2}' # 使用表达式
      '3'

      >>> w = {'name': 'Runoob', 'url': 'www.runoob.com'}
      >>> f'{w["name"]}: {w["url"]}'
      'Runoob: www.runoob.com'

      # 在 Python 3.8 的版本中可以使用 = 符号来拼接运算表达式与结果
      >>> x = 1
      >>> print(f'{x+1}') # Python 3.6
      2

      >>> x = 1
      >>> print(f'{x+1=}') # Python 3.8
      x+1=2

4. 字符串内建函数

序号 方法及描述
1 capitalize() 将字符串的第一个字符转换为大写
2 center(width, fillchar)返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。
3 count(str, beg= 0,end=len(string)) 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
4 bytes.decode(encoding=”utf-8”, errors=”strict”) Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。
5 encode(encoding=’UTF-8’,errors=’strict’) 以 encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是’ignore’或者’replace’
6 endswith(suffix, beg=0, end=len(string)) 检查字符串是否以 obj 结束,如果beg 或者 end 指定则检查指定的范围内是否以 obj 结束,如果是,返回 True,否则返回 False.
7 expandtabs(tabsize=8) 把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。
8 find(str, beg=0, end=len(string)) 检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1
9 index(str, beg=0, end=len(string)) 跟find()方法一样,只不过如果str不在字符串中会报一个异常。
10 isalnum() 如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
11 isalpha() 如果字符串至少有一个字符并且所有字符都是字母或中文字则返回 True, 否则返回 False
12 isdigit() 如果字符串只包含数字则返回 True 否则返回 False..
13 islower() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
14 isnumeric() 如果字符串中只包含数字字符,则返回 True,否则返回 False
15 isspace() 如果字符串中只包含空白,则返回 True,否则返回 False.
16 istitle() 如果字符串是标题化的(见 title())则返回 True,否则返回 False
17 isupper() 如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
18 join(seq) 以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
19 len(string) 返回字符串长度
20 ljust(width[, fillchar]) 返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。
21 lower() 转换字符串中所有大写字符为小写.
22 lstrip() 截掉字符串左边的空格或指定字符。
23 maketrans() 创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
24 max(str) 返回字符串 str 中最大的字母。
25 min(str) 返回字符串 str 中最小的字母。
26 replace(old, new [, max]) 把 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次。
27 rfind(str, beg=0,end=len(string)) 类似于 find()函数,不过是从右边开始查找.
28 rindex( str, beg=0, end=len(string)) 类似于 index(),不过是从右边开始.
29 rjust(width,[, fillchar]) 返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串
30 rstrip() 删除字符串末尾的空格或指定字符。
31 split(str=””, num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串
32 splitlines([keepends]) 按照行(‘\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
33 startswith(substr, beg=0,end=len(string)) 检查字符串是否是以指定子字符串 substr 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。
34 strip([chars]) 在字符串上执行 lstrip()和 rstrip()
35 swapcase() 将字符串中大写转换为小写,小写转换为大写
36 title() 返回”标题化”的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())
37 translate(table, deletechars=””) 根据 table 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中
38 upper() 转换字符串中的小写字母为大写
39 zfill (width) 返回长度为 width 的字符串,原字符串右对齐,前面填充0
40 isdecimal() 检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。

1-7 列表(List)

1. 列表更新

  • 使用 append() 方法来添加列表项

2. 删除列表元素

  • 使用 del 语句来删除列表的的元素

3. 列表脚本操作符

Python 表达式 结果 描述
len([1, 2, 3]) 3 长度
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] 组合
[‘Hi!’] * 4 [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] 重复
3 in [1, 2, 3] True 元素是否存在于列表中
for x in [1, 2, 3]: print(x, end=” “) 1 2 3 迭代

4. 列表截取与拼接

Python 表达式 结果 描述
L[2] ‘Taobao’ 读取第三个元素
L[-2] ‘Runoob’ 从右侧开始读取倒数第二个元素: count from the right
L[1:] [‘Runoob’, ‘Taobao’] 输出从第二个元素开始后的所有元素

5. 列表函数&方法

  • 函数
序号 函数
1 len(list) 列表元素个数
2 max(list) 返回列表元素最大值
3 min(list) 返回列表元素最小值
4 list(seq) 将元组转换为列表
  • 方法
序号 方法
1 list.append(obj) 在列表末尾添加新的对象
2 list.count(obj) 统计某个元素在列表中出现的次数
3 list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4 list.index(obj) 从列表中找出某个值第一个匹配项的索引位置
5 list.insert(index, obj) 将对象插入列表
6 list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7 list.remove(obj) 移除列表中某个值的第一个匹配项
8 list.reverse() 反向列表中元素
9 list.sort( key=None, reverse=False) 对原列表进行排序
10 list.clear() 清空列表
11 list.copy() 复制列表

1-8 元组(Tuple)

  • 元组中只包含一个元素时,需要在元素后面添加逗号 , ,否则括号会被当作运算符使用

1. 元组运算符

Python 表达式 结果 描述
len((1, 2, 3)) 3 计算元素个数
(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) 连接
('Hi!',) * 4 (‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’) 复制
3 in (1, 2, 3) True 元素是否存在
for x in (1, 2, 3): print (x, end=" ") 1 2 3 迭代

2. 元组内置函数

序号 方法及描述 实例
1 len(tuple) 计算元组元素个数。 >>> tuple1 = ('Google', 'Runoob', 'Taobao') >>> len(tuple1) 3 >>>
2 max(tuple) 返回元组中元素最大值。 >>> tuple2 = ('5', '4', '8') >>> max(tuple2) '8' >>>
3 min(tuple) 返回元组中元素最小值。 >>> tuple2 = ('5', '4', '8') >>> min(tuple2) '4' >>>
4 tuple(iterable) 将可迭代系列转换为元组。 >>> list1= ['Google', 'Taobao', 'Runoob', 'Baidu'] >>> tuple1=tuple(list1) >>> tuple1 ('Google', 'Taobao', 'Runoob', 'Baidu')

1-9 字典(Dictionary)

1. 字典键的特性

  • 字典值可以是任何的 python 对象,既可以是标准的对象,也可以是用户定义的,但键不行。
    • 不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住
    • 键必须不可变,所以可以用数字,字符串或元组充当,而用列表就不行

2. 字典内置函数&方法

  • 函数
序号 函数及描述 实例
1 len(dict) 计算字典元素个数,即键的总数。 >>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> len(tinydict) 3
2 str(dict) 输出字典,可以打印的字符串表示。 >>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> str(tinydict) "{'Name': 'Runoob', 'Class': 'First', 'Age': 7}"
3 type(variable) 返回输入的变量类型,如果变量是字典就返回字典类型。 >>> tinydict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'} >>> type(tinydict) <class 'dict'>
  • 方法
序号 函数及描述
1 dict.clear() 删除字典内所有元素
2 dict.copy() 返回一个字典的浅复制
3 dict.fromkeys() 创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4 dict.get(key, default=None) 返回指定键的值,如果键不在字典中返回 default 设置的默认值
5 key in dict 如果键在字典dict里返回true,否则返回false
6 dict.items() 以列表返回一个视图对象
7 dict.keys() 返回一个视图对象
8 dict.setdefault(key, default=None) 和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
9 dict.update(dict2) 把字典dict2的键/值对更新到dict里
10 dict.values() 返回一个视图对象
11 pop(key[,default]) 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
12 popitem() 返回并删除字典中的最后一对键和值。

1-10 集合(Set)

1. 添加元素

1
2
3
4
5
6
7
s.add( x )
# 将元素 x 添加到集合 s 中,如果元素已存在,则不进行任何操作。

s.update( x )
# 还有一个方法,也可以添加元素,且参数可以是列表,元组,字典等
# x 可以有多个,用逗号分开。
thisset.update([1,4],[5,6])

2. 移除元素

1
2
3
4
5
6
7
8
s.remove( x )
# 将元素 x 从集合 s 中移除,如果元素不存在,则会发生错误。

s.discard( x )
# 此外还有一个方法也是移除集合中的元素,且如果元素不存在,不会发生错误。

s.pop()
# 设置随机删除集合中的一个元素

3. 集合内置方法

方法 描述
add() 为集合添加元素
clear() 移除集合中的所有元素
copy() 拷贝一个集合
difference() 返回多个集合的差集
difference_update() 移除集合中的元素,该元素在指定的集合也存在。
discard() 删除集合中指定的元素
intersection() 返回集合的交集
intersection_update() 返回集合的交集。
isdisjoint() 判断两个集合是否包含相同的元素,如果没有返回 True,否则返回 False。
issubset() 判断指定集合是否为该方法参数集合的子集。
issuperset() 判断该方法的参数集合是否为指定集合的子集
pop() 随机移除元素
remove() 移除指定元素
symmetric_difference() 返回两个集合中不重复的元素集合。
symmetric_difference_update() 移除当前集合中在另外一个指定集合相同的元素,并将另外一个指定集合中不同的元素插入到当前集合中。
union() 返回两个集合的并集
update() 给集合添加元素