Python-循环与字符串
·
今天学循环——让程序重复执行任务,同时把字符串从头到尾学透。
一、为什么需要循环?
场景:打印 1 到 100、遍历每个用户名、重复猜数字直到猜对……
如果不用循环,只能一行一行写 100 次 print,循环让代码简洁高效。
二、while 循环
2.1 语法
while 条件:
循环体(需要重复执行的代码)
执行流程:
1. 判断条件是否为 True
2. 如果 True → 执行循环体 → 回到步骤 1
3. 如果 False → 跳出循环,继续执行后面的代码
2.2 基本示例
count = 0
while count < 5:
print(count)
count += 1
# 输出:0 1 2 3 4
2.3 死循环(无限循环)
条件永远为 True 时,循环不会结束:
# while True:
# print("永远执行") # 慎用!需要 break 跳出
2.4 应用:用户输入验证
password = ""
while password != "123456":
password = input("请输入密码:")
print("密码正确,欢迎!")
三、for 循环
3.1 语法
for 临时变量 in 可迭代对象:
循环体
可迭代对象:字符串、列表、元组、字典、range 等。
3.2 遍历 range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8(步长为2)
print(i)
3.3 遍历字符串
for ch in "Python":
print(ch)
# P y t h o n(每个字符一行)
3.4 for-else
for i in range(5):
print(i)
else:
print("循环正常结束") # 没有被 break 打断才执行
四、break 与 continue
| 关键字 | 作用 | 类比 |
|---|---|---|
break |
立即跳出整个循环 | 考试中途交卷离开 |
continue |
跳过本次,进入下一次 | 跳过一道题做下一道 |
# break 示例
for i in range(10):
if i == 5:
break
print(i) # 0 1 2 3 4
# continue 示例
for i in range(5):
if i == 2:
continue
print(i) # 0 1 3 4(跳过了2)
pass 占位符
if score >= 60:
pass # 暂时什么都不做,占个位置
else:
print("不及格")
五、while vs for 怎么选?
| 场景 | 推荐 |
|---|---|
| 知道要循环多少次 | for + range |
| 遍历序列(列表、字符串) | for |
| 不知道循环多少次,靠条件控制 | while |
| 用户输入直到满足条件 | while |
六、字符串完整知识
6.1 字符串特性
- 有序:每个字符有下标(索引)
- 不可变:不能修改某个位置的字符
- 可迭代:可以用 for 遍历
6.2 创建方式
s1 = 'hello'
s2 = "world"
s3 = '''多行
字符串'''
s4 = str(123) # '123'
s5 = r"C:\new\text" # 原始字符串,\n 不会转义
6.3 索引与切片
s = "Python"
# 索引(从0开始,负数从末尾数)
print(s[0]) # P
print(s[-1]) # n
# 切片 [start:end:step] 左闭右开
print(s[0:3]) # Pyt
print(s[:3]) # Pyt(省略start从0开始)
print(s[3:]) # hon(省略end到末尾)
print(s[::2]) # Pto(步长2)
print(s[::-1]) # nohtyP(反转)
6.4 字符串拼接与重复
print("hello" + " " + "world") # hello world
print("ab" * 3) # ababab
6.5 成员检测
print("py" in "python") # True
print("x" not in "hello") # True
print(len("hello")) # 5
6.6 常用字符串方法
| 方法 | 作用 | 示例 |
|---|---|---|
upper() / lower() |
大小写转换 | "Hi".upper() → "HI" |
capitalize() |
首字母大写 | "hello".capitalize() |
title() |
每个单词首字母大写 | |
strip() |
去除首尾空白 | " abc ".strip() |
lstrip() / rstrip() |
去左/右空白 | |
split(sep) |
分割为列表 | "a,b,c".split(",") |
join(iterable) |
拼接 | ",".join(["a","b"]) |
replace(old, new) |
替换 | "abc".replace("a","A") |
find(sub) |
查找子串位置 | 找不到返回 -1 |
index(sub) |
查找子串位置 | 找不到报 ValueError |
count(sub) |
统计出现次数 | |
startswith() / endswith() |
前缀/后缀判断 | |
isdigit() / isalpha() / isalnum() |
字符类型判断 |
email = " User@Example.COM "
email = email.strip().lower()
parts = email.split("@")
print(parts) # ['user', 'example.com']
6.7 编码与解码
s = "你好"
b = s.encode("utf-8")
print(b) # b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(b.decode("utf-8")) # 你好
6.8 字符串不可变
s = "hello"
# s[0] = "H" # TypeError!
# 正确"修改"方式
s = "H" + s[1:] # 切片拼接
s = s.replace("h", "H") # replace 返回新字符串
七、重点易错点
- while 循环别忘了更新条件变量,否则死循环
- 切片左闭右开:
s[0:3]取下标 0、1、2 - 字符串方法返回新字符串,原字符串不变
split()不带参数会按任意空白分割
八、练习题
基础题
1. 用 for 循环打印 1~100 的所有偶数。
2. 用 while 循环实现:用户输入数字,输入 0 时结束,输出所有输入数字的和。
3. 用户输入字符串,统计其中字母、数字、空格的个数。
4. 将 " hello,world,python " 去空格、按逗号分割、转大写、用 | 连接。
5. 判断输入字符串是否为回文(正读反读相同,如 level)。
进阶题
6. 打印九九乘法表(格式化对齐)。
7. 密码强度检测:长度≥8,包含大写、小写、数字各至少一个。
8. 解析 "name=张三&age=20&city=北京" 为字典。
参考答案
点击展开参考答案
# 1.
for i in range(2, 101, 2):
print(i, end=" ")
# 2.
total = 0
while True:
n = int(input("输入数字(0结束):"))
if n == 0: break
total += n
print("总和:", total)
# 3.
s = input("输入字符串:")
letters = sum(1 for c in s if c.isalpha())
digits = sum(1 for c in s if c.isdigit())
spaces = sum(1 for c in s if c.isspace())
print(f"字母:{letters} 数字:{digits} 空格:{spaces}")
# 4.
s = " hello,world,python "
result = "|".join(s.strip().split(",")).upper()
print(result)
# 5.
s = input("输入:").strip()
print("是回文" if s == s[::-1] else "不是回文")
# 6. 九九乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print(f"{j}×{i}={i*j}", end="\t")
print()
# 7.
pwd = input("输入密码:")
ok = len(pwd) >= 8 and any(c.isupper() for c in pwd) \
and any(c.islower() for c in pwd) and any(c.isdigit() for c in pwd)
print("合格" if ok else "不合格")
# 8.
query = "name=张三&age=20&city=北京"
d = dict(item.split("=") for item in query.split("&"))
print(d)
更多推荐
所有评论(0)