1Learning Python(第5版)

Python入门

走近Python

Python特性运行方式交互模式程序执行

🎯 AI 时代的学习建议:不要只读理论。理解这一章的设计动机(为什么需要这个概念?)和边界条件(什么情况下会失效?)。当 AI 生成的代码涉及这些概念时,你能判断它是否用对了场景。AI 能帮你总结内容,但无法替代你亲手阅读、思考、建立直觉的过程。

第1章:Python入门(A Python Tour)

一、导读

1.1 本章学习目标

第1章是《Learning Python》的开篇,带你走进 Python 的世界。Python 以其简洁优雅的语法和强大的生态系统,成为世界上最受欢迎的编程语言之一。本章将帮助你建立对 Python 语言的整体认知。

本章的核心学习目标包括:

  • 理解 Python 的设计哲学:掌握"Pythonic"编程的核心理念。
  • 了解 Python 的运行方式:掌握交互式模式、脚本模式和模块模式。
  • 理解 Python 的类型系统:动态类型、强类型、鸭子类型。
  • 掌握 Python 的代码组织:缩进、注释、编码规范。
  • 了解 Python 的应用领域:Web 开发、数据科学、自动化、AI 等。

1.2 为什么第一章如此重要

Python 的设计哲学是"优雅、明确、简单"。理解这些理念,不仅能帮你写出更好的 Python 代码,还能培养良好的编程习惯。Python 之禅(The Zen of Python)总结了这些理念:

python
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.

1.3 核心问题引导

Python 的动态类型和静态类型语言有什么本质区别?

Python 的缩进为什么如此重要?

Python 的解释器是如何工作的?

Python 适合什么场景?不适合什么场景?

如何编写"Pythonic"的代码?


二、核心概念详解

2.1 Python 的运行方式

2.1.1 交互式模式

python
>>> 2 + 3
5
>>> print("Hello, World!")
Hello, World!
>>> x = 42
>>> x
42

2.1.2 脚本模式

python
# hello.py
print("Hello, World!")
name = input("What is your name? ")
print(f"Hello, {name}!")
bash
$ python hello.py

2.1.3 Python 的执行过程

Python 是解释型语言,但它的执行过程比简单的"逐行解释"更复杂:

源代码(.py 文件)→ 字节码(.pyc 文件)→ Python 虚拟机(PVM)执行

字节码是平台无关的中间表示,PVM 逐条解释执行字节码

2.2 Python 的类型系统

2.2.1 动态类型

Python 是动态类型语言——变量的类型在运行时确定,不需要声明。

python
# 变量不需要声明类型
x = 42        # x 是整数
x = "hello"   # x 现在是字符串(类型变了!)
x = [1, 2, 3] # x 现在是列表

# 同一个变量可以指向不同类型的对象
def demo(x):
    print(type(x), x)

demo(42)       # <class 'int'> 42
demo("hello")  # <class 'str'> hello
demo([1, 2])   # <class 'list'> [1, 2]

2.2.2 强类型

Python 是强类型语言——不会隐式地进行不安全的类型转换。

python
# Python 不会隐式转换
"1" + 2  # TypeError: can only concatenate str (not "int") to str

# 需要显式转换
int("1") + 2    # 3
str(1) + "2"    # "12"

# 对比 JavaScript(弱类型)
# "1" + 2 = "12"(JavaScript 会隐式转换)

2.2.3 鸭子类型

Python 使用鸭子类型——不关心对象的类型,只关心对象是否有需要的方法。

python
# 鸭子类型
class Duck:
    def quack(self):
        return "Quack!"

class Person:
    def quack(self):
        return "I'm quacking like a duck!"

def make_it_quack(thing):
    print(thing.quack())

make_it_quack(Duck())    # Quack!
make_it_quack(Person())  # I'm quacking like a duck!
# 不关心类型,只关心是否有 quack 方法

2.3 Python 的内置类型

2.3.1 数字

python
# 整数(任意精度)
x = 42
y = 10 ** 100  # 大整数

# 浮点数
pi = 3.14159
e = 2.71828

# 复数
z = 3 + 4j
print(z.real, z.imag)  # 3.0 4.0

# 布尔值
True, False
bool(0)    # False
bool("")   # False
bool([])   # False
bool(None) # False
bool(1)    # True

2.3.2 字符串

python
# 字符串
s = "Hello, World!"
s = 'Hello, World!'  # 单引号和双引号等价

# 多行字符串
text = """This is
a multi-line
string."""

# 原始字符串(不处理转义)
path = r"C:\Users\Alice\Documents"

# f-string(格式化字符串,Python 3.6+)
name = "Alice"
age = 30
print(f"My name is {name} and I'm {age} years old.")
print(f"Next year I'll be {age + 1}.")

