Datewhale学习笔记02

Datewhale学习笔记2

$\textcolor{blue}{Datewhale学习笔记}$$\textcolor{red}{chap2}$

聪明办法学 Python 2nd Edition

Chapter 2 数据类型和操作 Data Types and Operators

In [15]

import math
def f():
    return 42

常用内置类型 Builtin Types

我们提前导入了 math 库,并创建了一个函数 f() (内容并不重要)

在本节中,我们将要见到这些基本类型:

  • 整数 Integer(int)
  • 浮点数 Float
  • 布尔值 Boolean(bool)
  • 类型 Type(是的,“类型”也是种类型!)

严格的来说,Type 是一种 对象,Python 是一门“面向对象友好”的语言

In [22]

print(type(2))
<class 'int'>

In [23]

print(type(2.2))
<class 'float'>

In [24]

print(type(2 < 2.2))
<class 'bool'>

In [27]

print(type(type(42)))
<class 'type'>

Python 中的一些基本类型

In [28]

print(type(2))           # int
print(type(2.2))         # float
print(type(2 < 2.2))     # bool (boolean)
print(type(type(42)))    # type 
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'type'>

在今后的内容中,我们将会见到更多类型:

  • 字符串 String(str)
  • 列表 List
  • 元组 Tuple
  • 集合 Set
  • 字典 Dictionary(dict,或者你可以叫它 映射 map
  • 复数 Complex Number(complex)
  • 函数 Function
  • 模块 Module

strlisttuplesetdict 将尝试用 数组 Array 的方式讲授

后续课程中会见到的类型

In [29]

print(type("2.2"))       # str (string or text)
print(type([1,2,3]))     # list
print(type((1,2,3)))     # tuple
print(type({1,2}))       # set
print(type({1:42}))      # dict (dictionary or map)
print(type(2+3j))        # complex  (complex number)
print(type(f))           # function
print(type(math))        # module
<class 'str'>
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>
<class 'complex'>
<class 'function'>
<class 'module'>

常用内置常数 Builtin Constants

常数区别于变量(将在下节课讲授),常数的值是固定的、不可改变的

Python 内置了一些常量

  • True,用于表示 布尔
  • False,用于表示 布尔
  • None,代表 ,用于空值

math 库中的一些数学常量

  • pi,数学常数 �π = 3.141592...,精确到可用精度
  • e,数学常数 ee = 2.718281...,精确到可用精度
  • tau,数学常数 �τ = 6.283185...,精确到可用精度(其实它不常用)
  • inf,浮点正无穷大,等价于 float('inf'),负无穷大使用 -math.inf

In [30]

print(True)
print(False)
print(None)
True
False
None

In [31]

print(math.pi)
print(math.e)
print(math.tau)
print(math.inf)
print(-math.inf)
3.141592653589793
2.718281828459045
6.283185307179586
inf
-inf

常用内置运算符 Builtin Operators

  • 算术:+, -, *, @, /, //, **, %, - (一元算符), + (一元算符)
  • 关系:<, <=, >=, >, ==, !=
  • 赋值: +=, -=, *=, /=, //=, **=, %=
  • 逻辑:and, or, not

我们暂时跳过按位运算符

整除 Integer Division (//)

这个知识点可能会在作业中发挥很大的作用,所以请多花些时间来理解它的运作方式

/` 指的是**浮点数**除法,它的结果是一个浮点数,例如 `2/1` 的结果是 `2.0

// 指的是整除除法,它的计算结果是整数,舍弃余数

/浮点数 除法操作符

In [34]

print(" 5/3  =", (5/3))
 5/3  = 1.6666666666666667

// 代表 整除

In [1]

print(" 5//3 =", ( 5//3))
print(" 2//3 =", ( 2//3))
print("-1//3 =", (-1//3))
print("-4//3 =", (-4//3))
 5//3 = 1
 2//3 = 0
-1//3 = -1
-4//3 = -2

模运算或余数运算符 (%)

这个知识点可能会在作业中发挥很大的作用,所以请多花些时间来理解它的运作方式

% 代表模运算(取余),结果为商的余数

例如:5 整除 2 的结果是 2余数1,则 5 % 2 的结果为 1

In [40]

print(" 6%3 =", ( 6%3))
print(" 5%3 =", ( 5%3))
print(" 2%3 =", ( 2%3))
print(" 0%3 =", ( 0%3))
print("-4%3 =", (-4%3))
print(" 3%0 =", ( 3%0))
 6%3 = 0
 5%3 = 2
 2%3 = 2
 0%3 = 0
-4%3 = 2

---------------------------------------------------------------------------****ZeroDivisionError Traceback (most recent call last)Cell In [40], line 6 4 print(" 0%3 =", ( 0%3)) 5 print("-4%3 =", (-4%3)) ----> 6 print(" 3%0 =", ( 3%0)) ZeroDivisionError: integer division or modulo by zero

$ a \mod b \iff a - (a \mid b) \times b $

In [38]

def mod(a, b):
  return a - (a//b)*b

In [39]

print(41%14 == mod(41,14))
print(14%41 == mod(14,41))
print(-32%9 == mod(-32,9))
print(32%-9 == mod(32,-9))
True
True
True
True

补充资料:注意 %math.fmod() 的区别,详见:Modulo operation

类型影响语义 Types Affect Semantics

运算符的运作方式会受到运算数据的类型的影响

In [41]

print(3 * 2)
print(3 * "p2s")
print(3 + 2)
print("Data" + "whale")
print(3 + "p2s")
6
p2sp2sp2s
5
Datawhale

---------------------------------------------------------------------------****TypeError Traceback (most recent call last)Cell In [41], line 5 3 print(3 + 2) 4 print("Data" + "whale") ----> 5 print(3 + "p2s") TypeError: unsupported operand type(s) for +: 'int' and 'str'

运算符优先级 Operator Order

优先顺序与结合律 Precedence and Associativity

In [1]

from IPython.display import IFrame
IFrame('https://docs.python.org/zh-cn/3.9/reference/expressions.html#operator-precedence', width=1300, height=600)
<IPython.lib.display.IFrame at 0x7fe502621360>

优先顺序 Precedence

In [43]

print(2+3*4)  # 14(不是 20)
print(5+4%3)  # 6(不是 0)
print(2**3*4) # 32(不是 4096)
14
6
32

结合律 Associativity

In [ ]

print(5-4-3)   # -2(不是 4)
print(4**3**2) # 262144(不是 4096)

浮点数误差

In [2]

print(0.1 + 0.1 == 0.2)        # True
print(0.1 + 0.1 + 0.1 == 0.3)  # False!
print(0.1 + 0.1 + 0.1)         # Why?
print((0.1 + 0.1 + 0.1) - 0.3) # 特别小,但不是 0
True
False
0.30000000000000004
5.551115123125783e-17

短路求值 Short-Circuit Evaluation

逻辑运算参照表

X Y X and Y X or Y not X not Y
True True True True False False
True False False True False True
False False False False True True
False True False True True False

我们先来定义一些函数

In [45]

def yes():
    return True

def no():
    return False

def crash():
    return 1/0 # 会崩溃!

In [47]

print(no() and crash()) # 成功运行!
print(crash() and no()) # 崩溃了!
print (yes() and crash()) # 因为上一行崩溃了,所以这行不会被运行,就是运行也会因为短路求值崩溃
False

---------------------------------------------------------------------------****ZeroDivisionError Traceback (most recent call last)Cell In [47], line 3 1 print(no() and crash()) # 成功运行! ----> 3 print (yes() and crash()) Cell In [45], line 8, in crash() 7 def crash(): ----> 8 return 1/0 ZeroDivisionError: division by zero

我们换成 or,再来试试

In [50]

print(yes() or crash()) # 成功运行
# print(crash() or yes()) # 崩溃了
print(no() or crash())  # 因为上一行崩溃了,所以这行不会被运行,就是运行也会因为短路求值崩溃
True

---------------------------------------------------------------------------****ZeroDivisionError Traceback (most recent call last)Cell In [50], line 3 1 print(yes() or crash()) # 成功运行 2 # print(crash() or yes()) # 崩溃了 ----> 3 print(no() or crash()) Cell In [45], line 8, in crash() 7 def crash(): ----> 8 return 1/0 ZeroDivisionError: division by zero

再来个例子,我们也先定义些函数

In [51]

def isPositive(n):
    result = (n > 0)
    print(n, "是不是正数?", result)
    return result

def isEven(n):
    result = (n % 2 == 0)
    print(n, "是不是偶数?", result)
    return result

In [64]

print(isEven(-4) and isPositive(-4)) # 调用了两个函数
-4 是不是偶数? True
-4 是不是正数? False
False

In [55]

print(isEven(-3) and isPositive(-3)) # 只调用了一个函数
-3 是不是偶数? False
False

type() vs isinstance()

In [57]

print(type("p2s") == str)
print(isinstance("p2s", str))
True
True

任务:编写代码,判断 x 是不是数字

In [58]

def isNumber(x):
    return ((type(x) == int) or
            (type(x) == float)) 

你能确保它能够判断所有数字吗?

In [59]

print(isNumber(1), isNumber(1.1), isNumber(1+2j), isNumber("p2s"))
True True False False
  • isinstance()type() 更具有 稳健性(Robustness)
  • 这种做法更加符合 面向对象编程继承(inheritance) 的思想

In [60]

import numbers
def isNumber(x):
    return isinstance(x, numbers.Number) # 可以应对任何类型的数字

In [61]

print(isNumber(1), isNumber(1.1), isNumber(1+2j), isNumber("p2s"))
True True True False

总结

  • Python 的类型系统很丰富,可以使用 type() 查看对应的类型
  • 常数类型的值是不可修改的
  • 除法操作默认是浮点数除法,整除操作需要使用 //
  • 运算符之间有运算优先级,运算符作用于不同对象之间的效果是不同的
  • 在进行逻辑判断时,会使用短路求值

原文链接

$\textcolor{red}{本文部分引用自网络}$

$\textcolor{red}{文章架构来源于课程ppt(免责声明)}$

课程ppt链接

posted @ 2023-11-25 18:33  瑟兰迪尔·绿叶  阅读(47)  评论(0)    收藏  举报