# Python 数字和转换

Jinku Hu 2023年1月30日 2018年3月7日

## Python 数字数据类型

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

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

``````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
``````

``````>>> print(0b110)
6
>>> print(0xFA)
250
>>> print(0o12)
10
``````

## Python 数字类型转换

### 隐式类型转换

``````>>> 2 + 3.0
5.0
``````

### 显式类型转换

``````>>> 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
``````
Author: Jinku Hu

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn