Python入门:欢迎来到Python类型容器工厂- 数据类型

最新案例动态,请查阅Python入门:欢迎来到Python类型容器工厂- 数据类型。小伙伴们快来领取华为开发者空间进行实操吧!

1 概述

1.1 背景介绍

在Python中,数据类型是非常重要的概念,它决定了数据的存储方式和可进行的操作,主要有数字类型、布尔类型、字符串类型、列表类型、元组类型、集合类型和字典类型这几种数据类型。

通过本案例可以帮助我们掌握快速Python编程语言各种数据类型的使用。

1.2 适用对象

  • 个人开发者
  • 高校学生

1.3 案例时间

本案例总时长预计30分钟。

1.4 案例流程

26d5fb2d798986ca6b139b2ab8a97011.png

说明:

① 用户开通开发者空间,进入云主机,打开CodeArts IDE for Python创建工程;
② 在CodeArts IDE for Python中编写代码,学习数据类型,完成工厂管理实践。

1.5 资源总览

本案例预计花费总计0元。

资源名称规格单价(元)时长(分钟)
华为开发者空间-云主机鲲鹏通用计算增强型 kc2 | 4vCPUs | 8G | Ubuntu免费30

2 准备开发环境

2.1 配置云主机

参考“10分钟玩转云主机” 案例介绍中“2.2 申请云主机”章节内容完成华为开发者空间云主机申请与配置,配置云主机建议:“CPU架构”选择“X86”,“操作系统”选择“Ubuntu”。

4656a3e3084e92122bca59160a0555fc.PNG

然后点击“进入桌面”进入云主机。

a60aef99273b7a40b7cef2f2348a3bf0.PNG

2.2 使用CodeArts IDE创建工程

参考“初识云主机:CodeArts IDE入门”案例介绍“3.1 新建工程”章节新建工程。

新建的工程包含如下三个目录文件部分:

目录文件说明
.artsCodeArts的配置文件
venv虚拟环境
main.py默认生成的入口文件

add22b386dea30246a181ae5dd690b63.png

3 Python数据类型的使用

3.1 代码练习

下面我们主要围绕Python中数字类型、布尔类型、字符串类型、元组类型、列表类型、集合类型、字典类型这些常用数据类型进行讲解和练习。

3.1.1 数字类型
  1. 整数:用于表示没有小数部分的数值,可正可负,Python中的整数大小仅受限于内存。部分常用方法和函数:
  • abs():返回整数的绝对值。
  • divmod():返回两个数的商和余数。
  • pow():计算幂次方。
  1. 浮点数:用于表示带有小数部分的数值。常用方法和函数:
  • is_integer():用于判断浮点数是否为整数。
  • round():用于对浮点数进行四舍五入。
  1. 复数:由实部和虚部组成,形式为a + bj。常用方法和函数:
  • conjugate():用于返回复数的共轭复数。
  • real:获取复数的实部。
  • imag:获取复数的虚部。
  • complex():用于创建复数。
  • abs():返回复数的模。
# 数字类型 - 整数
print("整数实验:")
int_num = 10
print(f"原始整数: {int_num}")
print(f"加法运算: {int_num + 5}")
print(f"abs 函数: {abs(-int_num)}")
print(f"divmod 函数: {divmod(int_num, 3)}")
print(f"pow 函数: {pow(int_num, 2)}")

# 数字类型 - 浮点数
import math
print("\n浮点数实验:")
float_num = 3.14
print(f"原始浮点数: {float_num}")
print(f"加法运算: {float_num + 2.5}")
print(f"is_integer 方法: {float_num.is_integer()}")
print(f"round 函数: {round(float_num, 1)}")

# 数字类型 - 复数
print("\n复数实验:")
complex_num = 3 + 4j
print(f"原始复数: {complex_num}")
print(f"加法运算: {complex_num + (1 + 2j)}")
print(f"conjugate 方法: {complex_num.conjugate()}")
print(f"real 属性: {complex_num.real}")
print(f"imag 属性: {complex_num.imag}")
print(f"complex 函数: {complex(5, 6)}")
print(f"abs 函数: {abs(complex_num)}")
3.1.2 布尔类型

