#Chapter 2 数据类型和操作 Data Types and Operators
import math ##导入 math 库,并创建了函数 f()
def f():
return 42
##常用内置类型 Builtin Types
print(type(2)) # int
print(type(2.2)) # float
print(type(2 < 2.2)) # bool (boolean)
print(type(type(42))) # type
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
####常用内置常数 Builtin Constants
print(True)
print(False)
print(None)
print(math.pi)
print(math.e)
print(math.tau)
print(math.inf)##浮点正无穷大,等价于 float('inf')
print(-math.inf)##负无穷大
print(float('inf'))
###常用内置运算符 Builtin Operators
### @矩阵乘法 //整除 / 浮点除 **次方 %模运算求余
### ==等于 但赋值只需要=
### +=, -=, *=, /=, //=, **=, %=先运算再赋值
### 逻辑:and, or, not
print(type(2/1))
print(type(1//2))##// 指的是整除除法,它的计算结果是整数,舍弃余数
print(" 6%3 =", ( 6%3))
print(" 2%3 =", ( 2%3))
print(" 0%3 =", ( 0%3))
print("-4%3 =", (-4%3))
print("-4//3 =", (-4//3))
print(" 5//3 =", ( 5//3))###1
print("math.fmod(5,3)=",math.fmod(5,3))###2.0
####类型影响语义 Types Affect Semantics
print(3 * 2)
print(3 * "p2s")
print(3 + 2)
print("Data" + "whale")
print("3" + "p2s")
####运算符优先级 Operator Order
print(2+3*4) # 14(不是 20)
print(5+4%3) # 6(不是 0)
print(2**3*4) # 32(不是 4096)
print(5-4-3) # -2(不是 4)加减从左到右
print(4**3**2) # 262144(不是 4096)次方从右往左
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) # 0.30000000000000004
print((0.1 + 0.1 + 0.1) - 0.3) # 特别小,但不是 0
###短路求值 Short-Circuit Evaluation
###第一个假就是假 or运算第一个真就是真
##定义一些函数
def yes():
return True
def no():
return False
def crash():
return 1/0 # 会崩溃!
print(no() and crash()) # 成功运行!
#print(crash() and no()) # 崩溃了!
#print (yes() and crash()) # 因为上一行崩溃了所以这行不会被运行,就是运行也会因为短路求值崩溃
print(yes() or crash()) # 成功运行
# print(crash() or yes()) # 崩溃了
#print(no() or crash()) # 因为上一行崩溃了,所以这行不会被运行
def isPositive(n):
result = (n > 0)
print(n, "是不是正数?", result)
return result
def isEven(n):
result = (n % 2 == 0)
print(n, "是不是偶数?", result)
return result ####被2整除
print(isEven(-4) and isPositive(-4)) # 调用了两个函数
print(isEven(-3) and isPositive(-3)) # 只调用了一个函数
###type() vs isinstance()
print(type("p2s") == str)
print(isinstance("p2s", str))
#任务:编写代码,判断 x 是不是数字
def isNumber(x):
return ((type(x) == int) or
(type(x) == float)) ####忽略了复数!!!
##isinstance() 比 type() 更具有 稳健性(Robustness)这种做法更加符合 面向对象编程 中 继承(inheritance) 的思想
import numbers
def isNumber(x):
return isinstance(x, numbers.Number) # 可以应对任何类型的数字
print(isNumber(1), isNumber(1.1), isNumber(1+2j), isNumber("p2s"))