[Python] Python 语法及入门(超全超详细)

134 0
Honkers 4 天前 来自手机 | 显示全部楼层 |阅读模式

Python是一种解释型的高级编程语言,其设计哲学强调代码的可读性和简洁性。以下是对Python语法及入门的超全超详细代码讲解:

CSDN大礼包:《2025年最新全套学习资料包》免费分享

1. Python 基础语法

1.1 第一个Python程序

  1. # 这是一个单行注释
  2. print("Hello, World!") # 输出字符串
复制代码

1.2 变量和数据类型

  1. # 变量声明和赋值
  2. name = "Alice" # 字符串
  3. age = 25 # 整数
  4. height = 1.75 # 浮点数
  5. is_student = True # 布尔值
  6. # 打印变量类型
  7. print(type(name)) # <class 'str'>
  8. print(type(age)) # <class 'int'>
  9. print(type(height)) # <class 'float'>
  10. print(type(is_student)) # <class 'bool'>
复制代码

1.3 运算符

  1. # 算术运算符
  2. a = 10
  3. b = 3
  4. print(a + b) # 加法 13
  5. print(a - b) # 减法 7
  6. print(a * b) # 乘法 30
  7. print(a / b) # 除法 3.333...
  8. print(a // b) # 整除 3
  9. print(a % b) # 取余 1
  10. print(a ** b) # 幂运算 1000
  11. # 比较运算符
  12. print(a == b) # False
  13. print(a != b) # True
  14. print(a > b) # True
  15. print(a < b) # False
  16. # 逻辑运算符
  17. x = True
  18. y = False
  19. print(x and y) # False
  20. print(x or y) # True
  21. print(not x) # False
复制代码

2. 控制流

2.1 条件语句

  1. # if-elif-else 结构
  2. score = 85
  3. if score >= 90:
  4. print("优秀")
  5. elif score >= 80:
  6. print("良好")
  7. elif score >= 60:
  8. print("及格")
  9. else:
  10. print("不及格")
复制代码

2.2 循环结构

  1. # for 循环
  2. for i in range(5): # 0到4
  3. print(i)
  4. for i in range(1, 6): # 1到5
  5. print(i)
  6. # while 循环
  7. count = 0
  8. while count < 5:
  9. print(count)
  10. count += 1
  11. # break 和 continue
  12. for num in range(10):
  13. if num == 3:
  14. continue # 跳过本次循环
  15. if num == 8:
  16. break # 终止循环
  17. print(num)
复制代码

3. 数据结构

3.1 列表 (List)

  1. # 创建列表
  2. fruits = ['apple', 'banana', 'cherry']
  3. print(fruits[1]) # 访问元素 banana
  4. # 修改列表
  5. fruits[0] = 'orange'
  6. print(fruits) # ['orange', 'banana', 'cherry']
  7. # 列表方法
  8. fruits.append('grape') # 添加元素
  9. fruits.insert(1, 'mango') # 插入元素
  10. fruits.remove('banana') # 删除元素
  11. print(fruits) # ['orange', 'mango', 'cherry', 'grape']
  12. # 列表切片
  13. print(fruits[1:3]) # ['mango', 'cherry']
  14. # 列表遍历
  15. for fruit in fruits:
  16. print(fruit)
复制代码

3.2 元组 (Tuple)

  1. # 创建元组
  2. coordinates = (10, 20)
  3. print(coordinates[0]) # 10
  4. # 元组不可修改
  5. # coordinates[0] = 15 # 会报错
  6. # 元组解包
  7. x, y = coordinates
  8. print(x, y) # 10 20
复制代码

3.3 集合 (Set)

  1. # 创建集合
  2. unique_numbers = {1, 2, 3, 2, 1} # 自动去重 {1, 2, 3}
  3. # 集合操作
  4. a = {1, 2, 3}
  5. b = {3, 4, 5}
  6. print(a | b) # 并集 {1, 2, 3, 4, 5}
  7. print(a & b) # 交集 {3}
  8. print(a - b) # 差集 {1, 2}
复制代码

3.4 字典 (Dictionary)

  1. # 创建字典
  2. person = {
  3. 'name': 'Alice',
  4. 'age': 25,
  5. 'city': 'New York'
  6. }
  7. # 访问字典值
  8. print(person['name']) # Alice
  9. print(person.get('age')) # 25
  10. # 修改字典
  11. person['age'] = 26
  12. person['email'] = 'alice@example.com'
  13. # 遍历字典
  14. for key, value in person.items():
  15. print(f"{key}: {value}")
复制代码

4. 函数

4.1 定义和调用函数

  1. # 定义函数
  2. def greet(name):
  3. """这是一个问候函数"""
  4. return f"Hello, {name}!"
  5. # 调用函数
  6. message = greet("Alice")
  7. print(message) # Hello, Alice!
  8. # 默认参数
  9. def power(base, exponent=2):
  10. return base ** exponent
  11. print(power(3)) # 9 (3的2次方)
  12. print(power(3, 3)) # 27 (3的3次方)
复制代码

4.2 返回值

  1. # 多返回值
  2. def min_max(numbers):
  3. return min(numbers), max(numbers)
  4. min_val, max_val = min_max([1, 2, 3, 4, 5])
  5. print(f"最小值: {min_val}, 最大值: {max_val}")
复制代码

4.3 匿名函数 (Lambda)

  1. # 使用lambda定义简单函数
  2. double = lambda x: x * 2
  3. print(double(5)) # 10
  4. # 在高阶函数中使用
  5. numbers = [1, 2, 3, 4, 5]
  6. squared = list(map(lambda x: x**2, numbers))
  7. print(squared) # [1, 4, 9, 16, 25]
复制代码

5. 文件操作

5.1 读写文件

  1. # 写入文件
  2. with open('example.txt', 'w') as file:
  3. file.write("这是第一行\n")
  4. file.write("这是第二行\n")
  5. # 读取文件
  6. with open('example.txt', 'r') as file:
  7. content = file.read()
  8. print(content)
  9. # 逐行读取
  10. with open('example.txt', 'r') as file:
  11. for line in file:
  12. print(line.strip()) # 去除换行符
复制代码

5.2 JSON 文件处理

  1. import json
  2. # 写入JSON
  3. data = {
  4. "name": "Alice",
  5. "age": 25,
  6. "hobbies": ["reading", "hiking"]
  7. }
  8. with open('data.json', 'w') as file:
  9. json.dump(data, file, indent=4)
  10. # 读取JSON
  11. with open('data.json', 'r') as file:
  12. loaded_data = json.load(file)
  13. print(loaded_data)
复制代码

6. 面向对象编程

6.1 类和对象

  1. # 定义类
  2. class Person:
  3. def __init__(self, name, age):
  4. self.name = name
  5. self.age = age
  6. def greet(self):
  7. return f"Hello, my name is {self.name} and I'm {self.age} years old."
  8. # 创建对象
  9. person1 = Person("Alice", 25)
  10. print(person1.greet())
  11. # 继承
  12. class Student(Person):
  13. def __init__(self, name, age, student_id):
  14. super().__init__(name, age)
  15. self.student_id = student_id
  16. def study(self):
  17. return f"{self.name} is studying."
  18. student1 = Student("Bob", 20, "S12345")
  19. print(student1.greet())
  20. print(student1.study())
复制代码

6.2 特殊方法

  1. class Vector:
  2. def __init__(self, x, y):
  3. self.x = x
  4. self.y = y
  5. def __add__(self, other):
  6. return Vector(self.x + other.x, self.y + other.y)
  7. def __str__(self):
  8. return f"Vector({self.x}, {self.y})"
  9. v1 = Vector(2, 3)
  10. v2 = Vector(4, 5)
  11. v3 = v1 + v2
  12. print(v3) # Vector(6, 8)
复制代码

7. 异常处理

  1. # try-except 块
  2. try:
  3. result = 10 / 0
  4. except ZeroDivisionError:
  5. print("不能除以零!")
  6. finally:
  7. print("这段代码总是会执行")
  8. # 捕获多个异常
  9. try:
  10. # 可能出错的代码
  11. value = int("abc")
  12. except ValueError:
  13. print("无效的整数字符串")
  14. except (TypeError, ZeroDivisionError):
  15. print("类型错误或除以零")
  16. # 自定义异常
  17. class NegativeNumberError(Exception):
  18. pass
  19. def square_root(x):
  20. if x < 0:
  21. raise NegativeNumberError("不能计算负数的平方根")
  22. return x ** 0.5
  23. try:
  24. print(square_root(-1))
  25. except NegativeNumberError as e:
  26. print(e)
复制代码

8. 模块和包

8.1 创建和使用模块

  1. # math_operations.py
  2. def add(a, b):
  3. return a + b
  4. def subtract(a, b):
  5. return a - b
  6. # main.py
  7. import math_operations
  8. print(math_operations.add(5, 3)) # 8
  9. print(math_operations.subtract(5, 3)) # 2
复制代码

8.2 使用标准库

  1. import math
  2. import random
  3. from datetime import datetime
  4. # 数学函数
  5. print(math.sqrt(16)) # 4.0
  6. print(math.pi) # 3.141592653589793
  7. # 随机数
  8. print(random.randint(1, 100)) # 1到100之间的随机整数
  9. # 日期时间
  10. now = datetime.now()
  11. print(now.strftime("%Y-%m-%d %H:%M:%S"))
复制代码

9. 高级特性

9.1 列表推导式

  1. # 普通列表
  2. squares = []
  3. for x in range(10):
  4. squares.append(x**2)
  5. # 列表推导式
  6. squares = [x**2 for x in range(10)]
  7. print(squares)
  8. # 带条件的列表推导式
  9. even_squares = [x**2 for x in range(10) if x % 2 == 0]
  10. print(even_squares)
复制代码

9.2 生成器

  1. # 生成器函数
  2. def countdown(n):
  3. while n > 0:
  4. yield n
  5. n -= 1
  6. # 使用生成器
  7. for i in countdown(5):
  8. print(i) # 5, 4, 3, 2, 1
  9. # 生成器表达式
  10. sum_of_squares = sum(x**2 for x in range(10))
  11. print(sum_of_squares)
复制代码

9.3 装饰器

  1. def my_decorator(func):
  2. def wrapper():
  3. print("函数执行前")
  4. func()
  5. print("函数执行后")
  6. return wrapper
  7. @my_decorator
  8. def say_hello():
  9. print("Hello!")
  10. say_hello()
  11. """
  12. 输出:
  13. 函数执行前
  14. Hello!
  15. 函数执行后
  16. """
复制代码

10. 常用内置函数

  1. # map 和 filter
  2. numbers = [1, 2, 3, 4, 5]
  3. doubled = list(map(lambda x: x*2, numbers)) # [2, 4, 6, 8, 10]
  4. evens = list(filter(lambda x: x%2 == 0, numbers)) # [2, 4]
  5. # enumerate
  6. for i, value in enumerate(['a', 'b', 'c']):
  7. print(i, value) # 0 a, 1 b, 2 c
  8. # zip
  9. names = ['Alice', 'Bob', 'Charlie']
  10. ages = [25, 30, 35]
  11. for name, age in zip(names, ages):
  12. print(f"{name} is {age} years old")
  13. # any 和 all
  14. print(any([False, True, False])) # True
  15. print(all([True, True, False])) # False
复制代码

总结

以上是Python的基础语法和常用功能的详细介绍。Python的语法简洁明了,非常适合初学者入门。要掌握Python,最重要的是多实践,通过编写代码来巩固所学知识。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2026 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行