Python 变量与数据类型

PythonPythonBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在这个实验中,你将学习 Python 变量和数据类型的基本概念。变量是编程中必不可少的构建块,它允许你在代码中存储、访问和操作数据。理解不同的数据类型对于编写有效的 Python 程序至关重要。

你将创建各种变量,探索 Python 中可用的不同数据类型,执行类型转换,并学习如何在表达式中使用变量。这些技能是 Python 编程的基础,也是开发更复杂应用程序所必需的。

在本实验结束时,你将能够自如地在 Python 中创建和使用不同数据类型的变量。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/BasicConceptsGroup -.-> python/strings("Strings") python/BasicConceptsGroup -.-> python/booleans("Booleans") python/BasicConceptsGroup -.-> python/type_conversion("Type Conversion") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") subgraph Lab Skills python/variables_data_types -.-> lab-271605{{"Python 变量与数据类型"}} python/numeric_types -.-> lab-271605{{"Python 变量与数据类型"}} python/strings -.-> lab-271605{{"Python 变量与数据类型"}} python/booleans -.-> lab-271605{{"Python 变量与数据类型"}} python/type_conversion -.-> lab-271605{{"Python 变量与数据类型"}} python/conditional_statements -.-> lab-271605{{"Python 变量与数据类型"}} end

创建你的第一个 Python 变量

在这一步中,你将学习如何在 Python 中创建和使用变量。变量是用于存储数据值的容器,并且为它们赋予有意义的名称,以便在代码中更方便地引用。

让我们从创建一个新的 Python 文件并定义一些基本变量开始:

  1. 在 WebIDE 中打开文件 /home/labex/project/variables.py

  2. 添加以下代码来定义三个变量:

## Creating basic variables
water_supply = 100    ## Amount of water in gallons
food_supply = 50      ## Amount of food in pounds
ammunition = 40       ## Number of ammunition rounds

在 Python 中,你可以通过指定一个名称,后跟等号 (=),然后是你要赋给它的值来创建一个变量。

  1. 让我们添加代码来显示这些变量的值:
## Displaying variable values
print("Water supply:", water_supply)
print("Food supply:", food_supply)
print("Ammunition:", ammunition)
  1. 在 WebIDE 中打开一个终端并执行以下命令来运行你的脚本:
python3 /home/labex/project/variables.py

你应该会看到以下输出:

Water supply: 100
Food supply: 50
Ammunition: 40

恭喜你。你已经创建了你的第一个 Python 变量并显示了它们的值。这些变量存储了你的程序可以访问和操作的信息。

理解数值数据类型

Python 有几种用于对不同类型的数据进行分类的数据类型。在这一步中,你将了解两种数值数据类型:整数(integer)和浮点数(float)。

  1. 在 WebIDE 中打开文件 /home/labex/project/variables.py

  2. 在文件中添加以下代码,以定义具有不同数值数据类型的变量:

## Numeric data types
integer_value = 42        ## Integer (whole number)
float_value = 3.14159     ## Float (decimal number)
  1. 让我们使用 type() 函数来探究这些变量的类型:
## Check the data types
print("\nUnderstanding data types:")
print("integer_value:", integer_value, "- Type:", type(integer_value))
print("float_value:", float_value, "- Type:", type(float_value))
  1. 现在,让我们对这些数值类型执行一些基本运算:
## Basic operations with numbers
sum_result = integer_value + float_value
product_result = integer_value * float_value

print("\nBasic operations:")
print(f"{integer_value} + {float_value} = {sum_result}")
print(f"{integer_value} * {float_value} = {product_result}")
  1. 运行你的脚本:
python3 /home/labex/project/variables.py

你应该会看到类似于以下的输出:

Water supply: 100
Food supply: 50
Ammunition: 40

Understanding data types:
integer_value: 42 - Type: <class 'int'>
float_value: 3.14159 - Type: <class 'float'>

Basic operations:
42 + 3.14159 = 45.14159
42 * 3.14159 = 131.94678

