整数
# 二进制n1 = 0b1010# 八进制n2 = 0o567# 十六进制n3 = 0xfdc2
浮点数
# 一般形式n1 = 3.14# 科学计数法n2, n3 = 3.2e6, 1.2e-3
简单数学函数
内建函数
- abs(num):
# 返回数的绝对值n1, n2, n3 = 1, 0, -1print(abs(n1), abs(n2), abs(n3)) # 1 0 1
- max(num) 和 min(num):
# 参数不定长n1, n2, n3, n4 = 1, 2, 3, 4print(max(n1, n2), min(n2, n3 , n4)) # 2 4# 接收可迭代对象li = [1, 2, 3, 4]print(max(li)) # 4
- round(num, n]):
# 四舍五入# n表示四舍五入的小数位数,不写默认是0(取整)pi = 3.14159print(round(pi)) # 3print(round(pi, 3)) #3.142
math模块中的函数
- ceil():
# 用来向上取整import mathpi = 3.14159print(round(pi)) # 3print(math.ceil(pi)) # 4print(round(pi + 0.5)) # 可以替代ceil()
- floor():
# 用来向下取整import mathx = 3.678print(round(x)) # 4print(math.floor(x)) # 3print(floor(x - 0.5)) # 可以替代floor()
- sqrt():
# 平方根运算import mathprint(math.sqrt(16)) # 4print(math.sqrt(17)) # 4.123105635
随机函数
- random():
import randomprint(random.random()) # 生成[0, 1)的一个小数
- choice(seq):
import randomli = [1, 2, 4, 5]print(random.choice(li)) # 从对应的列表中随机选择一个元素
- uniform(x, y):
import randomprint(random.uniform(1, 3) # 得到[1, 3]之间的随机小数
- randint(x, y):
import randomprint(random.randint(1, 5)) # [1, 5]之间的随机整数
- randrange(start, stop, step):
import randomprint(random.randrange(2, 10, 2) # 参数类型与range()函数一样# 相当于random.choice([2, 4, 6, 8])
三角函数
import mathangle = 1 / 6 * math.pi # 30°, pi/6res1 = math.sin(angle) # 接收弧度值angle = math.radians(30) # 将角度值转换为弧度值res1 = math.cos(angle)
布尔类型
是 int 的子类型,计算时会自动转换为 int
# True = 1, False = 0# 可以与整数进行运算print(2 + True) # 3print(1 + False) # 1
是一种单独的类型
flag, tag = True, False
可以当作判定条件使用
if True: # todo
字符串
字符串表示方式
str = 'abc' # 单引号对str = "abc" # 双引号对str = '''abc''' # 三个单引号str = """abc""" # 三个双引号# 混合表示,去掉字符串两端的限制符号就得到字符串数据# 可以避免使用引号的转义来表示引号str = "his name is 'rity', that is a good name"# 使用转义字符来完成str = "his name is 'rity', that is a good name"# 消除字符串的转义str1 = "That's all"str2 = r"That's all" print(str1) # That's allprint(str2) # That's all# 字符串的跨行表示str = "his name is 'rity', " "that is a good name"str = ("his name is 'rity', " "that is a good name") """可以直接在三对双引号内进行换行多用于程序段的注释---end---"""
字符串的操作
- 一般操作
- 字符串拼接
res1 = "abc" + "def"print(res1) # abcdefres2 = "abc" "def"print(res2) # abcdefres3 = "%s%S" % ("abc