
前言为什么要学数据类型很多刚学 Python 的同学写代码时总会报错字符串和数字不能相加、想要得到整数输出却输出小数、小数计算结果不对…… 根源就是分不清数据类型。 数据类型决定变量能存什么、能做什么运算。笔者只讲最常用的基础类型全部附带可运行代码零基础也能看懂。小知识1.type () 查看数据类型type(a) #a的数值类型1 Python的基本数据类型我们都知道C 语言标准的四大基础类型整型、字符型、浮点型、布尔型C99外加空类型 void 在python中则有 整数、浮点数、字符串、布尔值、空值这五大基本的数据类型。下面我将介绍一下这五种数据类型1 整数int存储整数 声明一个整数num 100 print(num, type(num)) E:\python2607\level1python 4.数值类型.py 100 class int E:\python2607\level12浮点数 float声明一个浮点数f1 3.14159 print(f1, type(f1)) f1 -3.14159 print(f1, type(f1)) E:\python2607\level1python 4.数值类型.py 3.14159 class float -3.14159 class float E:\python2607\level13字符串 str声明一个字符串str1 hello world print(str1, type(str1)) str2 hello world print(str2, type(str2)) str4 fgfgjrhfggjghjh print(str4, type(str4)) str5 fgfgjrhfggjghjh print(str5, type(str5)) hello world class str hello world class str fgfgjrhfggjghjh class str fgfgjrhfggjghjh class str4布尔 bool声明一个布尔值b1 True print(b1, type(b1)) b2 False print(b2, type(b2)) True class bool False class bool5空值 None声明一个变量 但是又不存储任何数据num None print(num, type(num)) None class NoneType2 Python整数进制转换我们常见的进制表示有 二进制、八进制、十进制、 十六进制下面我将介绍这些进制十进制Decimal基数10数字0,1,2,3,4,5,6,7,8,9 日常人类使用。二进制Binary基数2数字0、1 计算机底层存储只用二进制。 前缀标识0b十六进制Hexadecimal基数16数字0~9A (10)、B (11)、C (12)、D (13)、E (14)、F (15) 常用于内存、颜色、地址。 前缀标识0x八进制Octal基数8数字0~7 前缀标识0o下面展示Python中的进制进制表示与转换代码i 9 print(i, type(i)) 9 class intb 0b01110 print(b, type(b)) 14 class intc 0x1f print(c, type(c)) 31 class into 0o765 print(o, type(o)) 501 class int进制转换函数#int函数 将某进制转换为10进制 #base表示字符串内容是几进制 print(int(6474758, base10)) print(int(10011001, base2)) print(int(faa5f, base16)) print(int(77764, base8)) 6474758 153 1026655 32756#bin函数 10-2 print(bin(1000)) #oct函数 10-8 print(oct(1000)) #hex函数 10-16 print(hex(1000)) 0b1111101000 0o1750 0x3e83 Python数据类型转换函数int#int 可以将数字类型的字符串转整数 v int(fa336fbce, base16) print(v, type(v)) #int 可以将小数转为整数 v2 int(3.12222) print(v2, type(v2)) #int 可以将bool值转为整数 v3 int(True) v4 int(False) print(v3, v4) 67162799054 class int 3 class int 1 0float#float可以将数值类型最多一个小数点的字符串转为浮点数 f1 float(19999345655474) print(f1, type(f1)) f2 float(10333) print(f2, type(f2)) f3 float(1.223355) print(f3, type(f3)) f4 float(True) f5 float(False) print(f4, f5) 19999345655474.0 class float 10333.0 class float 1.223355 class float 1.0 0.0bool#任意类型都可以转换为布尔类型 b1 bool(yueiwrghuiryh32yh23) print(b1) b2 bool(123) print(b2) b3 bool(1.44566) print(b3) b4 bool() print(b4) b5 bool() print(b5) True True True False Falsestr#任意类型都可以转换为字符串 s1 str(235434654) print(s1) s2 str(‘’34546……%#‘’‘’‘Tgvgd) print(s2) s3 str(True) print(s3) s4 str(True) print(s4) 235434654 ‘’34546……%#‘’‘’‘Tgvgd True True