布尔类型只有两个值:True 和 False,常用于逻辑判断。部分常用方法和函数:

  • bool():将其他类型转换为布尔类型。
  • all():判断可迭代对象中的所有元素是否都为 True。
  • any():判断可迭代对象中是否至少有一个元素为 True。
    代码示例:
# 布尔类型
print("\n布尔类型实验:")
bool_example = True
print(f"原始布尔值: {bool_example}")
print(f"逻辑与运算: {bool_example and False}")
print(f"bool 函数: {bool(0)}")
print(f"all 函数: {all([True, True])}")
print(f"any 函数: {any([False, True])}")
3.1.3 字符串类型

字符串是由零个或多个字符组成的不可变序列,可用单引号、双引号或三引号表示。部分常用方法和函数:

  • upper():将字符串转换为大写。
  • lower():将字符串转换为小写。
  • strip():去除字符串首尾的指定字符,默认去除空格。
  • len():返回字符串的长度。
  • str():将其他类型转换为字符串。
  • format():格式化字符串。
# 字符串类型
print("\n字符串实验:")
str_example = "  hello,world  "
print(f"原始字符串: {str_example}")
print(f"拼接运算: {str_example + '!'}")
print(f"upper 方法: {str_example.upper()}")
print(f"lower 方法: {str_example.lower()}")
print(f"strip 方法: {str_example.strip()}")
print(f"len 函数: {len(str_example)}")
print(f"str 函数: {str(123)}")
print(f"format 函数: {'{} + {} = {}'.format(1, 2, 3)}")
3.1.4 列表类型

列表是可变的、有序的序列,可以包含不同类型的元素,用方括号表示。部分常用方法和函数:

  • append(x):在列表末尾添加元素 x。

  • pop([i]):移除并返回列表中索引为 i 的元素,默认移除最后一个元素。

  • sort():对列表进行原地排序。

  • len():返回列表的长度。

  • sorted():返回一个新的排序后的列表,原列表不变。

  • reversed():返回一个反向迭代器,反转列表。

    代码示例:

# 列表类型
print("\n列表实验:")
list_example = [3, 1, 2]
print(f"原始列表: {list_example}")
print(f"拼接运算: {list_example + [4, 5]}")
list_example.append(4)
print(f"append 方法: {list_example}")
popped = list_example.pop(1)
print(f"pop 方法: {popped}, {list_example}")
list_example.sort()
print(f"sort 方法: {list_example}")
print(f"len 函数: {len(list_example)}")
print(f"sorted 函数: {sorted(list_example)}")
print(f"reversed 函数: {list(reversed(list_example))}")
3.1.5 元组类型

元组是不可变的、有序的序列,用圆括号表示。部分常用方法和函数:

  • count(x):统计元素 x 在元组中出现的次数。

  • index(x):返回元素 x 在元组中第一次出现的索引。

  • len():返回元组的长度。

  • max():返回元组中的最大值。

  • min():返回元组中的最小值。

    代码示例:

# 元组类型
print("\n元组实验:")
tuple_example = (1, 2, 2, 3)
print(f"原始元组: {tuple_example}")
print(f"拼接运算: {tuple_example + (4, 5)}")
print(f"count 方法: {tuple_example.count(2)}")
print(f"index 方法: {tuple_example.index(2)}")
print(f"len 函数: {len(tuple_example)}")
print(f"max 函数: {max(tuple_example)}")
print(f"min 函数: {min(tuple_example)}")
3.1.6 集合类型

集合是无序的、唯一的数据类型,用花括号表示(空集合用 set())。部分常用方法和函数:

  • add(x):向集合中添加元素 x。
  • remove(x):移除集合中的元素 x,若元素不存在抛出 KeyError 异常。
  • pop():移除并返回集合中的任意一个元素,若集合为空抛出 KeyError 异常。
  • len():返回集合的元素个数。
  • sorted():返回一个新的排序后的列表,原集合不变。
  • any():判断集合中是否至少有一个元素为 True。
    代码示例:
