Python 中的数字类型与运算

PythonBeginner
立即练习

介绍

在这个 Lab 中,你将对 Python 中的数字类型和操作有一个基本的了解。我们将探索整数(integer)、布尔值(boolean)、浮点数(floating-point)和复数(complex number)类型的特性,包括它们的不可变性(immutability)以及如何检查它们的类型和内存地址。通过实践练习,你将学习如何在不同数字类型之间进行转换以及执行基本的算术运算,从而巩固你对 Python 数值能力的认识。

这是一个实验(Guided Lab),提供逐步指导来帮助你学习和实践。请仔细按照说明完成每个步骤,获得实际操作经验。根据历史数据,这是一个 初级 级别的实验,完成率为 98%。获得了学习者 100% 的好评率。

探索整数和布尔值类型

在这一步,我们将探索 Python 中的整数(int)和布尔值(bool)数据类型。整数是像 10-50 这样的整型数。布尔值代表 TrueFalse 这两个值之一,并且是整数的一个子类型。

Python 中一个重要的概念是不可变性(immutability)。数字类型是不可变的,这意味着一旦创建了一个数字对象,它的值就不能被改变。如果你将一个变量重新赋值给一个新的数字,它将指向内存中的一个新对象。我们可以使用内置的 id() 函数(返回对象的唯一内存地址)和 type() 函数(显示其数据类型)来验证这一点。

Lab 环境已经为你创建了一个文件。在左侧的 WebIDE 文件浏览器中,打开 ~/project/number_types.py 文件。将以下代码添加到其中:

## Demonstrate immutability of integers
a = 5
print(f"Initial value of a: {a}")
print(f"Type of a: {type(a)}")
print(f"ID of a: {id(a)}")

## Reassign 'a' to a new value
a = 6
print(f"\nNew value of a: {a}")
print(f"New ID of a: {id(a)}")

## Demonstrate boolean type
print("\n--- Boolean Types ---")
is_true = True
is_false = False
print(f"Value of is_true: {is_true}, Type: {type(is_true)}")
print(f"Value of is_false: {is_false}, Type: {type(is_false)}")

## Booleans behave like integers (1 and 0) in arithmetic
print(f"\nTrue + 5: {True + 5}")
print(f"False * 3: {False * 3}")

添加代码后,保存文件。要运行脚本,请在 WebIDE 中打开集成终端并执行以下命令:

python ~/project/number_types.py

你应该会看到类似以下的输出。请注意,内存地址(ID)在你的系统上会有所不同。

Initial value of a: 5
Type of a: <class 'int'>
ID of a: <memory_address_1>

New value of a: 6
New ID of a: <memory_address_2>

--- Boolean Types ---
Value of is_true: True, Type: <class 'bool'>
Value of is_false: False, Type: <class 'bool'>

True + 5: 6
False * 3: 0

输出显示,当 a5 被重新赋值为 6 时,它的 ID 发生了变化,这证实了创建了一个新的整数对象。它还表明在计算中,True 被当作 1False 被当作 0

处理浮点数

在这一步,我们将处理浮点数(float),它们表示带有小数点的实数。浮点数的一个常见问题是其精度有限,因为它们以二进制格式存储。这有时会导致计算中出现微小的误差。

让我们来探究一下这种行为。再次打开 ~/project/number_types.py 文件,并将以下代码添加到文件末尾。此代码将演示精度问题,并介绍两种处理方法:用于简单四舍五入的 round() 函数和用于高精度算术的 decimal 模块。

## Demonstrate floating-point numbers and precision
print("\n--- Floating-Point Numbers ---")
result = 1.1 + 2.2
print(f"1.1 + 2.2 = {result}")

## Using round() for approximation
print(f"round(result, 1) = {round(result, 1)}")

## Using the decimal module for accurate calculations
from decimal import Decimal

## Pass numbers as strings to Decimal to avoid initial float inaccuracy
d1 = Decimal('1.1')
d2 = Decimal('2.2')
decimal_result = d1 + d2
print(f"Decimal('1.1') + Decimal('2.2') = {decimal_result}")

保存文件,并再次从终端运行脚本:

python ~/project/number_types.py

你的输出现在将包含以下部分:

--- Floating-Point Numbers ---
1.1 + 2.2 = 3.3000000000000003
round(result, 1) = 3.3
Decimal('1.1') + Decimal('2.2') = 3.3

正如你所见,标准的浮点数加法 1.1 + 2.2 的结果并非精确的 3.3。虽然 round() 可以帮助格式化输出,但 decimal 模块提供了一种使用精确十进制表示进行计算的方法,从而得到精确的答案。

介绍复数

Python 内置支持复数,这在许多科学和工程领域至关重要。复数有一个实部和一个虚部,形式为 a + bj,其中 j 代表虚数单位。

你可以使用这种表示法或使用 complex(real, imag) 构造函数来创建复数。实部和虚部可以通过 .real.imag 属性访问。

