Python基础

40 阅读3分钟

Python是一种高级、解释型、通用的编程语言,以其简洁的语法和强大的功能而闻名。以下是Python基础知识的概述:

1. 基本语法

变量与数据类型

# 基本数据类型
num_int = 10          # 整数
num_float = 3.14      # 浮点数
boolean = True        # 布尔值
string = "Hello"      # 字符串
none_value = None     # 空值

# 集合类型
my_list = [1, 2, 3]           # 列表(可变)
my_tuple = (1, 2, 3)          # 元组(不可变)
my_set = {1, 2, 3}            # 集合(唯一元素)
my_dict = {"name": "Alice"}   # 字典(键值对)

运算符

# 算术运算符
sum = a + b
difference = a - b
product = a * b
quotient = a / b
remainder = a % b
exponent = a ** b  # 幂运算

# 比较运算符
is_equal = (a == b)
is_greater = (a > b)

# 逻辑运算符
result = (a > b) and (c < d)
alternative = (a > b) or (c < d)
negation = not (a > b)

2. 控制结构

条件语句

# if-elif-else
if score >= 90:
    print("优秀")
elif score >= 60:
    print("及格")
else:
    print("不及格")

# 三元表达式
result = "及格" if score >= 60 else "不及格"

循环结构

# for循环
for i in range(5):  # 0到4
    print(i)

# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# while循环
count = 0
while count < 5:
    print(count)
    count += 1

3. 函数

定义与调用函数

# 定义函数
def greet(name):
    return f"Hello, {name}!"

# 调用函数
message = greet("Alice")
print(message)

# 默认参数
def power(base, exponent=2):
    return base ** exponent

# 可变参数
def sum_all(*args):
    return sum(args)

4. 面向对象编程

类与对象

class Person:
    # 构造方法
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    # 实例方法
    def introduce(self):
        print(f"我叫{self.name}, 今年{self.age}岁")

# 创建对象
p = Person("张三", 25)
p.introduce()

继承

class Student(Person):
    def __init__(self, name, age, school):
        super().__init__(name, age)  # 调用父类构造方法
        self.school = school
    
    # 方法重写
    def introduce(self):
        super().introduce()
        print(f"我在{self.school}上学")

5. 异常处理

try:
    # 可能抛出异常的代码
    result = 10 / 0
except ZeroDivisionError:
    # 处理特定异常
    print("除数不能为零")
except Exception as e:
    # 处理其他异常
    print(f"发生错误: {e}")
else:
    # 没有异常时执行
    print("计算成功")
finally:
    # 无论是否发生异常都会执行
    print("程序执行完毕")

6. 常用数据结构

列表操作

numbers = [1, 2, 3, 4, 5]

# 添加元素
numbers.append(6)        # [1, 2, 3, 4, 5, 6]
numbers.insert(0, 0)     # [0, 1, 2, 3, 4, 5, 6]

# 删除元素
numbers.pop()            # 删除并返回最后一个元素
numbers.remove(3)        # 删除第一个值为3的元素

# 列表切片
first_three = numbers[:3]  # [0, 1, 2]
last_two = numbers[-2:]    # [5, 6]

# 列表推导式
squares = [x**2 for x in numbers if x % 2 == 0]

字典操作

person = {"name": "Alice", "age": 25, "city": "New York"}

# 访问值
print(person["name"])  # Alice
print(person.get("age"))  # 25

# 添加/修改
person["job"] = "Engineer"
person["age"] = 26

# 遍历
for key, value in person.items():
    print(f"{key}: {value}")

# 字典推导式
squared_dict = {x: x**2 for x in range(5)}

7. 文件操作

# 写入文件
with open("example.txt", "w", encoding="utf-8") as file:
    file.write("Hello, Python!\n")
    file.write("这是第二行")

# 读取文件
with open("example.txt", "r", encoding="utf-8") as file:
    content = file.read()  # 读取全部内容
    # 或者逐行读取
    for line in file:
        print(line.strip())

8. 模块与包

# 导入模块
import math
from datetime import datetime
import os.path as path

# 使用模块
print(math.sqrt(16))  # 4.0
print(datetime.now())  # 当前时间

# 创建自己的模块
# 创建一个my_module.py文件
"""
def say_hello():
    print("Hello from my_module")
"""

# 在其他文件中使用
import my_module
my_module.say_hello()

9. 常用内置函数

# 类型转换
int("123")      # 123
float("3.14")   # 3.14
str(100)        # "100"
list("abc")     # ['a', 'b', 'c']

# 其他常用函数
len([1, 2, 3])          # 3
sorted([3, 1, 2])       # [1, 2, 3]
sum([1, 2, 3])          # 6
max([1, 2, 3])          # 3
min([1, 2, 3])          # 1
range(5)                # 生成0-4的序列
enumerate(["a", "b"])   # 生成(索引, 值)对
zip([1, 2], ["a", "b"]) # 生成(1, "a"), (2, "b")

Python的这些基础知识为更高级的主题如Web开发、数据分析、机器学习等奠定了基础。