Python int() 函数

2024年9月26日 | 阅读 2 分钟

Python int() 函数用于获取整数值。 它返回转换为整数的表达式。 如果参数是浮点数,则转换会截断该数字。 如果参数超出整数范围,它会将数字转换为长整型。

如果该数字不是数字或给定了基数,则该数字必须是字符串。

签名

参数

x : 要转换为整数类型的数字。

base: 这是一个可选参数,如果使用数字,则必须是字符串。

返回

它返回一个整数值。

让我们看一些 int() 函数的示例来了解其功能。

Python int() 函数示例 1

这是一个简单的 python 示例,它将浮点值和字符串值转换为整数类型。 浮点值被该函数截断并返回一个整数。

输出

integer values : 10 10 10

Python int() 函数示例 2

为了验证返回值的类型,我们可以使用 type 函数。 type 函数返回值的类型。 请看下面的例子。

输出

<class 'int'> <class 'float'> <class 'str'>
values after conversion  10 10 10
and types are: 
  <class 'int'> <class 'int'> <class 'int'>

Python int() 函数示例 3

输出

Values after conversion: 2 175 8
and types are: 
  <class 'int'> <class 'int'> <class 'int'>

下一个主题Python 函数