Python的基础入门
一、Python 的基本数据类型
1. 整数 <class 'int'>
num = 0
print(num, type(num))
2. 浮点数 <class 'float'>
f1 = 3.1415926
f1_type = type(f1)
print(f1, f1_type)
3. 字符串 <class 'str'>
s1 = "hello world"
print("s1", type(s1))
s2 = 'hello world'
print("s2", type(s2))
4. 布尔值变量 <class 'bool'>
b1 = True
print(b1, type(b1))
b2 = False
print(b2, type(b2))
5. 空值 <class 'NoneType'>
n = None
print(n, type(n))
二、Python 的整数进制转换
1. 定义 2 进制变量
以前缀 0b 开头,数字只有 0 和 1。
逢二进一
b = 0b11000110
print(b, type(b))
2. 转 10 进制推导公式
从右侧数第 n 个数字 m,数值为 m * 底数的 n-1 次方。
例:198 为 128 + 64 + 4 + 2,为 2 的七次方 + 2 的六次方 + 2 的二次方 + 2 的一次方。
共八位,二进制为 11000110。
3. 定义 16 进制变量
以 0x 前缀,数字 0-9,字母 a-f。
逢十六进一。
h = 0xf11a
print(h, type(h))
4. 定义 8 进制变量
以 0o 前缀,数字 0-7。
逢八进一。
o = 0o66 # 6*8 的 1 次方 + 6*8 的 0 次方 = 54
print(o, type(o))
5. 进制转换函数
int 可以转换为十进制,base 表示字符串中的内容是几进制。
print(int("16", base=10))
print(int("1000110", base=2))
print(int("a12f", base=16))
print(int("77", base=8))
三、Python 数据类型转换函数
1. int 函数
int 可以将数字类型的字符串转化成整数。
v = int("10abcde", base=16)
print(v, type(v))
int 可以将小数转化成整数。
v2 = int(3.1415926)
print(v2, type(v2))
int 可以将 bool 值转化成整数。
v3 = int(True)
v4 = int(False)
print(v3, v4)
2. float 函数
float 可以将数字类型(最多一个小数点)的字符串转化成浮点数。
f1 = float(1234)
print(f1, type(f1))
f2 = float(True)
f3 = float(False)
print(f2, f3)
3. 布尔值
任意类型都可以转化成布尔值。
b1 = bool(0)
print(b1, type(b1))
b2 = bool(0.00000001)
print(b2, type(b2))
b3 = bool("False")
print(b3, type(b3))
b4 = bool("")
print(b4, type(b4))
b5 = bool(None)
print(b5, type(b5))
4. str 函数
str 可以将任意类型转换成字符串。
s1 = str(1)
print(s1, type(s1))
s2 = str(1.0001)
print(s2, type(s2))
s3 = str(False)
print(s3, type(s3)) # "False"
s4 = str(None)
print(s4, type(s4))