T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 4 天:随机数与列表

这是「Python 100 天」系列第 4 天的学习笔记:随机数与列表:石头剪刀布。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

玩家输入 0/1/2 代表石头/剪刀/布,电脑随机出一个,判断胜负。README 知识点:random 模块、列表的索引与追加、索引错误、嵌套列表。

一、random 模块

1
2
3
4
5
6
7
import random

random.randint(0, 2) # 0、1、2 中的一个,两端都包含
random.randrange(0, 3) # 0、1、2,右端不包含(像 range)
random.choice(["a","b"]) # 从序列里随机取一个
random.shuffle(lst) # 原地打乱列表,返回 None
random.random() # [0.0, 1.0) 的浮点数

randint 是闭区间,这一点和 range() 的左闭右开不同,考试常考。随机数并非真随机,是伪随机序列;需要可复现结果时用 random.seed(42)。

二、列表基础

1
2
3
4
5
6
7
fruits = ["apple", "banana", "cherry"]
fruits[0] # 'apple' 索引从 0 开始
fruits[-1] # 'cherry' 负数从末尾数
fruits[0:2] # ['apple','banana'] 切片,左闭右开
len(fruits) # 3
fruits.append("date") # 末尾追加,原地修改
fruits[1] = "blueberry" # 按索引改

越界会抛 IndexError: list index out of range。空列表取 [0] 也报这个错。

嵌套列表就是一个列表里放列表,用两个下标访问:

1
2
matrix = [[1,2,3],[4,5,6]]
matrix[0][2] # 3

三、代码思路

三个 ASCII 图案本身就是三个字符串变量,程序根据选择打印对应图案。

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# ============================================================
# day04/main.py —— 石头剪刀布(Rock Paper Scissors)
# 作用:用户输入 0/1/2,电脑随机出拳,比较后打印胜负。
# 知识点:random.randint()、isdigit() 校验、int() 转换、if/elif 分支
# 运行:python main.py
# ============================================================

# import random:导入标准库 random 模块。
# 标准库随 Python 一起安装,不用 pip;导入后才能用 random.randint 等方法。
import random

# 下面三段都是三引号多行字符串,纯粹是 ASCII 图案,作为变量保存起来,用到时再拼进输出。

rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''

paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''

scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''

