Python编程:从入门到实践(第3版)

> 📖 **一起读书吧!** 加入《Python编程:从入门到实践》共读营 👉 [点击参加](https://mp.weixin.qq.com/s/ehe2vMrfAFscRLqbM9TF-g)

本讲内容

  • 变量是什么(变量是标签,不是盒子)
  • 字符串:大小写、空白、制表符、f-string
  • 数字:整数、浮点数、下划线写法
  • 注释:单行注释、多行docstring

学习目标

掌握Python最基础的数据和文本操作 🔢


1. 变量:给数据贴标签

1
2
3
4
5
message = "Hello Python World!"
print(message)

message = "Hello Python Crash Course World!"
print(message)

变量是标签,不是盒子。一个变量可以反复赋值,每次都指向新值。

官方文档:Variables — 变量直接赋值使用,不需要声明。

变量命名规则

1
2
3
4
5
6
7
8
9
10
# ✅ 合法
user_name = "晚枫"
_age = 30
isValid = True
MAX_SIZE = 100 # 全大写 = 常量约定

# ❌ 非法(会报错)
# 2names = "test" # 数字不能在开头
# user-name = "test" # 不能用连字符
# user name = "test" # 不能有空格

官方文档:Identifiers and keywords — Python标识符规则。

2. 字符串

创建字符串

1
2
3
4
5
6
name = "程序员晚枫"     # 双引号
name = '也是可以的' # 单引号(等价)

# 引号嵌套
message = 'I am a "programmer"'
print(message) # I am a "programmer"

字符串方法(大小写)

1
2
3
4
5
name = "eric matthes"

print(name.title()) # Eric Matthes(每个单词首字母大写)
print(name.upper()) # ERIC MATTHES(全大写)
print(name.lower()) # eric matthes(全小写)

官方文档:str.title()str.upper()str.lower()

字符串中的空白

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 制表符 \t 和换行符 \n
print("Languages:\n\tPython\n\tJavaScript\n\tGo")
# Languages:
# Python
# JavaScript
# Go

# 去除空白(strip系列,第3版新增两个方法)
s = " python "
print(s.strip()) # "python"(去除两端空白)
print(s.lstrip()) # "python "(去左边)
print(s.rstrip()) # " python"(去右边)

# removeprefix/removesuffix(第3版新增)
url = "https://example.com"
print(url.removeprefix("https://")) # "example.com"
filename = "spam.txt"
print(filename.removesuffix(".txt")) # "spam"

官方文档:str.strip()str.removeprefix()str.removesuffix()

字符串和数字的转换

1
2
3
4
5
6
age = 25
print(f"I am {age} years old.") # I am 25 years old.

# 避免类型错误
age = "25" # 如果age是字符串,"I am " + age会成功
# age = 25 # 整数类型时,"I am " + age 会报TypeError!

3. 数字

整数运算

1
2
3
4
5
6
7
8
9
10
11
print(2 + 3)     # 5
print(3 - 2) # 1
print(2 * 3) # 6
print(3 / 2) # 1.5(永远返回浮点数!)
print(3 // 2) # 1(整除,向下取整)
print(3 % 2) # 1(取余)
print(3 ** 2) # 9(幂运算)

# 括号优先级
print(2 + 3 * 4) # 14
print((2 + 3) * 4) # 20

官方文档:3.1.1. Numbers/ 永远返回浮点数。

下划线写法(大数字可读性)

1
2
universe_age = 14_000_000_000
print(universe_age) # 14000000000

浮点数

1
2
3
4
5
6
print(0.1 + 0.1)       # 0.2
print(0.2 + 0.1) # 0.30000000000000004(浮点精度问题!)

# 整数和浮点混合运算,结果为浮点数
print(4 / 2) # 2.0
print(1 + 2.0) # 3.0

4. 注释

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 单行注释
print("Hello") # 行尾注释

"""
多行字符串作为注释(docstring),
通常用于模块、函数、类的说明。
"""

'''
也可以用单引号
'''

def greet(name):
"""
向指定的人打招呼。

Args:
name (str): 名字

Returns:
None
"""
print(f"Hello, {name}!")

官方文档:Comments in Python — 注释以 # 开头到行尾。


📚 官方文档参考


🎓 AI 编程实战课程

程序员晚枫专注AI编程培训,通过 《30讲 · AI编程训练营》,让小白也能用AI做出实际项目。