简介
在这个实验中,你将学习 Python 变量和数据类型的基本概念。变量是编程中必不可少的构建块,它允许你在代码中存储、访问和操作数据。理解不同的数据类型对于编写有效的 Python 程序至关重要。
你将创建各种变量,探索 Python 中可用的不同数据类型,执行类型转换,并学习如何在表达式中使用变量。这些技能是 Python 编程的基础,也是开发更复杂应用程序所必需的。
在本实验结束时,你将能够自如地在 Python 中创建和使用不同数据类型的变量。
在这个实验中,你将学习 Python 变量和数据类型的基本概念。变量是编程中必不可少的构建块,它允许你在代码中存储、访问和操作数据。理解不同的数据类型对于编写有效的 Python 程序至关重要。
你将创建各种变量,探索 Python 中可用的不同数据类型,执行类型转换,并学习如何在表达式中使用变量。这些技能是 Python 编程的基础,也是开发更复杂应用程序所必需的。
在本实验结束时,你将能够自如地在 Python 中创建和使用不同数据类型的变量。
在这一步中,你将学习如何在 Python 中创建和使用变量。变量是用于存储数据值的容器,并且为它们赋予有意义的名称,以便在代码中更方便地引用。
让我们从创建一个新的 Python 文件并定义一些基本变量开始:
在 WebIDE 中打开文件 /home/labex/project/variables.py
。
添加以下代码来定义三个变量:
## 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 中,你可以通过指定一个名称,后跟等号 (=
),然后是你要赋给它的值来创建一个变量。
## Displaying variable values
print("Water supply:", water_supply)
print("Food supply:", food_supply)
print("Ammunition:", ammunition)
python3 /home/labex/project/variables.py
你应该会看到以下输出:
Water supply: 100
Food supply: 50
Ammunition: 40
恭喜你。你已经创建了你的第一个 Python 变量并显示了它们的值。这些变量存储了你的程序可以访问和操作的信息。
Python 有几种用于对不同类型的数据进行分类的数据类型。在这一步中,你将了解两种数值数据类型:整数(integer)和浮点数(float)。
在 WebIDE 中打开文件 /home/labex/project/variables.py
。
在文件中添加以下代码,以定义具有不同数值数据类型的变量:
## Numeric data types
integer_value = 42 ## Integer (whole number)
float_value = 3.14159 ## Float (decimal number)
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))
## 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}")
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)。让我们来探索这些类型:
在 WebIDE 中打开文件 /home/labex/project/variables.py
。
添加以下代码来定义字符串和布尔变量:
## 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
## 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))
## String operations
full_location = camp_name + " in " + location
print("\nFull location:", full_location)
## String repetition
border = "-" * 20
print(border)
print("Camp Information")
print(border)
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
--------------------
注意字符串如何使用 +
运算符进行拼接,以及如何使用 *
运算符进行重复。布尔值对于表示条件和控制程序流程非常有用。
有时你需要将值从一种数据类型转换为另一种数据类型,或者检查变量的数据类型。这被称为类型转换(或类型强制转换)。让我们来探讨这个概念:
在 WebIDE 中打开文件 /home/labex/project/variables.py
。
添加代码来演示类型转换:
## 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)}")
## 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)}")
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()
函数用于检查变量是否为指定类型当你需要处理用户输入或处理来自不同来源的数据时,这些转换函数非常有用。
当变量用于表达式和决策结构时,它们会变得非常强大。让我们来探索如何在计算和条件语句中使用变量:
在 WebIDE 中打开文件 /home/labex/project/variables.py
。
添加代码以演示在计算中使用变量:
## 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")
## 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.")
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 变量和数据类型的基本概念。你创建并使用了不同类型的变量,包括:
你还学习了如何:
type()
函数检查变量的类型int()
、float()
和 str()
等函数进行不同数据类型之间的转换这些概念构成了 Python 编程的基础。变量使你能够存储和操作数据,而了解不同的数据类型有助于你在不同的场景中选择合适的类型。在你继续学习 Python 的过程中,你将基于这些基础知识创建更复杂、更强大的程序。