# input 返回 str,先不转换,留在 choice 里做“是不是数字”的校验。
choice = (input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissorsn0/1/2:"))

# random.randint(a, b)
# 模块函数。参数 a、b 是整数,返回 a 到 b 之间的随机整数,**两端都包含**。
# 所以 randint(0, 2) 的结果只能是 0、1、2 三个值之一——正好对应石头/剪刀布/剪刀。
computers_choice = random.randint(0,2)

# str.isdigit()
# 字符串方法,无参数。检查字符串是否“全部由数字字符组成”,返回 True / False。
# 它只能挡住 "abc"、"-1"、"1.5" 这类,不会帮你判断范围(范围下面另外查)。
if not choice.isdigit():
print("You've entered an invalid value, try again and choose a number between 0-2.")
else:
# int(x):把字符串转成整数,例如 "2" → 2。转换后才能和 0/1/2 比较大小。
choice = int(choice)
if choice > 2:
print("You've entered an invalid number, try again and choose a number between 0-2.")
# 这里用 or 把三个合法值串起来;其实前面已经排除了 >2,这段等价于“合法输入”。
elif choice == 0 or choice == 1 or choice == 2:
# ---- 先打印用户出的是什么 ----
# f-string 里可以把变量直接嵌进去:{rock} 会把上面存的图案字符串整段插进来。
if choice == 0:
print(f"You chose: Rock {rock}")
elif choice == 1:
print(f"You chose: Paper {paper}")
elif choice == 2:
print(f"You chose: Scissors {scissors}")

# ---- 再按电脑出拳分三种情况判断胜负 ----
if computers_choice == 0:
print(f"The computer chose: Rock {rock}")
if choice == 2:
print("You lose, Rock wins against scissors.")
elif choice == 0:
print("It's a draw!")
else:
print("You win!")

elif computers_choice == 1:
print(f"The computer chose: Paper {paper}")
if choice == 0:
print("You lose, Paper wins against rock.")
# 原仓库这里写成了 choice == 0,应该是 choice == 1(用户出布才算平局)。
# 后果:用户出 1(布)时会落到下面的 else 被判定为“你赢了”,实际应该是平局。
# 这类“复制粘贴后忘了改数字”的 bug 很典型,读别人代码时值得留意。
elif choice == 0:
print("It's a draw!")
else:
print("You win!")

elif computers_choice == 2:
print(f"The computer chose: Scissors {scissors}")
if choice == 1:
print("You lose, Scissors win against paper.")
elif choice == 2:
print("It's a draw!")
else:
print("You win!")

代码走读

  1. choice = input(...):先拿到字符串,不要立刻 int(),因为要先判断它是不是数字。
  2. computers_choice = random.randint(0,2):电脑的选择,闭区间 0~2。
  3. if not choice.isdigit(): —— 校验。str.isdigit() 判断是否全为数字字符,能挡住 "abc"、"1.5"、空串。这一层挡住后再 choice = int(choice) 才不会崩。
  4. if choice > 2: 挡住 9 这类越界数字。
  5. 再用 if/elif 把数字映射成图案打印。
  6. 最后的胜负判断是三层 if computers_choice == 0/1/2,每层里再比较 choice。

这份代码有一个真 bug

电脑出 Paper(1) 的那一段:

1
2
3
4
5
6
7
8
elif computers_choice == 1:
print(f"The computer chose: Paper {paper}")
if choice == 0:
print("You lose, Paper wins against rock.")
elif choice == 0: # ← 重复了同一个条件
print("It's a draw!")
else:
print("You win!")

第二个 elif choice == 0 永远不会执行;当玩家也出 Paper(choice == 1)时,会落到 else 打印 "You win!",而实际应该是平局。正确写法是 elif choice == 1: print("It's a draw!")。

这种"复制粘贴后忘改条件"的 bug,是真实开发里最常见的一类。建议你先把代码原样跑一遍,亲眼看它把平局判成赢,再动手修——这比读十遍教程有用。

运行示例

1
2
3
4
5
What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissors
0/1/2: 0
You chose: Rock
The computer chose: Scissors
You win!

易错点

  1. random.randint(0,2) 写成 randint(0,1),永远出不了剪刀。
  2. 列表索引从 0 开始,但玩家输入习惯是 0/1/2,映射关系要写清楚(这里 0=Rock 是作者自定义的)。
  3. choice.isdigit() 对 "-1" 返回 False,对 "12"(全角数字)却返回 True,边界情况要留意。

动手改

  • 修掉上面的平局 bug。
  • 改成"三局两胜":加计分变量 + while 循环(预习 Day 5)。
  • 用 random.choice(["rock","paper","scissors"]) 改写,避免数字映射,代码更可读。

源文件逐个讲解

2 个文件:main.py(75 行)、README.md(10 行)。这一天的「数据」全写在代码里——三个 ASCII 手势图。

main.py(75 行)

结构:3 个常量 + 1 次输入 + 1 次随机 + 三层 if

1
2
3
4
5
6
7
8
9
10
11
12
import random

rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''...''' # 同样 10 行
scissors = '''...''' # 同样 10 行

三个多行字符串常量占了 30 行。前缀 r 没用,但里面全是反斜杠和引号,如果用转义写会很痛苦——三引号正好绕过。

1
2
choice = (input("What do you choose? Type 0 for Rock, 1 for Paper or 2 for Scissorsn0/1/2:"))
computers_choice = random.randint(0,2)

注意 choice 一开始是字符串,先要过 isdigit() 才能转 int:

1
2
3
4
5
6
if not choice.isdigit():
print("You've entered an invalid value...")
else:
choice = int(choice)
if choice > 2:
print("You've entered an invalid number...")

isdigit() 挡住 "abc"、"-1"、"1.5",choice > 2 挡住 "5"。两道校验缺一不可:没有 isdigit 就 int("abc") 崩,没有 >2 就 [3] 越界(如果用手势列表的话)。

真正的对局逻辑(这是全文件的重点):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
if computers_choice == 0:          # 电脑出石头
if choice == 2:
print("You lose, Rock wins against scissors.")
elif choice == 0:
print("It's a draw!")
else:
print("You win!")

elif computers_choice == 1: # 电脑出布
if choice == 0:
print("You lose, Paper wins against rock.")
elif choice == 0: # ← 这里
print("It's a draw!")
else:
print("You win!")

elif computers_choice == 2: # 电脑出剪刀
if choice == 1:
print("You lose, Scissors win against paper.")
elif choice == 2:
print("It's a draw!")
else:
print("You win!")

第二段里 elif choice == 0 写了两遍,第二个分支永远进不去。结果是:电脑出布、你也出布,程序打印 "You win!"——平局被判成赢。这就是「复制粘贴三份一样的代码」的代价,正确写法是:

1
2
3
4
5
6
if choice == computers_choice:
print("It's a draw!")
elif (choice - computers_choice) % 3 == 1:
print("You win!")
else:
print("You lose.")

一个取模就把 9 种组合压成 3 行(这也是 README 里 Modulo Operator 真正该用的地方)。

另一个小问题:

1
print(f"You chose: Rock {rock}")

f-string 里塞了 10 行字符画,终端上会变成「You chose: Rock」后面跟一个巨大图形,排版很乱。把画和文字分两行打更好。

README.md(10 行)

标题 Day 4 - Randomisation and Python Lists,知识点覆盖 Random Module、Understanding the Offset and Appending Items to Lists、Index Errors、Nesting Lists。

代码里其实一个 list 都没用——三个手势是三个独立变量。README 说的列表是当天课上讲的(random.choice(list) 的用法),这份作业选择了「三个常量 + 三层 if」。

文件间关系

单文件,唯一依赖是标准库 random。这一天是「ASCII 常量内联」的最后一次,Day 07 开始这类常量全部搬到单独的 art.py。

微信收款码 微信
支付宝收款码 支付宝
评论