请注意,当你对整数和浮点数进行运算时,Python 会在需要时自动将结果转换为浮点数。

处理字符串和布尔值

除了数值数据类型外,Python 还提供了用于处理文本数据的字符串(string)和用于表示真假值的布尔值(boolean)。让我们来探索这些类型:

  1. 在 WebIDE 中打开文件 /home/labex/project/variables.py

  2. 添加以下代码来定义字符串和布尔变量:

## String data type - for text
camp_name = "Python Base Camp"
location = 'Programming Valley'  ## Strings can use single or double quotes

## Boolean data type - for true/false values
is_safe = True
has_water = True
enemy_nearby = False
  1. 添加代码来检查并显示这些变量:
## Displaying string and boolean variables
print("\nString variables:")
print("Camp name:", camp_name, "- Type:", type(camp_name))
print("Location:", location, "- Type:", type(location))

print("\nBoolean variables:")
print("Is the camp safe?", is_safe, "- Type:", type(is_safe))
print("Is water available?", has_water, "- Type:", type(has_water))
print("Is enemy nearby?", enemy_nearby, "- Type:", type(enemy_nearby))
  1. 让我们再演示一些字符串操作:
## String operations
full_location = camp_name + " in " + location
print("\nFull location:", full_location)

## String repetition
border = "-" * 20
print(border)
print("Camp Information")
print(border)
  1. 运行你的脚本:
python3 /home/labex/project/variables.py

你应该会看到类似于以下的输出:

Water supply: 100
Food supply: 50
Ammunition: 40

Understanding data types:
integer_value: 42 - Type: <class 'int'>
float_value: 3.14159 - Type: <class 'float'>

Basic operations:
42 + 3.14159 = 45.14159
42 * 3.14159 = 131.94678

String variables:
Camp name: Python Base Camp - Type: <class 'str'>
Location: Programming Valley - Type: <class 'str'>

Boolean variables:
Is the camp safe? True - Type: <class 'bool'>
Is water available? True - Type: <class 'bool'>
Is enemy nearby? False - Type: <class 'bool'>

Full location: Python Base Camp in Programming Valley
--------------------
Camp Information
--------------------

注意字符串如何使用 + 运算符进行拼接,以及如何使用 * 运算符进行重复。布尔值对于表示条件和控制程序流程非常有用。

类型转换和类型检查

有时你需要将值从一种数据类型转换为另一种数据类型,或者检查变量的数据类型。这被称为类型转换(或类型强制转换)。让我们来探讨这个概念:

  1. 在 WebIDE 中打开文件 /home/labex/project/variables.py

  2. 添加代码来演示类型转换:

## Type conversion examples
print("\nType Conversion Examples:")

## Converting string to integer
supplies_str = "75"
supplies_int = int(supplies_str)
print(f"String '{supplies_str}' converted to integer: {supplies_int} - Type: {type(supplies_int)}")

## Converting integer to string
days_int = 30
days_str = str(days_int)
print(f"Integer {days_int} converted to string: '{days_str}' - Type: {type(days_str)}")

## Converting integer to float
distance_int = 100
distance_float = float(distance_int)
print(f"Integer {distance_int} converted to float: {distance_float} - Type: {type(distance_float)}")

## Converting float to integer (note: this truncates the decimal part)
temperature_float = 32.7
temperature_int = int(temperature_float)
print(f"Float {temperature_float} converted to integer: {temperature_int} - Type: {type(temperature_int)}")
  1. 添加代码来检查数据类型:
## Type checking
print("\nType Checking Examples:")
value1 = 42
value2 = "42"
value3 = 42.0

print(f"Is {value1} an integer? {isinstance(value1, int)}")
print(f"Is {value2} an integer? {isinstance(value2, int)}")
print(f"Is {value3} a float? {isinstance(value3, float)}")
print(f"Is {value2} a string? {isinstance(value2, str)}")
  1. 运行你的脚本:
python3 /home/labex/project/variables.py

你应该会看到类似于以下的输出:

...previous output...