# 集合类型
print("\n集合实验:")
set_example1 = {1, 2}
set_example2 = {2, 3}
print(f"原始集合 1: {set_example1}, 原始集合 2: {set_example2}")
print(f"并集运算: {set_example1 | set_example2}")
set_example1.add(3)
print(f"add 方法: {set_example1}")
set_example1.remove(2)
print(f"remove 方法: {set_example1}")
popped_element = set_example1.pop()
print(f"pop 方法: {popped_element}, {set_example1}")
print(f"len 函数: {len(set_example1)}")
print(f"sorted 函数: {sorted(set_example1)}")
print(f"any 函数: {any(set_example1)}")
3.1.7 字典类型

字典是无序的键值对集合,用花括号表示,键必须是不可变类型。部分常用方法和函数:

  • get(key, default=None):根据键 key 获取对应的值,若键不存在返回 default。

  • setdefault(key, default=None):如果键 key 存在,返回对应的值;若不存在,插入键 key 并设置值为 default,返回 default。

  • pop(key, default=None):移除并返回指定键的值,若键不存在,返回 default(默认会抛出 KeyError 异常)。

  • update(other):用 other 字典更新当前字典,若有相同键则覆盖。

  • len():返回字典中键值对的数量。

  • sorted():对字典的键进行排序,返回一个新的排序后的键列表。

    代码示例:

# 字典类型
print("\n字典实验:")
dict_example = {"name": "John", "age": 25}
print(f"原始字典: {dict_example}")
print(f"get 方法: {dict_example.get('height', 0)}")
print(f"setdefault 方法: {dict_example.setdefault('weight', 70)}")
print(f"更新后的字典: {dict_example}")
popped_value = dict_example.pop("age")
print(f"pop 方法: {popped_value}, {dict_example}")
dict_example.update({"new_key": "new_value"})
print(f"update 方法: {dict_example}")
print(f"len 函数: {len(dict_example)}")
print(f"sorted 函数: {sorted(dict_example)}")

3.2 工厂管理系统

结合上面的知识点,来看一个工厂管理系统小程序。完整代码参考如下(注意:复制使用请保持缩进相同)。

import math

# 工厂的基本信息
factory_name = "卓越工厂"
factory_location = (30.2741, 120.1551)
has_customization = True
daily_budget = 8000
# 容器类型
container_types = ["塑料容器", "金属容器", "木质容器"]
# 订单信息
# 今日线上和线下订单数量(实部为线下,虚部为线上)
order_count = complex(30, 40)
total_orders = int(order_count.real + order_count.imag)
# 客户信息
long_term_customers = {"客户A", "客户B", "客户C"}
new_customers = ["客户D", "客户E"]
# 员工信息
employees = [
    {"name": "张三", "position": "生产工人", "shift": "早班"},
    {"name": "李四", "position": "质检员", "shift": "中班"},
    {"name": "王五", "position": "物流员", "shift": "晚班"}
]
# 原材料供应商信息
material_suppliers = {
    "供应商X": ["塑料颗粒", "塑料添加剂"],
    "供应商Y": ["钢材", "铝材"],
    "供应商Z": ["木材", "油漆"]
}
# 成本信息
average_cost = 30.5
total_cost = average_cost * total_orders
# 利润计算(假设每个容器售价为 50 元)
total_revenue = total_orders * 50
profit = total_revenue - total_cost

def handle_integer():
    print("当前涉及的整数数据有每日生产预算:", daily_budget)
    new_budget = int(input("请输入一个新的每日生产预算(整数):"))
    print("新的每日生产预算减少 1000 后为:", new_budget - 1000)
    print("新的每日生产预算取绝对值为:", abs(new_budget))
    print("新的每日生产预算的二次幂为:", pow(new_budget,2))

def handle_float():
    print("当前涉及的浮点数数据有每个容器的平均成本:", average_cost)
    new_cost = float(input("请输入一个新的每个容器平均成本(浮点数):"))
    print("新的每个容器平均成本是否为整数:", new_cost.is_integer())
    print("新的每个容器平均成本四舍五入后为:", round(new_cost))

def handle_complex():
    print("当前涉及的复数数据有今日订单数量(实部为线下,虚部为线上):", order_count)
    real_part = float(input("请输入新订单数量的实部(线下数量):"))
    imag_part = float(input("请输入新订单数量的虚部(线上数量):"))
    new_order_count = complex(real_part, imag_part)
    print("新的订单数量的共轭复数为:", new_order_count.conjugate())
    print("新的订单数量的模为:", abs(new_order_count))
    print("新的订单数量的实部为:", new_order_count.real)

