Python 的基础知识
Python 是一种高级、动态、解释型的编程语言,具有简单易学、功能强大、跨平台等优点。以下是 Python 基础知识的详细讲解,涵盖语法、数据类型、控制结构、函数等内容。
一、Python 的基本语法
- 程序结构:
- Python 程序由一系列语句组成,每条语句通常占一行。
- 使用缩进(而不是大括号
{})来表示代码块。1
2if True:
print("Hello, World!")
- 注释:
- 单行注释:
#1
# 这是一个单行注释
- 多行注释:使用三引号
'''或"""。1
2
3
4"""
这是多行注释
可以跨越多行
"""
- 单行注释:
- 输入输出:
- 输出:
print()函数。1
print("Hello, World!")
- 输入:
input()函数。1
2name = input("请输入你的名字:")
print(f"你好,{name}!")
- 输出:
二、数据类型与变量
- 基本数据类型:
- 整数:
int,如10, -5, 0 - 浮点数:
float,如3.14, -0.001 - 布尔值:
bool,True或False - 字符串:
str,用单引号' '或双引号" "表示。1
message = "Hello, Python!"
- 空值:
None,表示没有值。
- 整数:
- 复合数据类型:
- 列表(List):有序、可变的集合。
1
numbers = [1, 2, 3]
- 元组(Tuple):有序、不可变的集合。
1
coordinates = (10, 20)
- 字典(Dictionary):键值对的集合。
1
person = {"name": "Alice", "age": 25}
- 集合(Set):无序、不重复的元素集合。
1
unique_numbers = {1, 2, 3}
- 列表(List):有序、可变的集合。
- 变量声明与赋值:
- 动态类型,无需显式声明类型。
1
2x = 10
y = "Hello"
- 动态类型,无需显式声明类型。
- 多重赋值:
1
a, b, c = 1, 2, 3
三、运算符与表达式
- 算术运算符:
- 加减乘除:
+, -, *, / - 整除:
// - 取模:
% - 幂运算:
**
- 加减乘除:
- 关系运算符:
- 比较大小:
==, !=, >, <, >=, <=
- 比较大小:
- 逻辑运算符:
- 逻辑与:
and - 逻辑或:
or - 逻辑非:
not
- 逻辑与:
- 位运算符:
- 按位与:
& - 按位或:
| - 按位异或:
^ - 左移:
<< - 右移:
>>
- 按位与:
- 赋值运算符:
- 简单赋值:
= - 复合赋值:
+=, -=, *=, /=
- 简单赋值:
- 成员运算符:
- 判断是否在序列中:
in, not in1
2if "apple" in ["apple", "banana"]:
print("Found!")
- 判断是否在序列中:
- 身份运算符:
- 判断两个对象是否为同一对象:
is, is not
- 判断两个对象是否为同一对象:
四、控制结构
- 条件语句:
if-elif-else:1
2
3
4
5
6
7x = 10
if x > 0:
print("正数")
elif x == 0:
print("零")
else:
print("负数")
- 循环语句:
for循环:1
2for i in range(5):
print(i)while循环:1
2
3
4count = 0
while count < 5:
print(count)
count += 1
- 跳转语句:
break:跳出循环。continue:跳过当前迭代。pass:占位符,表示什么都不做。
五、函数
- 定义函数:
1
2def greet(name):
return f"Hello, {name}!" - 默认参数:
1
2def greet(name="World"):
return f"Hello, {name}!" - 可变参数:
*args:接收任意数量的位置参数。1
2def sum_all(*args):
return sum(args)**kwargs:接收任意数量的关键字参数。1
2
3def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
- 匿名函数(Lambda):
1
2square = lambda x: x ** 2
print(square(5)) # 输出 25 - 作用域:
- 局部变量:在函数内部定义。
- 全局变量:在函数外部定义,使用
global关键字修改。
六、模块与包
- 导入模块:
- 使用
import导入模块。1
2import math
print(math.sqrt(16)) - 使用
from ... import导入特定函数。1
2from math import sqrt
print(sqrt(16))
- 使用
- 创建模块:
- 将函数保存到
.py文件中,文件名即为模块名。1
2
3# my_module.py
def greet(name):
return f"Hello, {name}!"
- 将函数保存到
- 包:
- 包是包含多个模块的目录,必须包含一个
__init__.py文件。1
2
3
4my_package/
__init__.py
module1.py
module2.py
- 包是包含多个模块的目录,必须包含一个
七、文件操作
- 打开文件:
1
2with open("example.txt", "r") as file:
content = file.read() - 写入文件:
1
2with open("example.txt", "w") as file:
file.write("Hello, Python!") - 读取文件内容:
- 按行读取:
1
2
3with open("example.txt", "r") as file:
for line in file:
print(line.strip())
- 按行读取:
八、异常处理
- 捕获异常:
1
2
3
4
5
6try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"错误:{e}")
finally:
print("执行完成") - 抛出异常:
1
raise ValueError("无效的值")
九、面向对象编程(OOP)
- 类与对象:
1
2
3
4
5
6
7class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name}." - 继承:
1
2
3
4class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id - 多态:
- 不同子类可以实现相同的方法,表现出不同的行为。
- 封装:
- 使用私有属性和方法保护数据。
1
2
3class MyClass:
def __init__(self):
self.__private_var = 10
十、其他常用功能
- 列表推导式:
1
squares = [x**2 for x in range(10)]
- 生成器:
1
2
3def generate_numbers():
for i in range(5):
yield i - 装饰器:
1
2
3
4
5
6
7
8
9
10def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
def say_hello():
print("Hello!")
If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !