专为 Java 开发者 整理的《Python编程:从入门到实践》前8章核心内容

以下是专为 Java 开发者 整理的《Python编程:从入门到实践》前8章核心内容,突出与 Java 的差异及 AI 开发常用语法:

第 1 章:环境搭建与基础语法

核心概念

  • 动态类型:无需声明类型,x = 10 自动识别为 int

  • 缩进即语法:用 4 空格缩进代替 {} 代码块

  • 无需分号:行尾不需要 ;

  • 注释:# 单行注释(对比 Java //)

Java vs Python 对照

Java Python 说明
String name = "Alice"; name = "Alice" 无类型声明,无分号
System.out.println("Hi"); print("Hi") 函数而非类方法
name.length() len(name) 内置函数而非方法

字符串操作(AI 中高频使用)

python 复制代码
# f-string 格式化(Python 3.6+,最常用) 
name = "GPT" 
version = 4 
prompt = f"Hello, I am {name} version {version}" # Hello, I am GPT version 4
 # 多行文本(提示词模板常用) 
prompt_template = """ 
你是一个专业助手,请回答: 
{question} 
要求:
{requirement} """

第 2 章:列表(List)

核心概念

  • 类似 Java ArrayList,但可存储不同类型(不推荐混用)

  • 切片语法:list[start:end:step](Python 杀手级特性)

关键操作对比

操作 Java Python
创建 List<String> list = new ArrayList<>(); my_list = [] 或 my_list = ["a", "b"]
追加 list.add("item"); my_list.append("item")
长度 list.size() len(my_list)
获取 list.get(0) my_list[0]
最后元素 list.get(list.size()-1) my_list[-1](负索引)

切片(AI 数据处理核心)

python 复制代码
tokens = ["我", "喜欢", "Python", "编程", "非常", "有趣"] 
# 基础切片 [start:end) 左闭右开 
tokens[1:4] # ['喜欢', 'Python', '编程'] (索引1到3) 
tokens[:3] # ['我', '喜欢', 'Python'] (从头开始) 
tokens[-2:] # ['非常', '有趣'] (最后两个) # 步长(每隔一个取一个) 
tokens[::2] # ['我', 'Python', '非常'] 
tokens[::-1] # 反转列表,['有趣', '非常', ...]

列表推导式(AI 代码必会)

python 复制代码
# Java 风格 
squares = [] for x in range(10): squares.append(x**2) 
# Pythonic 风格(一行) 
squares = [x**2 for x in range(10)] 
# 带条件(过滤偶数) 
evens = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]

第 3 章:条件语句与布尔

语法差异

python 复制代码
# Python:elif 而不是 else if,冒号+缩进 
age = 20 
if age < 13: 
  print("儿童") 
elif age < 20: # 注意是 elif,不是 else if 
  print("青少年") 
else: 
  print("成年人")

布尔运算符(完全不同!)

Java Python 说明
&& and 逻辑与
\|\| or 逻辑或
! not 逻辑非
== == 值相等(字符串内容比较)
equals() == Python 中 == 比较内容,is 比较内存地址

空值检查(AI 处理 API 响应常用)

python 复制代码
response = None # Python 的 null 
if response is not None: # 用 is/not 判断 None 
process(response) 
# 简写:空列表、空字符串、0 都视为 False 
if not response: # 如果 response 为 None/空列表/空字符串 
  print("无数据")

第 4 章:字典(Dictionary)

核心概念

  • 类似 Java HashMap,但语法更简洁

  • JSON 天然对应:AI API 的 Request/Response 都是字典结构

操作对比

操作 Java (HashMap) Python (dict)
创建 Map<String, Object> map = new HashMap<>(); user = {} 或 user = {"name": "Tom", "age": 25}
添加 map.put("key", value); user["email"] = "tom@example.com"
获取 map.get("key") user["key"](不存在会抛异常) user.get("key")(不存在返回 None,推荐)
判断存在 map.containsKey("key") "key" in user

遍历(AI 处理 JSON 必备)

python 复制代码
message = {
    "role": "user",
    "content": "你好",
    "temperature": 0.7
}

# 遍历键值对(类似 Java entrySet)
for key, value in message.items():
    print(f"{key}: {value}")

# 仅遍历键
for key in message.keys():
    print(key)

# 仅遍历值
for value in message.values():
    print(value)

嵌套结构(OpenAI API 格式)

python 复制代码
chat_completion = {
    "id": "chatcmpl-123",
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "Hello!"
            },
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 9,
        "completion_tokens": 12
    }
}

