Python语法基础
原创...大约 13 分钟
摘要
本文用通俗易懂的方式介绍Python的基础语法,包括变量和数据类型的使用、各种运算符的应用、条件判断和循环控制,以及实用的列表推导式。通过大量实例帮助初学者快速掌握Python编程的核心语法。
1. 变量与数据类型
1.1 变量的使用
在Python中,变量就像是一个标签,用来给数据起个名字。
# 创建变量很简单,直接赋值就行
name = "小明"
age = 18
height = 1.75
is_student = True
print(f"姓名:{name},年龄:{age},身高:{height}m,是否学生:{is_student}")
小贴士
Python的变量名要遵循几个规则:
- 只能包含字母、数字和下划线
- 不能以数字开头
- 不能使用Python的关键字(如if、for等)
- 建议使用有意义的名字
1.2 基本数据类型
数字类型
# 整数
count = 100
negative_num = -50
# 浮点数(小数)
price = 99.99
temperature = -3.5
# 数字运算
total = count + 50
average = (100 + 200 + 300) / 3
print(f"总数:{total},平均值:{average}")
字符串类型
# 字符串可以用单引号或双引号
message1 = "Hello World"
message2 = '你好,世界'
# 多行字符串用三引号
long_text = """
这是一段
很长的文字
可以换行
"""
# 字符串拼接
first_name = "张"
last_name = "三"
full_name = first_name + last_name
print(f"全名:{full_name}")
# 字符串格式化(推荐用f-string)
name = "李四"
score = 95
result = f"{name}的成绩是{score}分"
print(result)
布尔类型
# 布尔值只有两个:True 和 False
is_sunny = True
is_raining = False
# 布尔运算
is_good_weather = is_sunny and not is_raining
print(f"天气好吗?{is_good_weather}")
1.3 集合数据类型
列表(List)- 有序可变
# 创建列表
fruits = ["苹果", "香蕉", "橙子"]
numbers = [1, 2, 3, 4, 5]
mixed = ["文字", 123, True, 3.14]
# 访问元素(从0开始计数)
print(f"第一个水果:{fruits[0]}")
print(f"最后一个水果:{fruits[-1]}")
# 修改元素
fruits[1] = "葡萄"
print(f"修改后的水果:{fruits}")
# 添加元素
fruits.append("西瓜")
fruits.insert(1, "草莓") # 在位置1插入
print(f"添加后的水果:{fruits}")
# 删除元素
fruits.remove("橙子") # 删除指定元素
last_fruit = fruits.pop() # 删除并返回最后一个
print(f"删除后的水果:{fruits},被删除的:{last_fruit}")
元组(Tuple)- 有序不可变
# 创建元组(用圆括号,但其实括号可以省略)
coordinates = (10, 20)
colors = ("红", "绿", "蓝")
single_item = ("唯一元素",) # 注意:单个元素的元组需要逗号
# 访问元素
print(f"坐标x:{coordinates[0]}, y:{coordinates[1]}")
# 元组不能修改,但可以解包
x, y = coordinates
print(f"解包后:x={x}, y={y}")
# 元组的用途:函数返回多个值
def get_name_age():
return "王五", 25
name, age = get_name_age()
print(f"姓名:{name},年龄:{age}")
字典(Dict)- 键值对
# 创建字典
student = {
"name": "张三",
"age": 20,
"major": "计算机科学",
"grades": [85, 90, 78]
}
# 访问值
print(f"学生姓名:{student['name']}")
print(f"专业:{student.get('major', '未知')}") # get方法更安全
# 修改和添加
student["age"] = 21 # 修改
student["email"] = "zhangsan@example.com" # 添加新键值对
# 删除
del student["grades"] # 删除键值对
email = student.pop("email", "无邮箱") # 删除并返回值
# 遍历字典
for key, value in student.items():
print(f"{key}: {value}")
集合(Set)- 无序不重复
# 创建集合
numbers = {1, 2, 3, 4, 5}
fruits = {"苹果", "香蕉", "苹果", "橙子"} # 重复的"苹果"会被去除
print(f"水果集合:{fruits}")
# 集合运算
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(f"交集:{set1 & set2}") # {3, 4}
print(f"并集:{set1 | set2}") # {1, 2, 3, 4, 5, 6}
print(f"差集:{set1 - set2}") # {1, 2}
# 添加和删除
numbers.add(6)
numbers.remove(1) # 如果元素不存在会报错
numbers.discard(10) # 如果元素不存在不会报错
print(f"修改后的数字集合:{numbers}")
1.4 数据类型互转
在实际编程中,经常需要在不同数据类型之间进行转换。
列表、元组、集合互转
# 原始数据
original_list = [1, 2, 3, 4, 5, 2, 3] # 有重复元素
print(f"原始列表:{original_list}")
# 列表转元组
list_to_tuple = tuple(original_list)
print(f"列表转元组:{list_to_tuple}")
# 列表转集合(自动去重)
list_to_set = set(original_list)
print(f"列表转集合:{list_to_set}")
# 元组转列表
tuple_to_list = list(list_to_tuple)
print(f"元组转列表:{tuple_to_list}")
# 集合转列表
set_to_list = list(list_to_set)
print(f"集合转列表:{set_to_list}")
# 实用例子:去重并保持顺序
def remove_duplicates_keep_order(lst):
seen = set()
result = []
for item in lst:
if item not in seen:
seen.add(item)
result.append(item)
return result
unique_list = remove_duplicates_keep_order(original_list)
print(f"去重保持顺序:{unique_list}")
字典与列表互转
# 字典转换
student_dict = {
"张三": 85,
"李四": 92,
"王五": 78,
"赵六": 96
}
# 字典的键转列表
keys_list = list(student_dict.keys())
print(f"学生姓名列表:{keys_list}")
# 字典的值转列表
values_list = list(student_dict.values())
print(f"成绩列表:{values_list}")
# 字典转键值对列表
items_list = list(student_dict.items())
print(f"键值对列表:{items_list}")
# 两个列表合并成字典
names = ["小明", "小红", "小刚"]
ages = [18, 19, 20]
name_age_dict = dict(zip(names, ages))
print(f"姓名年龄字典:{name_age_dict}")
# 列表转字典(带索引)
fruits = ["苹果", "香蕉", "橙子"]
fruit_index_dict = {i: fruit for i, fruit in enumerate(fruits)}
print(f"水果索引字典:{fruit_index_dict}")
# 嵌套列表转字典
nested_data = [["name", "张三"], ["age", 25], ["city", "北京"]]
nested_dict = dict(nested_data)
print(f"嵌套数据转字典:{nested_dict}")
JSON与Python数据类型互转
import json
# Python数据结构
python_data = {
"name": "张三",
"age": 25,
"hobbies": ["读书", "游泳", "编程"],
"address": {
"city": "北京",
"district": "朝阳区"
},
"is_student": True,
"score": 95.5
}
# Python对象转JSON字符串
json_string = json.dumps(python_data, ensure_ascii=False, indent=2)
print("Python转JSON字符串:")
print(json_string)
# JSON字符串转Python对象
parsed_data = json.loads(json_string)
print(f"\nJSON转Python对象:{parsed_data}")
print(f"类型:{type(parsed_data)}")
# 保存到JSON文件
with open("student_data.json", "w", encoding="utf-8") as f:
json.dump(python_data, f, ensure_ascii=False, indent=2)
print("\n数据已保存到student_data.json")
# 从JSON文件读取
with open("student_data.json", "r", encoding="utf-8") as f:
loaded_data = json.load(f)
print(f"从文件读取的数据:{loaded_data}")
复杂数据结构转换示例
# 示例:处理学生成绩数据
students_data = [
{"name": "张三", "subjects": {"数学": 85, "英语": 90, "物理": 78}},
{"name": "李四", "subjects": {"数学": 92, "英语": 88, "物理": 95}},
{"name": "王五", "subjects": {"数学": 76, "英语": 82, "物理": 89}}
]
# 1. 提取所有学生姓名
student_names = [student["name"] for student in students_data]
print(f"学生姓名:{student_names}")
# 2. 转换为科目-成绩的字典格式
subject_scores = {}
for student in students_data:
for subject, score in student["subjects"].items():
if subject not in subject_scores:
subject_scores[subject] = []
subject_scores[subject].append(score)
print(f"按科目分组的成绩:{subject_scores}")
# 3. 计算每科平均分
subject_averages = {subject: sum(scores)/len(scores)
for subject, scores in subject_scores.items()}
print(f"各科平均分:{subject_averages}")
# 4. 转换为适合图表显示的格式
chart_data = {
"labels": list(subject_averages.keys()),
"data": list(subject_averages.values())
}
print(f"图表数据格式:{chart_data}")
# 5. 转换为JSON格式(用于前端显示)
chart_json = json.dumps(chart_data, ensure_ascii=False)
print(f"JSON格式:{chart_json}")
实用转换函数
def safe_convert_to_int_list(data):
"""安全地将各种数据转换为整数列表"""
result = []
if isinstance(data, str):
# 字符串按逗号分割
items = data.split(',')
elif isinstance(data, (list, tuple, set)):
items = data
else:
items = [data]
for item in items:
try:
if isinstance(item, str):
item = item.strip()
result.append(int(item))
except (ValueError, TypeError):
print(f"无法转换 '{item}' 为整数,跳过")
return result
# 测试转换函数
test_data = [
"1,2,3,4,5", # 字符串
[1.5, 2.7, 3.9], # 浮点数列表
(4, 5, 6), # 元组
{7, 8, 9}, # 集合
"10, 11, abc, 12" # 包含无效数据的字符串
]
for data in test_data:
converted = safe_convert_to_int_list(data)
print(f"{data} -> {converted}")
数据类型转换总结表
# 常用转换方法总结
conversion_examples = {
"基本转换": {
"str -> list": "list('hello') -> ['h','e','l','l','o']",
"list -> str": "''.join(['a','b','c']) -> 'abc'",
"list -> tuple": "tuple([1,2,3]) -> (1,2,3)",
"tuple -> list": "list((1,2,3)) -> [1,2,3]",
"list -> set": "set([1,2,2,3]) -> {1,2,3}",
"set -> list": "list({1,2,3}) -> [1,2,3]"
},
"字典转换": {
"dict.keys()": "获取所有键",
"dict.values()": "获取所有值",
"dict.items()": "获取键值对列表",
"zip(keys, values)": "两个列表合并为字典",
"dict(list_of_pairs)": "键值对列表转字典"
},
"JSON转换": {
"json.dumps()": "Python对象转JSON字符串",
"json.loads()": "JSON字符串转Python对象",
"json.dump()": "Python对象保存到文件",
"json.load()": "从文件读取JSON数据"
}
}
# 打印转换方法总结
for category, methods in conversion_examples.items():
print(f"\n=== {category} ===")
for method, description in methods.items():
print(f"{method:15} : {description}")
转换技巧
选择合适的数据类型:
- 列表:需要保持顺序、允许重复、需要修改
- 元组:需要保持顺序、不允许修改、用作字典键
- 集合:需要去重、快速查找成员
- 字典:需要键值对应关系、快速按键查找
JSON转换注意事项:
- 使用
ensure_ascii=False
支持中文 - 使用
indent
参数美化输出格式 - Python的
None
、True
、False
会转换为JSON的null
、true
、false
2. 运算符与表达式
2.1 算术运算符
a = 10
b = 3
print(f"加法:{a} + {b} = {a + b}") # 13
print(f"减法:{a} - {b} = {a - b}") # 7
print(f"乘法:{a} * {b} = {a * b}") # 30
print(f"除法:{a} / {b} = {a / b}") # 3.333...
print(f"整除:{a} // {b} = {a // b}") # 3
print(f"取余:{a} % {b} = {a % b}") # 1
print(f"幂运算:{a} ** {b} = {a ** b}") # 1000
# 实用例子:判断奇偶数
number = 17
if number % 2 == 0:
print(f"{number}是偶数")
else:
print(f"{number}是奇数")
2.2 比较运算符
x = 5
y = 10
print(f"{x} == {y}: {x == y}") # False,相等
print(f"{x} != {y}: {x != y}") # True,不相等
print(f"{x} < {y}: {x < y}") # True,小于
print(f"{x} > {y}: {x > y}") # False,大于
print(f"{x} <= {y}: {x <= y}") # True,小于等于
print(f"{x} >= {y}: {x >= y}") # False,大于等于
# 字符串比较
name1 = "Alice"
name2 = "Bob"
print(f"'{name1}' < '{name2}': {name1 < name2}") # True,按字母顺序
2.3 逻辑运算符
# and(与)、or(或)、not(非)
age = 20
has_license = True
has_car = False
# and:所有条件都为True才返回True
can_drive = age >= 18 and has_license
print(f"能开车吗?{can_drive}")
# or:任意一个条件为True就返回True
need_transport = not has_car or age < 18
print(f"需要其他交通工具吗?{need_transport}")
# 实用例子:用户权限检查
username = "admin"
password = "123456"
is_admin = username == "admin" and password == "123456"
print(f"是管理员吗?{is_admin}")
2.4 成员运算符
# in 和 not in
fruits = ["苹果", "香蕉", "橙子"]
favorite_fruit = "苹果"
if favorite_fruit in fruits:
print(f"{favorite_fruit}在水果列表中")
else:
print(f"{favorite_fruit}不在水果列表中")
# 字符串中的成员运算
text = "Hello World"
if "World" in text:
print("找到了'World'")
# 字典中的成员运算(检查键)
student = {"name": "张三", "age": 20}
if "name" in student:
print(f"学生姓名:{student['name']}")
3. 条件与循环
3.1 条件判断(if语句)
# 基本if语句
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"分数:{score},等级:{grade}")
# 实用例子:天气建议
temperature = 25
is_raining = False
if temperature > 30:
suggestion = "太热了,待在室内吧"
elif temperature > 20 and not is_raining:
suggestion = "天气不错,适合出门"
elif is_raining:
suggestion = "下雨了,记得带伞"
else:
suggestion = "有点冷,多穿点衣服"
print(f"今天{temperature}度,{'下雨' if is_raining else '晴天'},建议:{suggestion}")
3.2 for循环
# 遍历列表
fruits = ["苹果", "香蕉", "橙子", "葡萄"]
print("我喜欢的水果:")
for fruit in fruits:
print(f"- {fruit}")
# 遍历字符串
word = "Python"
print("字母分解:")
for letter in word:
print(letter, end=" ") # end=" "表示不换行,用空格分隔
print() # 换行
# 使用range()生成数字序列
print("1到5的平方:")
for i in range(1, 6): # range(1, 6)生成1,2,3,4,5
print(f"{i}的平方是{i**2}")
# 遍历字典
student = {"姓名": "李四", "年龄": 22, "专业": "数学"}
print("学生信息:")
for key, value in student.items():
print(f"{key}:{value}")
# 带索引的遍历
colors = ["红", "绿", "蓝"]
for index, color in enumerate(colors):
print(f"第{index+1}个颜色是{color}")
3.3 while循环
# 基本while循环
count = 1
print("倒计时:")
while count <= 5:
print(f"{count}...")
count += 1
print("时间到!")
# 实用例子:猜数字游戏
import random
secret_number = random.randint(1, 10)
guess = 0
attempts = 0
print("猜数字游戏!我想了一个1-10之间的数字")
while guess != secret_number:
guess = int(input("请输入你的猜测:"))
attempts += 1
if guess < secret_number:
print("太小了!")
elif guess > secret_number:
print("太大了!")
else:
print(f"恭喜!你用{attempts}次猜对了!")
3.4 循环控制
# break:跳出循环
print("寻找第一个偶数:")
numbers = [1, 3, 7, 8, 9, 12, 15]
for num in numbers:
if num % 2 == 0:
print(f"找到了第一个偶数:{num}")
break
print(f"{num}是奇数,继续寻找...")
# continue:跳过当前循环
print("\n只打印偶数:")
for num in range(1, 11):
if num % 2 != 0: # 如果是奇数
continue # 跳过后面的代码,继续下一次循环
print(f"{num}是偶数")
# 嵌套循环
print("\n九九乘法表:")
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j}", end="\t")
print() # 换行
4. 列表推导式
列表推导式是Python的一个强大特性,可以用简洁的方式创建列表。
4.1 基本语法
# 传统方式:创建1到10的平方列表
squares_traditional = []
for i in range(1, 11):
squares_traditional.append(i ** 2)
print(f"传统方式:{squares_traditional}")
# 列表推导式:一行搞定
squares_comprehension = [i ** 2 for i in range(1, 11)]
print(f"列表推导式:{squares_comprehension}")
# 基本语法:[表达式 for 变量 in 可迭代对象]
4.2 带条件的列表推导式
# 筛选偶数
numbers = range(1, 21)
even_numbers = [num for num in numbers if num % 2 == 0]
print(f"1-20中的偶数:{even_numbers}")
# 筛选并转换
words = ["apple", "banana", "cherry", "date"]
long_words_upper = [word.upper() for word in words if len(word) > 5]
print(f"长度大于5的单词(大写):{long_words_upper}")
# 实用例子:处理学生成绩
scores = [85, 92, 78, 96, 88, 76, 94]
high_scores = [score for score in scores if score >= 90]
print(f"优秀成绩(>=90):{high_scores}")
# 成绩等级转换
grade_letters = ["A" if score >= 90 else "B" if score >= 80 else "C"
for score in scores]
print(f"成绩等级:{grade_letters}")
4.3 嵌套列表推导式
# 创建二维列表(矩阵)
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print("3x3矩阵:")
for row in matrix:
print(row)
# 展平嵌套列表
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in nested_list for num in row]
print(f"展平后:{flattened}")
# 实用例子:处理学生信息
students = [
{"name": "张三", "scores": [85, 90, 78]},
{"name": "李四", "scores": [92, 88, 95]},
{"name": "王五", "scores": [76, 82, 89]}
]
# 提取所有学生的所有成绩
all_scores = [score for student in students for score in student["scores"]]
print(f"所有成绩:{all_scores}")
# 计算每个学生的平均分
averages = [sum(student["scores"]) / len(student["scores"]) for student in students]
print(f"平均分:{averages}")
4.4 其他推导式
# 字典推导式
fruits = ["apple", "banana", "cherry"]
fruit_lengths = {fruit: len(fruit) for fruit in fruits}
print(f"水果长度字典:{fruit_lengths}")
# 集合推导式
numbers = [1, 2, 2, 3, 3, 4, 5]
unique_squares = {num ** 2 for num in numbers}
print(f"唯一平方数集合:{unique_squares}")
# 生成器表达式(节省内存)
large_squares = (i ** 2 for i in range(1000000)) # 不会立即计算
print(f"生成器对象:{large_squares}")
print(f"前5个值:{[next(large_squares) for _ in range(5)]}")
4.5 实际应用示例
# 示例1:处理文本数据
text = "Hello World Python Programming"
words = text.split()
# 提取长度大于5的单词,转为小写
long_words = [word.lower() for word in words if len(word) > 5]
print(f"长单词:{long_words}")
# 示例2:数据清洗
raw_data = [" 123 ", "456", " 789 ", "abc", " 012 "]
# 清理空格并转换为数字(跳过非数字)
clean_numbers = [int(item.strip()) for item in raw_data if item.strip().isdigit()]
print(f"清理后的数字:{clean_numbers}")
# 示例3:坐标转换
points = [(1, 2), (3, 4), (5, 6)]
# 计算每个点到原点的距离
distances = [round((x**2 + y**2)**0.5, 2) for x, y in points]
print(f"到原点距离:{distances}")
# 示例4:文件处理模拟
file_names = ["document.txt", "image.jpg", "script.py", "data.csv", "photo.png"]
# 筛选图片文件
image_files = [name for name in file_names if name.endswith(('.jpg', '.png'))]
print(f"图片文件:{image_files}")
使用建议
什么时候用列表推导式:
- 简单的数据转换和筛选
- 代码逻辑清晰,一行能表达完整
- 需要创建新列表的场景
什么时候不用:
- 逻辑复杂,影响代码可读性
- 需要复杂的错误处理
- 有副作用的操作(如打印、文件操作)
记住:代码的可读性比简洁性更重要!
总结
通过本文,我们学习了Python的核心语法:
- 变量与数据类型:掌握了基本类型和集合类型的使用
- 运算符与表达式:学会了各种运算符的应用
- 条件与循环:理解了程序流程控制的方法
- 列表推导式:掌握了Python的高效编程技巧
这些是Python编程的基础,熟练掌握后就可以开始编写更复杂的程序了。记住,多练习是提高编程能力的最好方法!
下一步学习建议
- 练习编写小程序巩固语法
- 学习函数和模块的使用
- 了解面向对象编程
- 探索Python的标准库
Powered by Waline v3.6.0