目前AI很火,agent应用场景也越来越多,那作为AI中,目前比较贴合的语言python我们该如何掌握它呢?python是一种高级、解释型、通用的编程语言,以其简洁的语法和强大的功能而闻名。接下来我将从几个方面来介绍 python 的基础知识。
一、变量与数据类型
基本数据类型
# 整数
age = 25# 浮点数
height = 1.75# 字符串
name = "Alice"# 布尔值
is_student = True# 空值
result = None
数据类型检查与转换
# 类型检查
print(type(age)) # <class 'int'>
print(type(name)) # <class 'str'># 类型转换
num_str = "123"
num_int = int(num_str)
num_float = float(num_str)
str_num = str(123)
二、数据结构
列表 (List)
# 创建列表
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]# 列表操作
fruits.append("grape") # 添加元素
fruits.remove("banana") # 删除元素
fruits[0] = "pear" # 修改元素# 列表切片
print(numbers[1:3]) # [2, 3]
print(numbers[:3]) # [1, 2, 3]
print(numbers[2:]) # [3, 4, 5]
元组 (Tuple)
# 创建元组(不可变)
coordinates = (10, 20)
person = ("Alice", 25, "Engineer")# 访问元素
print(coordinates[0]) # 10
字典 (Dictionary)
# 创建字典
student = {"name": "Bob","age": 20,"major": "Computer Science"
}# 字典操作
student["grade"] = "A" # 添加键值对
print(student["name"]) # 访问值
del student["age"] # 删除键值对
集合 (Set)
# 创建集合
unique_numbers = {1, 2, 3, 3, 4} # {1, 2, 3, 4}# 集合操作
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1.union(set2)) # {1, 2, 3, 4, 5}
print(set1.intersection(set2)) # {3}
三、 控制流程
条件语句
# if-elif-else
score = 85if score >= 90:grade = "A"
elif score >= 80:grade = "B"
elif score >= 70:grade = "C"
else:grade = "D"print(f"成绩等级: {grade}")
循环语句
# for 循环
fruits = ["apple", "banana", "orange"]
for fruit in fruits:print(fruit)# 使用 range()
for i in range(5): # 0, 1, 2, 3, 4print(i)for i in range(1, 6): # 1, 2, 3, 4, 5print(i)# while 循环
count = 0
while count < 5:print(count)count += 1# 循环控制
for i in range(10):if i == 3:continue # 跳过本次循环if i == 7:break # 终止循环print(i)
四、函数
函数定义与调用
# 基本函数
def greet(name):return f"Hello, {name}!"print(greet("Alice")) # Hello, Alice!# 带默认参数的函数
def introduce(name, age=18):return f"My name is {name}, I'm {age} years old."print(introduce("Bob")) # My name is Bob, I'm 18 years old.
print(introduce("Charlie", 25)) # My name is Charlie, I'm 25 years old.# 返回多个值
def calculate(a, b):return a + b, a - b, a * bsum_result, diff_result, product_result = calculate(10, 5)
Lambda 函数
# 匿名函数
square = lambda x: x ** 2
print(square(5)) # 25# 在排序中使用
students = [("Alice", 20), ("Bob", 18), ("Charlie", 22)]
students.sort(key=lambda student: student[1])
print(students) # [('Bob', 18), ('Alice', 20), ('Charlie', 22)]
五、文件操作
# 写入文件
with open("example.txt", "w", encoding="utf-8") as file:file.write("Hello, World!\n")file.write("This is a text file.\n")# 读取文件
with open("example.txt", "r", encoding="utf-8") as file:content = file.read()print(content)# 逐行读取
with open("example.txt", "r", encoding="utf-8") as file:for line in file:print(line.strip())
六、异常处理
try:num = int(input("请输入一个数字: "))result = 10 / numprint(f"结果是: {result}")
except ValueError:print("输入错误,请输入有效的数字!")
except ZeroDivisionError:print("错误:不能除以零!")
except Exception as e:print(f"发生未知错误: {e}")
else:print("计算成功完成!")
finally:print("程序执行完毕。")
七、面向对象编程
类与对象
class Student:# 类属性school = "ABC School"# 初始化方法def __init__(self, name, age):self.name = name # 实例属性self.age = age# 实例方法def introduce(self):return f"My name is {self.name}, I'm {self.age} years old."# 类方法@classmethoddef get_school_info(cls):return f"This is {cls.school}"# 创建对象
student1 = Student("Alice", 20)
print(student1.introduce()) # My name is Alice, I'm 20 years old.
print(Student.get_school_info()) # This is ABC School
继承
class Person:def __init__(self, name, age):self.name = nameself.age = agedef speak(self):return f"My name is {self.name}"class Teacher(Person):def __init__(self, name, age, subject):super().__init__(name, age)self.subject = subjectdef speak(self):return f"I'm {self.name}, I teach {self.subject}"teacher = Teacher("Mr. Smith", 35, "Math")
print(teacher.speak()) # I'm Mr. Smith, I teach Math
八、模块与包
# 导入整个模块
import math
print(math.sqrt(16)) # 4.0# 导入特定函数
from math import pi, cos
print(pi) # 3.141592653589793# 给模块起别名
import numpy as np
import pandas as pd
九、列表推导式
# 基本列表推导式
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]# 带条件的列表推导式
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]# 字典推导式
square_dict = {x: x**2 for x in range(1, 6)}
print(square_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
十、常用内置函数
# len() - 获取长度
print(len("hello")) # 5
print(len([1, 2, 3])) # 3# range() - 生成数字序列
print(list(range(5))) # [0, 1, 2, 3, 4]# enumerate() - 同时获取索引和值
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):print(f"{index}: {fruit}")# zip() - 合并多个序列
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):print(f"{name} is {age} years old")
这些基础知识点是学习 python 的基石,掌握它们将为学习AI和训练AI大模型提供基础。
建议通过实际写代码来巩固这些知识。