# 访问嵌套数据
content = chat_completion["choices"][0]["message"]["content"]
tokens = chat_completion["usage"]["prompt_tokens"]

第 5 章:用户输入与 while 循环

输入处理(命令行工具常用)

python 复制代码
# input() 返回字符串(类似 Java Scanner.nextLine())
name = input("请输入姓名:")  # 程序会暂停等待输入
age = int(input("请输入年龄:"))  # 需手动转 int(对比 Java nextInt())

# AI 应用:命令行版 ChatBot
while True:
    user_input = input("你:")
    if user_input.lower() == 'quit':
        break
    # 调用 API...
    print(f"AI:处理 {user_input}")

while 循环与 else(Python 特色)

python 复制代码
# 循环正常结束(非 break)时执行 else
attempts = 3
while attempts > 0:
    if try_connect():
        print("连接成功")
        break
    attempts -= 1
else:  # 如果上面被 break 了,这里不会执行
    print("3次尝试均失败")

第 6 章:函数

定义对比

python 复制代码
# Python:def 关键字,无需返回类型声明,无大括号
def greet(name, greeting="Hello"):  # 默认参数值
    """函数的文档字符串(docstring),说明用途"""
    return f"{greeting}, {name}!"

# 调用
print(greet("Alice"))              # Hello, Alice!
print(greet("Bob", "Hi"))          # Hi, Bob!
print(greet(name="Carol"))         # 关键字参数(类似 Java 具名参数)

可变参数(AI 工具函数常用)

python 复制代码
# *args:任意数量的位置参数(类似 Java 可变参数 Object... args)
def sum_all(*numbers):
    return sum(numbers)

result = sum_all(1, 2, 3, 4)  # 10

# **kwargs:任意数量的关键字参数(接收为字典)
def build_profile(**user_info):
    return user_info

profile = build_profile(name="Tom", age=25, city="Beijing")
# {'name': 'Tom', 'age': 25, 'city': 'Beijing'}

# 组合使用(常见于 AI 函数封装)
def call_api(endpoint, *args, **kwargs):
    """args 放路径参数,kwargs 放查询参数"""
    pass

Lambda 表达式(简单函数)

python 复制代码
# Java:(a, b) -> a + b
# Python:
add = lambda a, b: a + b

# 实际场景:排序
users = [{"name": "Tom", "age": 25}, {"name": "Jerry", "age": 20}]
users.sort(key=lambda x: x["age"])  # 按年龄排序

第 7 章:类与面向对象

基础类定义

python 复制代码
class Dog:
    # 类属性(类似 Java static,但所有实例共享)
    species = "Canis familiaris"
    
    # 构造方法(对比 Java 构造函数)
    def __init__(self, name, age):  # self 类似 Java 的 this,但必须显式写第一个参数
        self.name = name            # 实例属性
        self.age = age
    
    # 实例方法
    def bark(self):
        return f"{self.name} says woof!"
    
    # 字符串表示(类似 Java toString())
    def __str__(self):
        return f"Dog(name={self.name}, age={self.age})"
    
    # 官方字符串表示(用于调试)
    def __repr__(self):
        return f"Dog('{self.name}', {self.age})"
# 使用
my_dog = Dog("Buddy", 3)
print(my_dog.name)    # Buddy
print(my_dog.bark())  # Buddy says woof!
print(my_dog)         # Dog(name=Buddy, age=3)

继承(AI 中常用:自定义 Exception、数据处理器)

python 复制代码
class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError("Subclass must implement")

class Cat(Animal):  # 继承
    def __init__(self, name, color):
        super().__init__(name)  # 调用父类构造(对比 Java super())
        self.color = color
    
    def speak(self):  # 重写
        return f"{self.name} says meow!"

# 多态
animals = [Dog("Buddy", 3), Cat("Kitty", "white")]
for animal in animals:
    print(animal.speak())  # 自动调用各自实现

模块与导入(项目结构)

python 复制代码
# 文件结构:
# project/
#   main.py
#   utils/
#     __init__.py  # 空文件,标记为包(类似 Java package)
#     helpers.py

# helpers.py 中
def format_prompt(text):
    return text.strip()

# main.py 中导入
from utils.helpers import format_prompt  # 类似 Java import
import utils.helpers as helpers          # 别名(类似 Java import static)

# 或使用(不推荐,污染命名空间)
from utils.helpers import *

第 8 章:文件与异常(AI 数据处理核心)

文件读写(对比 Java 繁琐的 IO 流)

