geekdoc-python-zh/docs/pythonland/28.md

91 lines
3.0 KiB
Markdown
Raw Permalink Normal View History

2024-03-03 22:54:39 +08:00
# Python Integer:用示例代码解释
> 原文:[https://python.land/python-data-types/python-integer](https://python.land/python-data-types/python-integer)
Python 整数是一个非小数,如 1、2、45、-1、-2 和-100。这是 Python 本身支持的三种数字类型之一,另外两种是浮点数和复数。
目录
* [Python 整数的最大大小](#Max_size_of_a_Python_integer "Max size of a Python integer")
* [整数类型](#Integer_types "Integer types")
* [转换成整数](#Converting_from_and_to_an_integer "Converting from and to an integer")
* [Python 随机整数](#Python_random_integer "Python random integer")
* [是 Python 整数吗?](#Is_it_a_Python_integer "Is it a Python integer?")
## Python 整数的最大大小
与许多其他编程语言不同Python 3 中的整数可以有很大的值。事实上,它们是无限的,这意味着它们的大小没有限制,例如:
```py
>>> num = 98762345098709872345000
>>> num + 1
98762345098709872345001
```
当然,这是有限制的,因为你的电脑没有无限的内存。然而,出于所有实际目的,您不必为此担心。
## 整数类型
与 Python 2 和许多其他语言不同Python 3 只有一种类型的整数。这是 Python 渴望成为一种干净、易学的语言的一部分。我们又少了一件需要担心的事情。更多详情,请参见 [PEP-0237](https://www.python.org/dev/peps/pep-0237/) 。
## 转换成整数
### 字符串到整数
要在 Python 中将一个[字符串](https://python.land/introduction-to-python/strings)转换成整数,使用`int()` [函数](https://python.land/introduction-to-python/functions):
```py
>>> int('100')
100
```
### 整数到字符串
要在 Python 中将整数转换成字符串,使用`str()` [函数](https://python.land/introduction-to-python/functions):
```py
>>> str(200)
'200'
```
### 浮点到整数
要将浮点数转换成整数,使用`int()` [函数](https://python.land/introduction-to-python/functions):
```py
>>> int(2.3)
2
```
## Python 随机整数
许多用例需要一个随机整数。为此,需要[导入模块](https://python.land/project-structure/python-modules) `random`。请注意,这提供了*伪随机性*,不适合加密。
让我们得到一个随机数:
```py
>>> import random
>>> random.randint(1,10)
```
上面的指令返回一个从 1 到 10(含)的伪随机数,也就是说*包括* 1 和 10。关于随机模块的全部细节请访问 [Python 文档](https://docs.python.org/3/library/random.html)。
## 是 Python 整数吗?
要检查一个值是否是整数,我们可以使用`type()` [函数](https://python.land/introduction-to-python/functions)。对于整数,它将返回`int`。这里有一个如何在`if`语句中使用它的简单例子:
```py
>>> type(2)
int
>>> if isinstance(2, int):
... print('An integer')
...
An integer
```
不要用`if type(2) == int`。
使用`isinstance()`几乎总是更好、更干净的方式,并且覆盖更多的用例,比如子类。