Python 快速入门指南(AI工程师必备)

1. Python 基础语法

2.1 变量与数据类型

2.1.1 变量的定义与命名规则
# 变量定义
name = "Alice"
age = 25
height = 1.68
is_student = True

# 打印变量值
print(name)
print(age)
print(height)
print(is_student)

name = "张三"
print(name)

# 变量命名规则
# 1. 变量名只能包含字母、数字和下划线
# 2. 变量名不能以数字开头
# 3. 变量名不能是 Python 关键字
# 4. 变量名应具有描述性

⚠️ 注意:name = "Alice' 是错误写法(引号不匹配),会导致 SyntaxError


2.1.2 数据类型
# 数字类型
num1 = 10        # 整数 (int)
num2 = 3.14      # 浮点数 (float)

# 字符串类型
name = "Alice"           # 字符串 (str)
message = 'Hello, world!' # 单引号也可

# 布尔类型
is_student = True   # 布尔值 (bool)
is_working = False

# 使用 type() 函数查看数据类型
print(type(num1))        # <class 'int'>
print(type(num2))        # <class 'float'>
print(type(name))        # <class 'str'>
print(type(is_student))  # <class 'bool'>

💡 布尔值首字母必须大写:True / False,小写会报错。


2.1.3 类型转换
# 将字符串转换为整数
num_str = "123"
num_int = int(num_str)
print(num_int)  # 123

# 将整数转换为字符串
num_int = 456
num_str = str(num_int)
print(num_str)  # "456"

# 将浮点数转换为整数(会丢失小数部分)
num_float = 3.14
num_int = int(num_float)
print(num_int)  # 3

⚠️ 注意:int("3.14") 会报 ValueError,需先转为 float


2.2 运算符与表达式

2.2.1 算术运算符
# 加法
result = 10 + 5
print(result)  # 15

# 减法
result = 10 - 5
print(result)  # 5

# 乘法
result = 10 * 5
print(result)  # 50

# 除法(结果为浮点数)
result = 10 / 5
print(result)  # 2.0

# 取整除(向下取整)
result = 10 // 3
print(result)  # 3

# 取余
result = 10 % 3
print(result)  # 1

# 幂运算
result = 2 ** 3
print(result)  # 8

2.2.2 比较运算符
# 等于
result = 10 == 5
print(result)  # False

# 不等于
result = 10 != 5
print(result)  # True

# 大于
result = 10 > 5
print(result)  # True

# 小于
result = 10 < 5
print(result)  # False

# 大于等于
result = 10 >= 5
print(result)  # True

# 小于等于
result = 10 <= 5
print(result)  # False

2.3 输入与输出

2.3.1 input() 函数
# 获取用户输入
name = input("请输入你的名字: ")
print("你好," + name + "!")

💡 input() 返回的始终是字符串类型,需用 int() 等转换。


2.3.2 print() 函数
# 打印字符串
print("Hello, world!")

# 打印变量值
name = "Alice"
age = 25
print("姓名:", name)
print("年龄:", age)

# 格式化输出(f-string,推荐)
print(f"姓名: {name}, 年龄: {age}")

2. Python 控制结构

2.1 条件语句

age = 20

if age >= 18:
    print("成年人")
elif age >= 13:
    print("青少年")
else:
    print("儿童")

💡 Python 使用缩进(通常 4 个空格)定义代码块,无大括号。


2.2 循环控制语句

2.2.1 for 循环
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(fruit)
2.2.2 while 循环
count = 0
while count < 5:
    print(count)
    count += 1
2.2.3 循环控制语句
for i in range(10):
    if i == 3:
        continue  # 跳过本次循环
    if i == 7:
        break     # 退出整个循环
    print(i)

3. Python 数据结构

3.1 列表和列表操作

# 创建列表
fruits = ["apple", "banana", "cherry"]

# 访问元素
print(fruits[0])  # apple

# 修改元素
fruits[1] = "orange"

# 添加元素
fruits.append("mango")

# 删除元素
fruits.remove("cherry")

print(fruits)  # ['apple', 'orange', 'mango']

3.2 元组、字典和集合操作

3.2.1 元组(不可变)
coordinates = (10, 20)
print(coordinates[0])  # 10
# coordinates[0] = 30  # ❌ 报错!元组不可修改
3.2.2 字典(键值对)
person = {"name": "Alice", "age": 25}

print(person["name"])  # Alice

# 修改/添加
person["age"] = 26
person["city"] = "Beijing"

print(person)  # {'name': 'Alice', 'age': 26, 'city': 'Beijing'}
3.2.3 集合(无序、唯一)
numbers = {1, 2, 3, 4, 5}
numbers.add(6)
numbers.remove(3)
print(numbers)  # {1, 2, 4, 5, 6}

4. Python 函数和模块

4.1 Python 函数基础

def greet(name):
    """返回问候语"""
    return f"Hello, {name}!"

print(greet("Alice"))  # Hello, Alice!

def add(a, b):
    return a + b

print(add(5, 3))  # 8

4.2 Python 模块介绍

# 导入整个模块
import math
print(math.sqrt(16))  # 4.0

# 导入特定函数
from random import randint
print(randint(1, 10))  # 随机输出 1~10 的整数

5. Python 面向对象编程

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, I'm {self.name}, {self.age} years old."

# 创建对象
person = Person("Alice", 25)
print(person.greet())  # Hello, I'm Alice, 25 years old.

# 继承示例
class Student(Person):
    def __init__(self, name, age, grade):
        super().__init__(name, age)
        self.grade = grade

student = Student("Bob", 20, "A")
print(student.greet())  # Hello, I'm Bob, 20 years old.

6. Python 数据处理

6.1 NumPy

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr.mean())   # 3.0
print(arr * 2)      # [2 4 6 8 10]

6.2 Pandas

import pandas as pd

data = {'Name': ['Alice', 'Bob'], 'Age': [25, 20]}
df = pd.DataFrame(data)
print(df)
#     Name  Age
# 0  Alice   25
# 1    Bob   20

6.3 Matplotlib

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]
y = [10, 20, 25, 30]

plt.plot(x, y)
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.title('示例折线图')
plt.show()

✅ 总结

本教程覆盖了 Python 编程的核心知识点:

  • 基础语法:变量、类型、运算、输入输出
  • 程序控制:条件、循环
  • 数据结构:列表、元组、字典、集合
  • 函数与模块:代码复用与组织
  • 面向对象:类与继承
  • 数据处理:NumPy、Pandas、Matplotlib(AI/数据分析基石)

🐍 建议:动手敲一遍所有代码,修改参数观察结果,是掌握 Python 最有效的方式!


原创内容,转载请注明出处。关注我,获取更多 Python 实战教程!

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