Python变量与数据类型
一、变量基础
- 什么是变量?
变量是存储数据的容器,可以理解为数据的”标签”或”名字”。在Python中,变量不需要提前声明类型,赋值时会自动确定类型。
- 变量命名规则
• 只能包含字母、数字和下划线(A-z, 0-9, _)
• 不能以数字开头
• 不能使用Python关键字(如if, for, while等)
• 区分大小写(age和Age是不同的变量)
• 推荐使用描述性名称(如user_name而非un)
- 变量赋值
Python使用等号(=)进行赋值:
1 2 3 4 5 6 7 8 9 10 11 12 13
| counter = 100 name = "张三"
x = y = z = 1
a, b, c = 1, 2, "hello"
a = 1 a = "Hel"
|
- 变量类型检查
使用type()
函数查看变量类型:
1 2
| age = 25 print(type(age))
|
二、基本数据类型
Python有几种内置的基本数据类型:
- 数字类型
整数(int)
浮点数(float)
1 2
| pi = 3.14159 temperature = -10.5
|
复数(complex)
数字运算
1 2 3 4 5 6 7 8 9 10 11 12
| print(10 + 3) print(10 - 3) print(10 * 3) print(10 / 3) print(10 // 3) print(10 % 3) print(10 ** 3)
int_num = int(3.14) float_num = float(5)
|
- 布尔类型(bool)
表示真(True)或假(False),常用于条件判断:
1 2 3 4 5 6 7
| is_active = True has_permission = False
print(True and False) print(True or False) print(not True)
|
- 字符串(str)
字符串是不可变的字符序列,可以用单引号或双引号创建:
基本操作
1 2 3 4 5 6 7 8 9 10 11
| name = "Alice" greeting = 'Hello'
full_greeting = greeting + ", " + name
stars = "*" * 10
print(len(name))
|
字符串索引和切片
1 2 3 4 5 6 7
| s = "Python"
print(s[0]) print(s[-1]) print(s[2:5]) print(s[:3]) print(s[3:])
|
常用字符串方法
1 2 3 4 5 6 7 8 9
| text = " Hello, World! "
print(text.strip()) print(text.lower()) print(text.upper()) print(text.replace("H", "J")) print(text.split(",")) print("Python".startswith("Py")) print("123".isdigit())
|
- None类型
表示空值或没有值:
三、复合数据类型
- 列表(list)
有序、可变的元素集合:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| fruits = ["apple", "banana", "cherry"] numbers = [1, 2, 3, 4, 5]
fruits.append("orange") fruits[1] = "blueberry" del fruits[0] print(len(fruits))
print(numbers[1:4])
nums = [3, 1, 4, 1, 5] nums.sort() nums.reverse() print(nums.count(1))
|
- 元组(tuple)
有序、不可变的元素集合:
1 2 3 4 5 6 7 8 9
| coordinates = (10, 20) colors = ("red", "green", "blue")
x, y = coordinates print(x)
|
- 字典(dict)
键值对的集合,无序、可变:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| person = { "name": "Alice", "age": 25, "city": "New York" }
print(person["name"])
person["email"] = "alice@example.com" person["age"] = 26
del person["city"]
print(person.keys()) print(person.values()) print(person.items())
|
- 集合(set)
无序、不重复的元素集合:
1 2 3 4 5 6 7 8 9
| unique_numbers = {1, 2, 3, 3, 4}
a = {1, 2, 3} b = {3, 4, 5}
print(a | b) print(a & b) print(a - b)
|
四、类型转换
Python提供了多种类型转换函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| print(int("123")) print(int(3.14))
print(float("3.14")) print(float(5))
print(str(123)) print(str(True))
print(bool(1)) print(bool(0)) print(bool("")) print(bool("Hi"))
print(list("hello")) print(list({1, 2, 3}))
|
五、变量作用域
Python中的变量作用域分为:
- 局部变量:在函数内部定义,只在函数内有效
- 全局变量:在函数外部定义,整个程序都可访问
1 2 3 4 5 6 7 8 9
| global_var = "我是全局变量"
def test_scope(): local_var = "我是局部变量" print(global_var) print(local_var)
test_scope()
|
要修改全局变量,需要使用global
关键字:
1 2 3 4 5 6 7 8
| count = 0
def increment(): global count count += 1
increment() print(count)
|
六、提示
- 使用描述性变量名:
user_age
比ua
更易理解
- 避免使用全局变量:除非必要,否则优先使用局部变量
- 注意可变与不可变类型:列表可变,元组不可变
- 合理选择数据类型:根据需求选择最适合的数据结构
- 使用类型注解(Python 3.6+):提高代码可读性
1 2
| def greet(name: str) -> str: return f"Hello, {name}"
|
七、高级特性与陷阱
可变与不可变类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| 不可变类型示例 s = "hello" try: s[0] = "H" except TypeError as e: print(e)
可变类型示例 lst = [1, 2, 3] lst[0] = 100 print(lst)
浅拷贝与深拷贝 import copy original = [[1, 2], [3, 4]] shallow = copy.copy(original) deep = copy.deepcopy(original)
|
浮点数精度问题解决方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 问题重现 print(0.1 + 0.2)
解决方案1:四舍五入 print(round(0.1 + 0.2, 1))
解决方案2:decimal模块 from decimal import Decimal, getcontext getcontext().prec = 6 print(Decimal('0.1') + Decimal('0.2'))
解决方案3:fractions模块 from fractions import Fraction print(Fraction(1, 10) + Fraction(2, 10))
|
可变默认参数
1 2 3 4 5 6 7
| def add_item(item, lst=[]): lst.append(item) return lst
print(add_item(1)) print(add_item(2))
|