Type Conversion Examples:
String '75' converted to integer: 75 - Type: <class 'int'>
Integer 30 converted to string: '30' - Type: <class 'str'>
Integer 100 converted to float: 100.0 - Type: <class 'float'>
Float 32.7 converted to integer: 32 - Type: <class 'int'>

Type Checking Examples:
Is 42 an integer? True
Is 42 an integer? False
Is 42.0 a float? True
Is 42 a string? True

请注意:

  • int() 函数将值转换为整数
  • float() 函数将值转换为浮点数
  • str() 函数将值转换为字符串
  • 当将浮点数转换为整数时,小数部分会被截断(而非四舍五入)
  • isinstance() 函数用于检查变量是否为指定类型

当你需要处理用户输入或处理来自不同来源的数据时,这些转换函数非常有用。

表达式和决策中的变量

当变量用于表达式和决策结构时,它们会变得非常强大。让我们来探索如何在计算和条件语句中使用变量:

  1. 在 WebIDE 中打开文件 /home/labex/project/variables.py

  2. 添加代码以演示在计算中使用变量:

## Variables in expressions
print("\nVariables in Expressions:")

water_per_day = 4  ## gallons
food_per_day = 2.5  ## pounds

## Calculate how long supplies will last
water_days = water_supply / water_per_day
food_days = food_supply / food_per_day

print(f"With {water_supply} gallons of water, consuming {water_per_day} gallons per day, water will last {water_days} days")
print(f"With {food_supply} pounds of food, consuming {food_per_day} pounds per day, food will last {food_days} days")
  1. 添加代码以演示在条件语句中使用变量:
## Using variables for decision making
print("\nDecision Making with Variables:")

## Check which supply will run out first
if water_days < food_days:
    limiting_factor = "Water"
    limiting_days = water_days
else:
    limiting_factor = "Food"
    limiting_days = food_days

print(f"{limiting_factor} will run out first, after {limiting_days} days")

## Check if supplies are sufficient for a 10-day journey
journey_days = 10
sufficient_supplies = water_days >= journey_days and food_days >= journey_days and ammunition >= 20

print(f"Planning a {journey_days}-day journey.")
print(f"Do we have sufficient supplies? {sufficient_supplies}")

## Provide specific supply status
if water_days < journey_days:
    print(f"Warning: Water will only last {water_days:.1f} days.")
if food_days < journey_days:
    print(f"Warning: Food will only last {food_days:.1f} days.")
if ammunition < 20:
    print(f"Warning: Only {ammunition} rounds of ammunition available.")
  1. 运行你的脚本:
python3 /home/labex/project/variables.py

你应该会看到类似于以下的输出:

...previous output...

Variables in Expressions:
With 100 gallons of water, consuming 4 gallons per day, water will last 25.0 days
With 50 pounds of food, consuming 2.5 pounds per day, food will last 20.0 days

Decision Making with Variables:
Food will run out first, after 20.0 days
Planning a 10-day journey.
Do we have sufficient supplies? True

这展示了你如何在数学计算中使用变量,以及如何根据变量的值做出决策。注意我们如何使用比较运算符 (<, >=) 和逻辑运算符 (and) 来创建条件。

格式化语法 {water_days:.1f} 指定浮点数应显示一位小数。

总结

在本次实验中,你学习了 Python 变量和数据类型的基本概念。你创建并使用了不同类型的变量,包括:

  • 整数(Integer):用于表示整数
  • 浮点数(Float):用于表示小数
  • 字符串(String):用于表示文本数据
  • 布尔值(Boolean):用于表示真/假值

你还学习了如何:

  • 使用 type() 函数检查变量的类型
  • 使用 int()float()str() 等函数进行不同数据类型之间的转换
  • 在表达式和计算中使用变量
  • 使用条件语句根据变量的值做出决策

这些概念构成了 Python 编程的基础。变量使你能够存储和操作数据,而了解不同的数据类型有助于你在不同的场景中选择合适的类型。在你继续学习 Python 的过程中,你将基于这些基础知识创建更复杂、更强大的程序。