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

Python 100 天 · 第 14 天:项目实战:Higher Lower 猜粉丝数

这是「Python 100 天」系列第 14 天的学习笔记:项目实战:Higher Lower 猜粉丝数。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

屏幕给出两个名人(A、B)及其简介,玩家猜谁粉丝更多。猜对得分、继续;猜错结束。README 知识点:字典数据、过程(函数)、条件判断——本质是第一个"数据驱动"的程序。

一、数据长什么样

game_data.py 里是一个列表套字典的结构,50 条记录:

1
2
3
4
5
6
{
'name': 'Instagram',
'follower_count': 346, # 单位:百万
'description': 'Social media platform',
'country': 'United States'
}

这就是真实 API 返回值的典型形态。把它和 Day 9 的拍卖记录对比:结构完全一样,只是字段更多。数据结构一旦定好,代码就变成"从数据里取字段 + 比较"。

二、返回多个值

1
2
3
def profile():
...
return compare, follower_count

调用端 profile_a, followers_a = profile() 一次接两个值(元组解包)。这比返回一个字典更轻,但要靠调用者记住顺序。

三、random.randint(0, 49)

作者用下标随机取记录。这依赖"数据正好 50 条"这个隐含事实;一旦数据增删,就会 IndexError。更稳的写法是:

1
item = random.choice(data)

choice 自动适配长度,也不需要知道有多少条。

代码全文

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
# ============================================================
# day14/main.py —— 谁粉丝更多(Higher Lower)
# 作用:每次给出两位名人,你猜谁的粉丝多;猜对继续,猜错结束并结算得分。
# 知识点:把数据放进 game_data.py、函数返回多个值(元组解包)、
# 字典按 key 取值、while + 布尔标志、递归重开
# 运行:python main.py(clear 来自 Replit)
# ============================================================

from art import logo, vs
# 从 game_data.py 导入 data:它是 50 条字典组成的列表,
# 每条形如 {"name": "Instagram", "follower_count": 346, "description": "…", "country": "…"}
from game_data import data
from replit import clear
import random


# 随机取一条名人资料,把“描述文字”和“粉丝数”一起交回去。
# 无参数。返回值:一个元组 (compare, follower_count)
# compare——拼好的介绍串,例如 "Instagram, a Social media platform, from United States."
# follower_count——粉丝数(单位百万,int)
def profile():
# data 有 50 条(下标 0–49),所以 randint(0, 49);randint 两端都包含。
random_number = random.randint(0, 49)
# 先用下标取出那一条字典,再用键取值——两步可以合成一步:data[random_number]['name']
name = data[random_number]['name']
follower_count = data[random_number]['follower_count']
description = data[random_number]['description']
country = data[random_number]['country']
compare = (f"{name}, a {description}, from {country}.")
# return 多个值,本质是返回一个元组;调用方可以用 a, b = profile() 一次接住。
return compare, follower_count


def higher_lower():
# 元组解包:函数返回 2 个值,就用 2 个变量接。
profile_a, followers_a = profile()
profile_b, followers_b = profile()
# 两人粉丝恰好一样多时,重新抽一次 B,避免“猜哪个都算对”的歧义。
if followers_a == followers_b:
profile_b, followers_b = profile()
score = 0
# 布尔标志:为 True 就继续下一轮,猜错时置 False 退出循环。
correct = True

while correct:
clear()
print(logo)
if score > 0:
print(f"Correct! Your current score is: {score}.")
# 下面这行是调试用的“偷看答案”,注释掉了;取消注释就能看到两边粉丝数。
# print (followers_a, followers_b)
print(f"Compare A: {profile_a}")
print(vs)
print(f"Compare B: {profile_b}")

a_or_b = input("nWho do you think has more followers? Type 'a', or 'b': ").lower()
# 四个分支穷举了“猜 A / 猜 B × 猜对 / 猜错”。
# 猜对时:得分 +1,并把“被淘汰的那一位”换成新抽的一位——
# 猜 A 对 → B 换成新人物,A 留在原位继续比;猜 B 对则相反。
if a_or_b == 'a' and followers_a >= followers_b:
score += 1
profile_b, followers_b = profile()
elif a_or_b == 'b' and followers_a <= followers_b:
score += 1
profile_a, followers_a = profile()
elif a_or_b == 'a' and followers_a < followers_b:
print(f"nIncorrect, your final score is {score}.")
correct = False
elif a_or_b == 'b' and followers_a > followers_b:
print(f"nIncorrect, your final score is {score}.")
correct = False
# 若输入不是 a/b(比如乱敲),四个分支全不命中,循环会原地重来一遍,不扣分。
play_again = input("nDo you want to play again? Type 'y' or 'n': ")
if play_again == 'y':
higher_lower()
elif play_again == 'n':
print("Thanks for playing!")

# 入口:定义完立刻开一局。
higher_lower()

代码走读

  1. profile():随机取一条,拼出一句介绍(f"{name}, a {description}, from {country}."),返回(介绍文本, 粉丝数)。
  2. higher_lower():抽 A、抽 B;如果两人粉丝相同就重抽一次 B(只重抽一次,仍可能相同,是个小瑕疵)。
  3. score = 0、correct = True:计分与循环标志。
  4. 循环开头 clear() + 打印 logo + 当前分数,再打印 A、vs、B。
  5. 判定四种情况:
  • 选 a 且 followers_a >= followers_b → 得分,把 B 换成新人物(A 保留,形成"擂台"效果);
  • 选 b 且 followers_a <= followers_b → 得分,把 A 换成新人物;
  • 选错 → 打印最终得分,correct = False 退出。
  1. 结束时问是否再玩,y 递归重开。

设计上的巧思

猜对之后不是"两个都换",而是保留赢家、只换输家——这样玩家有连续感,也减少了重复出题。这个小设计比语法更值得学。

运行示例

1
2
3
4
5
6
7
8
Compare A: Instagram, a Social media platform, from United States.
_ __
| | / /____
...
Compare B: Cristiano Ronaldo, a Footballer, from Portugal.

Who do you think has more followers? Type 'a', or 'b': a
Correct! Your current score is: 1.

易错点

  1. profile() 返回值顺序搞反:profile_a, followers_a 接反了不会报错,只会得到错误结果。
  2. >= 与 >:粉丝相同算玩家赢,规则要明确写出来。
  3. 数据条数写死 49:数据一变就崩。
  4. 递归重开:和 Day 11 一样,层数会累积。
  5. followers 是整数(百万):如果要显示 3.46 亿,得自己乘 100 再格式化。

动手改

  • 换成 random.choice(data),并保证 A、B 不是同一个人。
  • 猜对后把"新人物"和"赢家"比较,若新人物更强则交换位置(避免玩家靠记忆取胜)。
  • 加最高分记录:把 score 写进文件(Day 24 会讲文件读写)。

源文件逐个讲解

4 个文件:main.py(53 行)、game_data.py(303 行)、art.py(18 行)、README.md(8 行)。

game_data.py(303 行)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
data = [
{
'name': 'Instagram',
'follower_count': 346,
'description': 'Social media platform',
'country': 'United States'
},
{
'name': 'Cristiano Ronaldo',
'follower_count': 215,
'description': 'Footballer',
'country': 'Portugal'
},
...
]

一个变量 data,列表里 50 个字典(实测 50 条),每条 4 个键:name、follower_count(单位百万)、description、country。

这是「嵌套数据结构」最典型的形态:

1
2
3
4
5
6
data            list
└── [0] dict
├── 'name' str
├── 'follower_count' int
├── 'description' str
└── 'country' str

访问方式是 data[0]['name']——先按下标取字典,再按键取值。这个两层访问在后面(Day 25 的 CSV、Day 34 的 API 返回)会反复出现。

注意 follower_count 是整数(百万),346 表示 3.46 亿。单位没写进字段名,只能从量级猜——真实项目里字段该叫 follower_count_millions。

art.py(18 行)

两个变量:

1
2
3
4
5
6
7
8
9
10
logo = """    __  ___       __             
/ / / (_)___ _/ /_ ___ _____
...
"""

vs = """ _ __
| | / /____
| | / / ___/
...
"""

logo 是开场的大字「HIGHER LOWER」,vs 是两屏之间的「VS」标志。这是第一个「一个 art 文件里放多个素材」的例子,所以在 main.py 里是 from art import logo, vs。

main.py(53 行)

结构:profile() 取一条数据 → higher_lower() 主循环 → 递归重开

1
2
3
4
5
6
7
8
9
10
11
12
13
from art import logo, vs
from game_data import data
from replit import clear
import random

def profile():
random_number = random.randint(0, 49)
name = data[random_number]['name']
follower_count = data[random_number]['follower_count']
description = data[random_number]['description']
country = data[random_number]['country']
compare = (f"{name}, a {description}, from {country}.")
return compare, follower_count

四个要点:

  1. randint(0, 49) 硬编码了「50 条」这个事实。往 data 里加一条就会漏掉最后一条,删一条就 IndexError。正确写法 random.choice(data) 或 random.randint(0, len(data)-1)。
  2. profile() 返回两个值(compare, follower_count),调用方用元组解包接:profile_a, followers_a = profile()。这是 README 里 Multiple return values 的落点。
  3. compare 拼成一句人话:"Instagram, a Social media platform, from United States."。
  4. name/description/country 都是临时变量,只为了拼那一句——可以直接在 f-string 里写 data[n]['name'],但分开写更易读。
1
2
3
4
5
6
7
def higher_lower():
profile_a, followers_a = profile()
profile_b, followers_b = profile()
if followers_a == followers_b:
profile_b, followers_b = profile()
score = 0
correct = True

开局抽 A、B 两条,如果粉丝数撞了就再抽一次 B。但只重抽一次——如果第二次还相同(概率极低但不是 0),会带着相同数据进游戏(那样选 a 或 b 都对,白送一分)。

更严重的是没检查「A 和 B 是同一条记录」:profile() 两次独立随机,可能抽到同一个人(1/50 概率)。屏幕上就会出现「Compare A: Instagram...」和「Compare B: Instagram...」,这时 followers_a == followers_b 成立,会重抽 B——恰好被上面那行挡住了。所以这条 bug 被「意外修复」了,但只是运气。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  while correct:
clear()
print(logo)
if score > 0:
print(f"Correct! Your current score is: {score}.")
print(f"Compare A: {profile_a}")
print(vs)
print(f"Compare B: {profile_b}")

a_or_b = input("nWho do you think has more followers? Type 'a', or 'b': ").lower()
if a_or_b == 'a' and followers_a >= followers_b:
score += 1
profile_b, followers_b = profile()
elif a_or_b == 'b' and followers_a <= followers_b:
score += 1
profile_a, followers_a = profile()
elif a_or_b == 'a' and followers_a < followers_b:
print(f"nIncorrect, your final score is {score}.")
correct = False
elif a_or_b == 'b' and followers_a > followers_b:
print(f"nIncorrect, your final score is {score}.")
correct = False

核心的「接龙」逻辑:

  • 猜 A 对 → B 换新人,A 留着(下一轮 A 就是上一轮的 B);
  • 猜 B 对 → A 换新人,B 留着。

这就保证了「上一轮的赢家留在屏幕上」,游戏有连续性。这个设计比「每轮都换两个」高明。

四个分支用了 >= 和 <=,意味着粉丝数相等时选哪边都算对。但因为开局挡掉了相等,实际跑不到。

四个分支的 elif 没有兜底:如果用户输入 "c" 或直接回车,四个条件全不成立,循环体结束回到 while correct——屏幕上什么都不变,玩家会以为程序卡死了。这是这份代码最影响体验的地方,应该加:

1
2
else:
print("只能输入 a 或 b")
1
2
3
4
5
6
  play_again = input("nDo you want to play again? Type 'y' or 'n': ")
if play_again == 'y':
higher_lower()
elif play_again == 'n':
print("Thanks for playing!")
higher_lower()

递归重开(第三次出现这个模式),最后一行顶格调用。

这份代码的问题

  1. randint(0, 49) 硬编码数据条数。
  2. 输入非 a/b 时静默卡住(无 else 兜底)。
  3. 可能抽到同一条记录(靠「粉丝数相等就重抽」碰巧挡住)。
  4. >= / <= 让平局算对,语义上应该是「必须严格大于」。
  5. from replit import clear 本地跑不了。
  6. 递归重开。

README.md(8 行)

标题 Day 14 - Higher Lower Game Project,知识点是 Functions、Randomisation、Dictionaries、Lists、User Input、Score Keeping、Formatting。

这是一份「综合复习」清单——前 13 天学的东西全用上了,没有新语法。最后一行给的 replit 链接就是在线可玩版本。

四个文件怎么配合

1
2
main.py ──import──▶ game_data.data   (50 条游戏数据)
──import──▶ art.logo, art.vs (开场图 / VS 图)

数据、素材、逻辑三者彻底分开——这是 Day 07 确立的模式,到这里已经很自然了。Day 15 之后,逻辑部分会从「一个函数」变成「多个类」,但「数据 / 素材 / 逻辑」的三分法一直保留。

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