def handle_string():
    print("当前涉及的字符串数据有工厂名称:", factory_name)
    new_name = input("请输入一个新的工厂名称:")
    print("新的工厂名称大写后为:", new_name.upper())
    print("新的工厂名称去除首尾空格后为:", new_name.strip())
    print("新的工厂名称长度为:", len(new_name))

def handle_boolean():
    print("当前涉及的布尔数据有是否提供定制服务:", has_customization)
    new_customization = input("请输入是否提供定制服务(True/False):").lower() == 'true'
    print("新的是否提供定制服务取反后为:", not new_customization)
    print("新的是否提供定制服务与 True 进行逻辑与运算结果为:", new_customization and True)
    print("新的是否提供定制服务与 False 进行逻辑或运算结果为:", new_customization or False)

def handle_list():
    print("当前涉及的列表数据有新客户列表:", new_customers)
    new_customer = input("请输入一个新的客户名称:")
    new_customers.append(new_customer)
    print("添加新客户后的列表为:", new_customers)
    popped_customer = new_customers.pop(0)
    print("移除第一个客户后的列表为:", new_customers)
    print("移除的客户是:", popped_customer)
    print("排序后的新客户列表为:", sorted(new_customers))

def handle_tuple():
    print("当前涉及的元组数据有工厂位置:", factory_location)
    new_lat = float(input("请输入新的纬度:"))
    new_lon = float(input("请输入新的经度:"))
    new_location = (new_lat, new_lon)
    print("新的工厂位置与原位置拼接后为:", factory_location + new_location)
    print("新的工厂位置中纬度出现的次数为:", new_location.count(new_lat))
    print("新的工厂位置中经度的索引为:", new_location.index(new_lon))

def handle_set():
    print("当前涉及的集合数据有长期合作客户集合:", long_term_customers)
    new_customer = input("请输入一个新的长期合作客户名称:")
    long_term_customers.add(new_customer)
    print("添加新客户后的集合为:", long_term_customers)
    removed_customer = input("请输入要移除的长期合作客户名称:")
    if removed_customer in long_term_customers:
        long_term_customers.remove(removed_customer)
    else:
        print("该客户不在集合中,无法移除。")
    print("移除客户后的集合为:", long_term_customers)
    print("集合排序后的列表为:", sorted(long_term_customers))

def handle_dict():
    print("当前涉及的字典数据有原材料供应商信息:", material_suppliers)
    new_supplier = input("请输入新的供应商名称:")
    new_materials = input("请输入新供应商供应的材料(用逗号分隔):").split(',')
    material_suppliers[new_supplier] = new_materials
    print("添加新供应商后的字典为:", material_suppliers)
    removed_supplier = input("请输入要移除的供应商名称:")
    if removed_supplier in material_suppliers:
        del material_suppliers[removed_supplier]
    else:
        print("该供应商不在字典中,无法移除。")
    print("移除供应商后的字典为:", material_suppliers)
    print("字典的键排序后的列表为:", sorted(material_suppliers.keys()))

data_type_handlers = {
    1: handle_integer,
    2: handle_float,
    3: handle_complex,
    4: handle_string,
    5: handle_boolean,
    6: handle_list,
    7: handle_tuple,
    8: handle_set,
    9: handle_dict
}

while True:
    print("\n请选择要操作的数据类型:")
    print("1. 整数")
    print("2. 浮点数")
    print("3. 复数")
    print("4. 字符串")
    print("5. 布尔值")
    print("6. 列表")
    print("7. 元组")
    print("8. 集合")
    print("9. 字典")
    print("输入 0 退出程序。")
    try:
        choice = int(input())
        if choice == 0:
            break
        elif choice in data_type_handlers:
            data_type_handlers[choice]()
        else:
            print("输入无效,请输入 0 - 9 之间的数字。")
    except ValueError:
        print("输入无效,请输入有效的整数。") 

同时,可以参考上面代码进行扩展练习,例如:

1. 在handle_list()中使用reversed()将客户列表反转。
2. 在handle_dict ()中使用update更新供应商信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值