[TimLinux] Python 3.x 内建数据类型介绍

1. 内建(built-in)数据类型种类

  • 数字类型:int(), float()
  • 顺序(sequence):
    • 字符串:str()
    • 元祖:tuple()
    • 列表:list()
  • 字典:dict()
  • 集合:set()
  • 文件:open()
  • 布尔:True, False
  • 空对象:None

2. 各类型示例详解

2.1. 数字类型:

数字直接量示例

>>> 123 + 222  # 整数加
345

>>> 1.5 * 4  # 浮点数乘
6.0

>>> 2 ** 100  # 2的100次幂
1267650600228229401496703205376

>>> str(2**100)  # 转换为字符串

>>> 3.1415 * 2 #  (Python < 2.7 和 3.1),调用类的__repr__函数
6.28300000000004 

>>> print(3.1415 * 2)  # 调用了类的__str__函数
6.283

>>> import math  # 引入外部模块, math数学模块
>>> math.pi
3.141592653589793
>>> math.sqrt(85)
9.219544457292887

>>> import random  # 引入随机数模块
>>> random.random()  # 生产随机数, 小于1的正数
0.6489341324245831
>>> random.randint(1, 10) # 生产1~10之间的整数,含1,10
5
>>> random.choice([1,3,4,8]) # 1,3,4,8中随机选择一个数
4
View Code

第三方开源数字类型有:矩阵、向量、扩展精度数等。

字符串转换为数字示例

>>> help(int)
class int(object)
  int(x=0) -> integer
  int(x, base=10) --> integer (默认转换为10进制整数)

>>> int("12a")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12a'

>>> int("a12")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a12'

>>> int("abc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'

以上示例说明,含有非数字的字符串无法调用int()函数进行转换,使用过程中需要进行异常捕捉。

>>> int('12')
12

>>> int('12', 2)  # 字符串中的2在二进制模式内是越界的
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '12'

>>> int('1010', 2)
10

>>> int('0777')
777
>>> int('0777', 8)
511
>>> int('0x1212')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0x1212'
>>> int('0x1212', 16)
4626
>>> int('0xFF', 16)
255
>>> int('0xFG', 16)  # 字符G在十六进制中越界
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0xFG'

>>> help(float)
class float(object)
  float(x) -> floating point number # 只接收一个参数,只能包含点和数字
>>> float('0.1x')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not covert string to float: '0.1x')

>>> float('0.1')
0.1
>>> float('.1')
0.1

>>> float('0.1.2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not covert string to float: '0.1.2')
View Code

猜你喜欢

转载自www.cnblogs.com/timlinux/p/9059521.html