快捷搜索:  汽车  科技

python数字形式转换教程(Python数字和转换)

python数字形式转换教程(Python数字和转换)二进制前缀x = 3 print("type of" x "is" type(x)) x = 3.23 print("type of" x "is" type(x)) x = 3 3j print("is" x "a complex number:" isinstance(x complex)) type of 3 is <class 'int'> type of 3.23 is <class 'float'> is (3 3j) a complex number: True 整数可以是任意长度,但浮点数只能达到 15 位小数。整数也可以用二进制、十六进制和八进制格式表示,它们通过使用前缀来区分。如下表:数字系统

在本节中,我们来学习 Python 中的数字数据类型以及你可以对这些数字执行的数学运算。此外,我们还会学习如何从一种数据类型转换为另一种数据类型。

Python 数字数据类型

Python 中的数字数据类型包括:

  1. 整数
  2. 浮点数字
  3. 复数

其中,复数有一个实部和一个虚部。复数的形式为 x yj ,其中 x 是实部, yj 是虚部。

函数 type() 用于获取变量的数据类型,或者更简单来说是一个对象。函数 isinstance() 用于查看变量是否属于某个特定的类。

x = 3 print("type of" x "is" type(x)) x = 3.23 print("type of" x "is" type(x)) x = 3 3j print("is" x "a complex number:" isinstance(x complex))

type of 3 is <class 'int'> type of 3.23 is <class 'float'> is (3 3j) a complex number: True

整数可以是任意长度,但浮点数只能达到 15 位小数。

整数也可以用二进制、十六进制和八进制格式表示,它们通过使用前缀来区分。如下表:

数字系统

前缀

二进制

0b or 0B

八进制

0o or 0O

十六进制

0x or 0X

举例

>>> print(0b110) 6 >>> print(0xFA) 250 >>> print(0o12) 10 Python 数字类型转换隐式类型转换

如果一个 float 类型的数字和另一个 int 类型的数字相加,那结果的数据类型将是 float 。这里 int 被隐式转换为 float 。

>>> 2 3.0 5.0

这种转换被称为隐式类型转换。

显式类型转换

你也可以使用 int() 、 float() 和 str() 等函数进行显式数字数据类型转换。

>>> x = 8 >>> print("Value of x = " int(x)) Value of x = 8 >>> print("Converted Value of x = " float(x)) Converted Value of x = 8.0

当浮点类型被转换为整数类型时候,小数点后面的数字被舍去。

Python 分数

Python 中有一个 fractions 模块用于执行涉及分数的操作。 fractions 模块可以将分数表示为 分子/分母 的形式。

import fractions print(fractions.Fraction(0.5))

1/2

fractions 模块中的 Fraction 函数将小数转换为分数,然后你可以对这些分数执行数学运算:

print(Fraction(0.5) Fraction(1.5)) print(Fraction(0.5) * Fraction(1.5)) print(Fraction(0.5) / Fraction(1.5))

2 3/4 1/3



python数字形式转换教程(Python数字和转换)(1)

猜您喜欢: