Python3入门指南Python语言的特点和实际应用Python3环境搭建配置VSCode进行Python开发Python基础语法Python变量与数据类型Python数据类型转换Python解释器使用Python注释使用Python运算符Python数字类型Python字符串操作Python列表操作Python元组使用Python字典使用Python集合使用Python条件控制详解Python循环语句详解Python编程入门实践Python推导式详解Python迭代器和生成器Python with语句详解Python函数详解Python lambda(匿名函数)Python装饰器Python数据结构Python模块和包使用Python中__name__和__main__的用法Python输入输出:从基础到文件操作Python文件操作Python OS模块使用Python错误和异常处理Python面向对象编程Python命名空间和作用域Python虚拟环境:venv详细教程Python类型注解Python标准库常用模块Python正则表达式Python CGI编程Python MySQL(mysql-connector驱动)Python MySQL(PyMySQL驱动)Python网络编程Python发送邮件Python多线程编程Python XML解析Python JSON解析Python日期和时间处理Python操作MongoDBPython urllib库使用Python uWSGI 安装与配置Python pip包管理工具Python operator模块Python math模块Python requests模块HTTP请求Python random模块Python OpenAI库Python AI绘画制作Python statistics模块Python hashlib模块:哈希加密Python量化交易Python pyecharts数据可视化Python Selenium网页自动化Python BeautifulSoup网页数据提取Python Scrapy爬虫框架Python Markdown转HTMLPython sys模块Python Pickle模块:数据存储Python subprocess模块Python queue队列模块Python StringIO内存文件操作Python logging日志记录Python datetime日期时间处理Python re正则表达式Python csv表格数据处理Python threading 多线程编程Python asyncio 异步编程Python PyQt 图形界面开发Python 应用方向和常用库框架

Python变量与数据类型

Python编程中,变量和数据类型是最基础的概念。理解这些知识对后续学习很重要。


变量的基本使用

Python中的变量不需要提前声明。当你给变量赋值时,变量就自动创建了。

使用等号(=)给变量赋值,左边是变量名,右边是值:

counter = 100          # 整数变量
price = 29.99          # 小数变量
name = "张三"          # 字符串变量
is_student = True      # 布尔变量

print(counter)
print(price)
print(name)
print(is_student)

运行结果:

100
29.99
张三
True


多个变量赋值

Python可以同时给多个变量赋值:

# 三个变量都赋值为1
x = y = z = 1

# 分别赋值
a, b, c = 10, 20, "你好"

print(x, y, z)  # 输出:1 1 1
print(a, b, c)  # 输出:10 20 你好


查看数据类型

使用type()函数可以查看变量的类型:

age = 25
height = 175.5
username = "李四"
is_active = False

print(type(age))       # <class 'int'>
print(type(height))    # <class 'float'>
print(type(username))  # <class 'str'>
print(type(is_active)) # <class 'bool'>


Python的数据类型

Python有几种基本数据类型:

  • 数字:整数、小数、复数、布尔值

  • 字符串:文本信息

  • 列表:有序的可变序列

  • 元组:有序的不可变序列

  • 集合:无序的唯一元素集合

  • 字典:键值对集合

其中,数字、字符串、元组是不可变类型,列表、集合、字典是可变类型。


数字类型

Python支持多种数字类型:

# 整数
age = 25

# 浮点数(小数)
weight = 65.5

# 布尔值
is_pass = True

# 复数
complex_num = 3 + 4j

print(age, weight, is_pass, complex_num)


数字运算

基本的数学运算:

a = 10
b = 3

print(a + b)   # 加法:13
print(a - b)   # 减法:7
print(a * b)   # 乘法:30
print(a / b)   # 除法:3.333...
print(a // b)  # 整除:3
print(a % b)   # 取余:1
print(a ** b)  # 乘方:1000


字符串

字符串用于表示文本:

# 创建字符串
str1 = 'Hello'
str2 = "世界"
str3 = """多行
字符串"""

# 字符串操作
text = "Python编程"
print(text[0])      # 输出:P
print(text[0:6])    # 输出:Python
print(text + "学习") # 输出:Python编程学习
print(text * 2)     # 输出:Python编程Python编程

# 原始字符串(不转义)
print(r'hello\nworld')  # 输出:hello\nworld


布尔类型

布尔值只有True和False两种:

# 布尔值
is_rain = True
is_sunny = False

# 布尔运算
print(True and False)  # 与运算:False
print(True or False)   # 或运算:True
print(not True)        # 非运算:False

# 比较运算
print(5 > 3)   # True
print(2 == 2)  # True
print(7 < 4)   # False

# 类型转换
print(bool(0))     # False
print(bool(10))    # True
print(bool(""))    # False
print(bool("Hi"))  # True


列表

列表是有序的元素集合,可以修改:

# 创建列表
fruits = ['苹果', '香蕉', '橙子']
numbers = [1, 2, 3, 4, 5]
mixed = [1, 'hello', 3.14, True]

print(fruits[0])      # 苹果
print(fruits[1:3])    # ['香蕉', '橙子']

# 修改列表
fruits[0] = '梨'
fruits.append('葡萄')  # 添加元素
print(fruits)         # ['梨', '香蕉', '橙子', '葡萄']


元组

元组类似列表,但不能修改:

# 创建元组
colors = ('红色', '绿色', '蓝色')
point = (10, 20)

print(colors[0])   # 红色
print(colors[1:3]) # ('绿色', '蓝色')

# 元组不能修改
# colors[0] = '黄色'  # 这行会报错

# 单个元素的元组
single = (5,)  # 注意要有逗号


集合

集合是无序的唯一元素集合:

# 创建集合
numbers = {1, 2, 3, 3, 4, 4}
fruits = {'苹果', '香蕉', '苹果'}

print(numbers)  # {1, 2, 3, 4}(自动去重)
print(fruits)   # {'苹果', '香蕉'}

# 集合运算
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

print(set1 - set2)  # 差集:{1, 2}
print(set1 | set2)  # 并集:{1, 2, 3, 4, 5, 6}
print(set1 & set2)  # 交集:{3, 4}


字典

字典是键值对的集合:

# 创建字典
student = {
    'name': '王五',
    'age': 20,
    'score': 95.5
}

# 访问字典
print(student['name'])  # 王五
print(student['age'])   # 20

# 修改字典
student['age'] = 21
student['class'] = '三班'  # 添加新键值对

print(student.keys())   # 所有键
print(student.values()) # 所有值


数据类型转换

不同类型之间可以相互转换:

# 字符串转数字
num_str = "123"
num_int = int(num_str)

# 数字转字符串
num = 456
num_str = str(num)

# 列表转元组
my_list = [1, 2, 3]
my_tuple = tuple(my_list)

# 元组转列表
my_tuple = (4, 5, 6)
my_list = list(my_tuple)

print(type(num_int))   # <class 'int'>
print(type(num_str))   # <class 'str'>
print(type(my_tuple))  # <class 'tuple'>


使用建议

  1. 变量名要有意义,比如用age表示年龄,不要用a、b这样的名字

  2. 字符串用单引号或双引号都可以,但要保持一致

  3. 列表适合存储会变化的数据序列

  4. 元组适合存储不会变化的数据序列

  5. 集合适合去重和集合运算

  6. 字典适合存储有对应关系的数据

学习数据类型时,要多动手实践。可以在Python交互环境中尝试各种操作,观察结果。理解这些基础概念后,你就能写出更有用的Python程序了。记住,编程是实践技能,多写代码才能进步。

本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!

链接: https://fly63.com/course/36_2077

目录选择