继续编辑 ~/project/number_types.py 文件。在文件末尾添加以下代码以探索复数:

## Demonstrate complex numbers
print("\n--- Complex Numbers ---")
c1 = 3 + 4j
print(f"Complex number c1: {c1}")
print(f"Type of c1: {type(c1)}")
print(f"Real part of c1: {c1.real}")
print(f"Imaginary part of c1: {c1.imag}")

## Creating a complex number with the constructor
c2 = complex(5, -2)
print(f"\nComplex number c2: {c2}")
print(f"Real part of c2: {c2.real}")
print(f"Imaginary part of c2: {c2.imag}")

保存文件,并从终端运行脚本:

python ~/project/number_types.py

新的输出将是:

--- Complex Numbers ---
Complex number c1: (3+4j)
Type of c1: <class 'complex'>
Real part of c1: 3.0
Imaginary part of c1: 4.0

Complex number c2: (5-2j)
Real part of c2: 5.0
Imaginary part of c2: -2.0

请注意,即使你用整数定义实部和虚部,它们也都被存储为浮点数。

数字类型间转换

Python 提供了内置函数在不同数字类型之间进行转换,例如 int()float()complex()。这被称为类型转换(type casting)。

  • int(x): 将 x 转换为整数。当转换浮点数时,它会截断(切掉)小数部分,而不是四舍五入。
  • float(x): 将 x 转换为浮点数。
  • complex(real, imag): 创建一个复数。

让我们练习一下类型转换。将以下代码添加到你的 ~/project/number_types.py 脚本的末尾:

## Demonstrate type conversion
print("\n--- Type Conversion ---")

## Convert float to int (truncation)
float_num = 9.9
int_num = int(float_num)
print(f"float_num = {float_num}")
print(f"int(float_num) = {int_num}")

## Convert int to float
int_val = 10
float_val = float(int_val)
print(f"\nint_val = {int_val}")
print(f"float(int_val) = {float_val}")

## Convert string to number
str_num = "123.45"
converted_float = float(str_num)
converted_int = int(float(str_num)) ## Must convert to float first
print(f"\nstr_num = '{str_num}'")
print(f"float(str_num) = {converted_float}")
print(f"int(float(str_num)) = {converted_int}")

保存文件,并再次运行脚本:

python ~/project/number_types.py

输出现在将包含以下部分:

--- Type Conversion ---
float_num = 9.9
int(float_num) = 9

int_val = 10
float(int_val) = 10.0

str_num = '123.45'
float(str_num) = 123.45
int(float(str_num)) = 123

此输出清晰地展示了 int() 如何将 9.9 的小数部分截断为 9。它还说明了将包含小数的字符串转换为整数所需的两步过程。

执行基本算术运算

Python 支持所有标准的算术运算。当你对不同数字类型(例如 intfloat)的运算子执行操作时,Python 会自动将结果“提升”(widens)到更通用的类型。层次结构是 int -> float -> complex

以下是常见的运算符:

  • + (加法)
  • - (减法)
  • * (乘法)
  • / (除法 - 结果始终为 float)
  • // (整除 - 除法并向下取整到最近的整数)
  • % (取模 - 返回除法的余数)
  • ** (幂运算)

为了完成我们的探索,让我们向 ~/project/number_types.py 添加一个最终部分来练习这些运算。

## Demonstrate basic arithmetic operations
print("\n--- Basic Arithmetic Operations ---")
a = 10
b = 3

print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b}")
print(f"{a} // {b} = {a // b}")
print(f"{a} % {b} = {a % b}")
print(f"{a} ** {b} = {a ** b}")

## Demonstrate mixed-type operations
print("\n--- Mixed-Type Operations ---")
int_op = 5
float_op = 2.5
result_mixed = int_op * float_op
print(f"{int_op} (int) * {float_op} (float) = {result_mixed} ({type(result_mixed)})")

保存文件并运行完整的脚本:

python ~/project/number_types.py

最终输出将包括:

--- Basic Arithmetic Operations ---
10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3.3333333333333335
10 // 3 = 3
10 % 3 = 1
10 ** 3 = 1000

--- Mixed-Type Operations ---
5 (int) * 2.5 (float) = 12.5 (<class 'float'>)

此输出确认了每个运算符的行为。请注意,标准除法 / 产生一个 float,而整除 // 产生一个整数。整数和浮点数之间的混合类型运算如预期那样产生一个 float。

总结

在这个实验中,你对 Python 的数字数据类型获得了坚实的基础。你了解了整数(integers)、布尔值(booleans)、浮点数(floats)和复数(complex numbers)。你探索了不可变性(immutability)的概念,并使用了 id()type() 函数来检查对象。你练习了使用 decimal 模块处理浮点精度问题,使用 int()float()complex() 在不同数字类型之间进行转换,并执行了一系列算术运算。这些知识对于你在 Python 中进行任何进一步的编程或数据分析任务都至关重要。