# 字符串操作
"hello".upper()        # "HELLO"
"HELLO".lower()        # "hello"
"hello world".title()  # "Hello World"
"  hello  ".strip()    # "hello"
"hello".replace("l", "L")  # "heLLo"
"hello world".split()  # ["hello", "world"]
", ".join(["a", "b", "c"])  # "a, b, c"
"hello".startswith("he")    # True
"hello".endswith("lo")      # True
"hello".find("ll")          # 2

2.3.3 列表

python
# 列表(可变序列)
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# 访问元素
numbers[0]    # 1
numbers[-1]   # 5(最后一个)
numbers[1:3]  # [2, 3](切片)

# 修改
numbers[0] = 10       # [10, 2, 3, 4, 5]
numbers.append(6)     # [10, 2, 3, 4, 5, 6]
numbers.insert(0, 0)  # [0, 10, 2, 3, 4, 5, 6]
numbers.pop()         # 6
numbers.remove(10)    # [0, 2, 3, 4, 5]

# 列表操作
len(numbers)          # 5
sorted(numbers)       # [0, 2, 3, 4, 5]
reversed(numbers)     # <list_reverseiterator>
list(reversed(numbers))  # [5, 4, 3, 2, 0]

# 列表推导式
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]

2.3.4 字典

python
# 字典(键值对)
person = {"name": "Alice", "age": 30, "city": "NYC"}

# 访问
person["name"]          # "Alice"
person.get("email", "N/A")  # "N/A"(不存在时返回默认值)

# 修改
person["email"] = "alice@example.com"
person.update({"age": 31, "city": "LA"})
del person["email"]

# 遍历
for key in person:
    print(key, person[key])

for key, value in person.items():
    print(key, value)

# 字典推导式
squares = {x: x**2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

2.4 控制流

python
# if/elif/else
x = 42
if x > 0:
    print("positive")
elif x == 0:
    print("zero")
else:
    print("negative")

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

for item in [1, 2, 3]:
    print(item)

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

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

# break 和 continue
for i in range(10):
    if i == 3:
        continue  # 跳过 3
    if i == 7:
        break     # 到 7 停止
    print(i)  # 0, 1, 2, 4, 5, 6

2.5 函数

python
# 基本函数
def greet(name):
    return f"Hello, {name}!"

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

power(3)     # 9
power(3, 3)  # 27

# 关键字参数
def create_user(name, age, city="Unknown"):
    return {"name": name, "age": age, "city": city}

create_user("Alice", 30, city="NYC")

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

total(1, 2, 3, 4)  # 10

# 关键字可变参数
def config(**kwargs):
    return kwargs

config(host="localhost", port=8080)  # {"host": "localhost", "port": 8080}

# Lambda 表达式
square = lambda x: x ** 2
square(5)  # 25

# 高阶函数
numbers = [1, 2, 3, 4, 5]
list(map(lambda x: x * 2, numbers))      # [2, 4, 6, 8, 10]
list(filter(lambda x: x > 3, numbers))   # [4, 5]

三、实战案例

3.1 FizzBuzz

python
def fizzbuzz(n):
    for i in range(1, n + 1):
        if i % 15 == 0:
            print("FizzBuzz")
        elif i % 3 == 0:
            print("Fizz")
        elif i % 5 == 0:
            print("Buzz")
        else:
            print(i)

fizzbuzz(20)

3.2 词频统计

python
from collections import Counter

def word_frequency(text):
    words = text.lower().split()
    # 去除标点
    words = [w.strip(".,!?;:\"'()[]{}") for w in words]
    return Counter(words)

text = """
The quick brown fox jumps over the lazy dog.
The dog barked at the fox. The fox ran away.
"""

freq = word_frequency(text)
for word, count in freq.most_common(5):
    print(f"{word}: {count}")

四、本章小结

第1章带你走进了 Python 的世界:

Python 的设计哲学:优雅、明确、简单。

动态类型:变量不需要声明类型,类型在运行时确定。

强类型:不会隐式进行不安全的类型转换。

丰富的内置类型:数字、字符串、列表、字典、元组、集合。

简洁的控制流:if/for/while,配合缩进组织代码。

Python 是一门"入门容易,精通困难"的语言。本章只是开始,后续章节将深入讲解每个主题。


五、思考与练习

思考题

Python 的动态类型有哪些优缺点?

为什么 Python 使用缩进来组织代码?

列表推导式和 map/filter 哪个更"Pythonic"?

鸭子类型的优势是什么?有什么风险?

Python 适合什么场景?不适合什么场景?

编程练习

实现一个简单的计算器:支持加减乘除。

实现词频统计:读取文件,统计每个单词的出现次数。

实现一个简单的待办事项管理器:支持添加、删除、列出待办事项。


1/8Pyth
0%