python 复制代码
# 读取整个文件(自动关闭,类似 Java try-with-resources)
with open('data.txt', 'r', encoding='utf-8') as file:
    content = file.read()  # 整个文件读成字符串

# 逐行读取(处理大文件,不占用内存)
with open('data.txt', 'r') as file:
    for line in file:  # 直接迭代,无需 BufferedReader
        print(line.strip())  # strip() 去掉换行符

# 写入文件
with open('output.txt', 'w') as file:
    file.write("Hello, Python!\n")
    file.write("第二行")

# 追加模式
with open('log.txt', 'a') as file:
    file.write("日志记录\n")

JSON 处理(AI 工程天天用)

python 复制代码
import json

# Python 对象 → JSON 字符串(序列化)
data = {
    "model": "gpt-4",
    "messages": [{"role": "user", "content": "Hello"}],
    "temperature": 0.7
}

json_str = json.dumps(data, ensure_ascii=False, indent=2)
print(json_str)
# {
#   "model": "gpt-4",
#   "messages": [...]
# }

# JSON 字符串 → Python 对象(反序列化,AI API 响应处理)
response_str = '{"id": "123", "choices": [{"text": "Hi"}]}'
response_obj = json.loads(response_str)
print(response_obj["choices"][0]["text"])  # Hi

# 直接读写 JSON 文件
with open('config.json', 'r') as f:
    config = json.load(f)  # 对比 json.loads(读字符串)vs json.load(读文件)

异常处理(对比 Java try-catch)

python 复制代码
try:
    result = 10 / 0
    with open('not_exist.txt') as f:
        content = f.read()
except ZeroDivisionError as e:  # 特定异常(类似 Java catch 特定类型)
    print(f"除零错误: {e}")
except FileNotFoundError:
    print("文件不存在")
except Exception as e:          # 通用异常(类似 Java Exception e)
    print(f"未知错误: {e}")
else:
    print("无异常时执行(类似 Java try 正常结束)")
finally:
    print("无论有无异常都执行(清理资源)")

# 自定义异常(继承 Exception)
class APIError(Exception):
    def __init__(self, message, status_code):
        super().__init__(message)
        self.status_code = status_code

# 抛出
raise APIError("模型调用失败", 500)  # 对比 Java throw new Exception()

🎯 Java 开发者速成要点

必须改变的思维习惯

  1. 忘记分号和大括号:用缩进(4空格)表示代码块

  2. 忘记类型声明:但要养成写类型提示的习惯(Python 3.5+): def process_data(data: list[str]) -> dict: # 提示输入输出类型 pass

  3. 忘记 getter/setter:Python 直接访问属性,需要时用 @property 装饰器

  4. 掌握切片:[::-1] 反转、[:10] 前10个,比 Java subList 简洁得多

AI 开发高频模式

python 复制代码
# 模式 1:处理 API 列表响应
responses = api_call()  # 返回列表
for item in responses:
    if item.get("finish_reason") == "stop":
        process(item["message"]["content"])

# 模式 2:批量处理(列表推导)
texts = [clean_text(t) for t in raw_texts if t is not None]

# 模式 3:安全获取嵌套值(避免 NullPointerException)
# Java: Optional.ofNullable(obj).map(...).orElse(default)
# Python: dict.get() 链式调用
content = response.get("choices", [{}])[0].get("message", {}).get("content", "默认值")

掌握这 8 章内容,你就可以看懂并修改 90% 的 AI 项目 Python 代码了。

相关推荐
规划酱2 小时前
Arcgis中pip安装ezdxf部分GIS有pyparsing安装失败的情况处理
python·arcgis·pip·规划酱
ThreeAu.2 小时前
windows篇| Windows进程与命令行
windows
witAI2 小时前
**AI漫剧一键生成2025指南,解锁零门槛动画创作新体验*
人工智能·python
ktoking2 小时前
Stock Agent AI 模型的选股器实现 [七]
人工智能·python·django
一嘴一个橘子2 小时前
idea Could not autowire. No beans of ‘xxxMapper‘ type found
java
海边的Kurisu2 小时前
苍穹外卖日记 | Day9 用户端历史订单模块、商家端订单管理模块、用户下单功能优化
java·苍穹外卖
nbsaas-boot2 小时前
架构设计怎么做:一套可复用、可落地的方法论
java·开发语言·微服务
骆驼爱记录2 小时前
Word表格题注自动设置全攻略
开发语言·c#·自动化·word·excel·wps·新人首发
wbs_scy2 小时前
C++:智能指针完全指南(原理、用法与避坑实战,从 RAII 到循环引用)
开发语言·c++·算法