Python变量与数据类型全解析(最新整理)

作者:

文章目录
  • 变量是数据的载体,简单的说就是一块用来保存数据的内存空间,变量的值可以被读取和修改,这是所有运算和控制的基础。
  • 目录
    • 1、变量
      • 变量命名规范
    • Python数据类型
      • 1、基本数据类型
        • 数值类型(Number):
        • 布尔类型(bool)
        • 字符串(str)
      • 2、复合数据类型
        • (1) 列表(list)
        • (2) 元组(tuple)
        • (3) 集合(set)
        • (4) 字典(dict)

    变量是数据的载体,简单的说就是一块用来保存数据的内存空间,变量的值可以被读取和修改,这是所有运算和控制的基础。

    在 Python 中,变量命名需要遵循以下的规则和惯例。

    规则部分:

    规则1:变量名由字母、数字和下划线构成,数字不能开头。需要说明的是,这里说的字母指的是 Unicode 字符,Unicode 称为万国码,囊括了世界上大部分的文字系统,这也就意味着中文、日文、希腊字母等都可以作为变量名中的字符,但是一些特殊字符(如:!、@、#等)是不能出现在变量名中的。我们强烈建议大家把这里说的字母理解为尽可能只使用英文字母。

    规则2:Python 是大小写敏感的编程语言,简单的说就是大写的A和小写的a是两个不同的变量,这一条其实并不算规则,而是需要大家注意的地方。

    规则3:变量名不要跟 Python 的关键字重名,尽可能避开 Python 的保留字。这里的关键字是指在 Python 程序中有特殊含义的单词(如:is、if、else、for、while、True、False等),保留字主要指 Python 语言内置函数、内置模块等的名字(如:int、print、input、str、math、os等)。

    • int: 整数,如10-50
    • float: 浮点数,如3.14-0.0012.0
    • complex: 复数,如1+2j3-4j
    a = 10         # int
    b = 3.14       # float
    c = 1 + 2j     # complex
    print(a, b, c)

    整型(int):Python 中可以处理任意大小的整数,而且支持二进制(如0b100,换算成十进制是4)、八进制(如0o100,换算成十进制是64)、十进制(100)和十六进制(0x100,换算成十进制是256)的表示法。

    print(0b100)  # 二进制整数
    print(0o100)  # 八进制整数
    print(100)    # 十进制整数
    print(0x100)  # 十六进制整数

    浮点型(float):浮点数也就是小数,之所以称为浮点数,是因为按照科学记数法表示时,一个浮点数的小数点位置是可变的,浮点数除了数学写法(如123.456)之外还支持科学计数法(如1.23456e2

    print(123.456)    # 数学写法
    print(1.23456e2)  # 科学计数法

    复数(complex)是Python中的一种数字类型,用于表示数学中的复数。复数由实数部分和虚数部分组成,

    a = 3 + 4j      # 复数 3+4i
    e = complex(2, 3)    # 2+3j
    f = complex(4)       # 4+0j
    g = complex('5+6j')  # 从字符串创建 5+6j
    print(a, e, f, g)

    布尔型(bool):布尔型只有TrueFalse两种值,要么是True,要么是False,可以用来表示现实世界中的“是”和“否”,命题的“真”和“假”,状况的“好”与“坏”,水平的“高”与“低”等等。如果一个变量的值只有两种状态,我们就可以使用布尔型。

    is_active = True
    is_admin = False
    print(is_active, is_admin)
    print(is_active and is_admin)

    字符串型(str):字符串是以单引号或双引号包裹起来的任意文本,比如'hello'"hello",使用反斜杠  转义特殊字符,三引号''' '''/""" """包围也是字符串

    s1 = 'hello'
    s2 = "world"
    s3 = '''多行
    字符串'''
    print(s1, s2, s3)

    特点:

    • 有序的可变序列
    • 用方括号[]表示
    • 可以包含不同类型的元素
    • 允许重复元素
    # 创建列表
    fruits = ['apple', 'banana', 'cherry']
    numbers = [1, 2, 3, 4, 5]
    mixed = [1, 'a', True, 3.14]
    # 访问元素
    print(fruits[0])    # 'apple' (正向索引从0开始)
    print(fruits[-1])   # 'cherry' (负索引表示从后往前)
    # 修改元素
    fruits[1] = 'blueberry'
    print(fruits)       # ['apple', 'blueberry', 'cherry']
    # 切片操作
    print(numbers[1:3]) # [2, 3] (获取索引1到2的元素)
    print(numbers[:2])  # [1, 2] (从开始到索引1)
    print(numbers[2:])  # [3, 4, 5] (从索引2到结束)
    # 常用方法
    fruits.append('orange')      # 末尾添加
    fruits.insert(1, 'pear')     # 指定位置插入
    fruits.remove('apple')       # 删除指定元素
    popped = fruits.pop(2)       # 删除并返回指定索引元素
    fruits.sort()                # 排序(原地修改)
    sorted_fruits = sorted(fruits)  # 返回新排序列表

    实际案例:学生成绩管理:

    # 初始化学生成绩列表
    grades = [85, 90, 78, 92, 88]
    # 添加新成绩
    grades.append(95)
    print("添加后:", grades)  # [85, 90, 78, 92, 88, 95]
    # 计算平均分
    average = sum(grades) / len(grades)
    print("平均分:", average)
    # 找出最高分和最低分
    print("最高分:", max(grades))
    print("最低分:", min(grades))
    # 排序成绩
    grades.sort(reverse=True)
    print("降序排列:", grades)

    特点:

    • 有序的不可变序列
    • 用圆括号()表示
    • 可以包含不同类型的元素
    • 一旦创建不能修改
    # 创建元组
    colors = ('red', 'green', 'blue')
    coordinates = (10.5, 20.3)
    single_element = (42,)  # 注意逗号,区分(42)是整数
    # 访问元素
    print(colors[1])     # 'green'
    print(coordinates[0]) # 10.5
    # 切片操作
    print(colors[:2])    # ('red', 'green')
    # 元组解包
    x, y = coordinates
    print(f"x: {x}, y: {y}")  # x: 10.5, y: 20.3
    # 不可变性尝试(会报错)
    # colors[1] = 'yellow'  # TypeError
    # 元组连接
    new_tuple = colors + ('yellow', 'black')
    print(new_tuple)  # ('red', 'green', 'blue', 'yellow', 'black')

    实际案例:RGB颜色处理:

    # 定义一组RGB颜色
    color1 = (255, 0, 0)    # 红色
    color2 = (0, 255, 0)    # 绿色
    color3 = (0, 0, 255)    # 蓝色
    # 计算灰度值函数
    def calculate_grayscale(rgb):
        r, g, b = rgb
        return round(0.299 * r + 0.587 * g + 0.114 * b)
    # 计算各颜色的灰度值
    print(f"红色的灰度值: {calculate_grayscale(color1)}")
    print(f"绿色的灰度值: {calculate_grayscale(color2)}")
    print(f"蓝色的灰度值: {calculate_grayscale(color3)}")
    # 颜色混合函数
    def mix_colors(color_a, color_b, ratio=0.5):
        return tuple(round(a * ratio + b * (1 - ratio)) for a, b in zip(color_a, color_b))
    # 混合红色和蓝色
    purple = mix_colors(color1, color3)
    print(f"混合红色和蓝色得到: {purple}")  # (128, 0, 128)

    特点:

    • 无序的不重复元素集
    • 用花括号{}表示(但空集合必须用set())
    • 可变集合(set)和不可变集合(frozenset)两种
    • 支持数学集合运算
    # 创建集合
    unique_numbers = {1, 2, 3, 3, 4}  # 实际为{1, 2, 3, 4}
    letters = set('hello')             # {'h', 'e', 'l', 'o'}
    empty_set = set()                  # 空集合(不能用{},这是空字典)
    # 添加/删除元素
    unique_numbers.add(5)
    unique_numbers.remove(2)  # 如果元素不存在会报错
    unique_numbers.discard(10)  # 安全删除,不存在也不报错
    popped = unique_numbers.pop()  # 随机删除并返回一个元素
    # 集合运算
    a = {1, 2, 3}
    b = {2, 3, 4}
    print(a | b)  # 并集 {1, 2, 3, 4}
    print(a & b)  # 交集 {2, 3}
    print(a - b)  # 差集 {1}
    print(a ^ b)  # 对称差集 {1, 4}
    # 集合推导式
    squares = {x**2 for x in range(5)}
    print(squares)  # {0, 1, 4, 9, 16}

    实际案例:数据分析

    # 两个班级的学生
    class_a = {'Alice', 'Bob', 'Charlie', 'David'}
    class_b = {'Charlie', 'David', 'Eve', 'Frank'}
    # 找出同时在两个班级的学生
    both_classes = class_a & class_b
    print("同时在两个班级的学生:", both_classes)
    # 找出只在A班的学生
    only_a = class_a - class_b
    print("只在A班的学生:", only_a)
    # 所有不重复的学生
    all_students = class_a | class_b
    print("所有学生:", all_students)
    # 添加新学生
    class_a.add('Grace')
    print("更新后的A班:", class_a)
    # 检查学生是否存在
    print("Alice在A班吗?", 'Alice' in class_a)
    print("Eve在A班吗?", 'Eve' in class_a)

    特点:

    • 键值对集合
    • 用花括号{}表示,键值对用:分隔
    • 键必须是不可变类型,值可以是任意类型
    • 从Python 3.7开始保持插入顺序
    # 创建字典
    person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
    grades = {'math': 90, 'english': 85, 'history': 88}
    empty_dict = {}
    # 访问元素
    print(person['name'])  # 'Alice'
    print(grades.get('math', 0))  # 90 (get方法可设置默认值)
    # 添加/修改元素
    person['email'] = 'alice@example.com'  # 添加
    grades['math'] = 95  # 修改
    # 删除元素
    del person['city']
    popped_value = grades.pop('english')  # 删除并返回值
    # 常用方法
    print(person.keys())    # 所有键
    print(person.values())  # 所有值
    print(person.items())   # 所有键值对
    # 字典推导式
    squares = {x: x**2 for x in range(5)}
    print(squares)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

    实际案例:单词统计

    def word_count(text):
        """统计文本中单词出现次数"""
        word_counts = {}
        # 分割文本为单词(简单处理)
        words = text.lower().split()
        for word in words:
            # 去除标点符号(简单处理)
            word = word.strip(".,!?")
            # 更新计数
            if word in word_counts:
                word_counts[word] += 1
            else:
                word_counts[word] = 1
        return word_counts
    # 测试文本
    text = "Hello world! Hello Python. Python is great, isn't it? The world is big."
    # 统计单词
    counts = word_count(text)
    # 打印结果
    print("单词统计结果:")
    for word, count in sorted(counts.items()):
        print(f"{word}: {count}")
    # 找出出现最多的单词
    most_common = max(counts.items(), key=lambda item: item[1])
    print(f"n最常出现的单词是 '{most_common[0]}',出现了 {most_common[1]} 次")

    类型

    可变性

    有序性

    元素要求

    表示符号

    主要用途

    列表(list)

    可变

    有序

    []

    存储有序数据集合,可能修改

    元组(tuple)

    不可变

    有序

    ()

    存储不应修改的有序数据

    集合(set)

    可变

    无序

    必须可哈希

    {}

    存储唯一元素,快速成员检查

    字典(dict)

    可变

    有序(3.7+)

    键必须可哈希

    {key: value}

    存储键值对关联数据

    到此这篇关于Python变量与数据类型全解析的文章就介绍到这了,更多相关Python变量与数据类型内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

    您可能感兴趣的文章:

    • Python中的变量和数据类型使用方式
    • Python入门教程之变量与数据类型
    • Python变量和数据类型详解
    • 深入理解Python变量的数据类型和存储
    • Python3变量与基本数据类型用法实例分析
    • Python变量、数据类型、数据类型转换相关函数用法实例详解
    • Python变量和数据类型详解
    • 详细解析Python中的变量的数据类型
    • 详细解析Python当中的数据类型和变量
    • python基础教程之基本数据类型和变量声明介绍

    站内搜索