python-task3:Data Types and Operators

发布时间 2023-11-23 15:30:04作者: 别小乔我

常见数据类型

  • 整数 Integer(int)
  • 浮点数 Float(python中默认为双精度浮点型)
  • 布尔值 Boolean(bool)
  • 类型 Type(“类型”也是种类型)

其他数据类型

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

print(type("2.2")) # str 
print(type([1,2,3])) # list 
print(type((1,2,3))) # tuple 
print(type({1,2})) # set 
print(type({1:42})) # dict or map
print(type(2+3j)) # complex 
print(type(f)) # function 
print(type(math)) # module

python内置常数

常数区别于变量,常数的值是固定的、不可改变的

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

math库中的一些数学常量

  • pi,数学常数π = 3.141592...
  • e,数学常数e = 2.718281...
  • tau,数学常数τ = 6.283185... (2*pi)
  • inf,浮点正无穷大,等价于float('inf'),负无穷大使用-math.inf

常用内置运算符

  • 算术+, -, *, @(矩阵乘法), /(浮点除), //(整除), **(幂), %(模运算), - (一元算符), + (一元算符)

    取模运算 %

    对于整型数a,b来说,取模运算或者求余运算的方法都是:

    计算方法:a - (a//b)*b

    例如:10%(-3)*=-2

    10//(-3)=-4
    10 - (-4)*(-3)=2
    
  • 关系<, <=, >=, >, ==, !=

  • 赋值+=, -=, *=, /=, //=, **=, %=

  • 逻辑and, or, not

    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

    逻辑运算符 not>and>or

    !所有的空字符串都是假,非空字符串都是真,非零的数字都是真。

    not: x为假,输出True,x为真,输出False
    and:x and y 的值只能是x 和 y,x为真时就是y,x为假就是x
    or: x or y 的值只可能是 x 和 y,x为真就是x,x为假就是y

Python运算符优先级 (从高到低)

**:幂运算

~, +, -:按位取反,正号,负号

*, /, %, //:乘,除,取模,整除

+, -:加,减

<<, >>:左移,右移

&:按位与

^:按位异或

|:按位或

==, !=, >, >=, <, <=, is, is not, in, not in:比较运算符,包括身份和成员运算符

not:布尔“非”

and:布尔“与”

or:布尔“或”

结合律:从左到右算,,(幂从右往左算)

print(5-4-3) # -2(不是 4) 
print(4**3**2) # 262144(不是 4096)先算3**2,再算4**9

浮点数误差

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) # 特别小,5.551115123125783e-17,不是0

type() VS isinstance()


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

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

def isNumber(x): 
	return ((type(x) == int) or (type(x) == float)) #不能判断所有数字,忽略了复数
print(isNumber(1), isNumber(1.1), isNumber(1+2j), isNumber("p2s"))
# True True False False

import numbers 
def isNumber(x): 
	return isinstance(x, numbers.Number) # 可以应对任何类型的数字
print(isNumber(1), isNumber(1.1), isNumber(1+2j), isNumber("p2s"))
# True True True False
  • isinstance()type() 更具有 稳健性
  • 这种做法更加符合 面向对象编程中 继承 的思想