为何我的猜数字代码出现TypeError: 'int' object is not subscriptable错误?
问题分析与修复
错误原因
- 变量名冲突:
compare_guess函数内的for guess in range(4):将传入的字典类型guess覆盖为循环整数(0-3),导致后续guess["1"]尝试对整数做下标访问,触发TypeError: 'int' object is not subscriptable。 - 类型不匹配:代码末尾将
guess赋值为字符串"0000",而secret_code是字典,while secret_code != guess:的判断永远为真,无法终止循环。 - 逻辑漏洞:
- 函数内循环4次但每次重复检查所有4个位置,且第一次循环就执行
return,循环完全无效。 guess["1"] in secret_code是判断键是否存在于字典,而非判断数字是否在秘密代码的数值中,应该检查值是否在secret_code.values()里。- 初始的猜数字输入被后续
guess = "0000"覆盖,完全未被使用。
- 函数内循环4次但每次重复检查所有4个位置,且第一次循环就执行
修复后的代码
print("welcome to spaceship and aliens!") print("your goal is to crack a secret 4-digit code.All the digits in the code are unique.") print("a spaceship (S) means you've guessed the right position.") print("an alien (A) means you've guessed the right digit but at the wrong position") print("wrong digits get ignored") # 初始化秘密代码字典 secret_code = {} secret_code["1"] = input("pick the first digit in the secret code:") secret_code["2"] = input("pick the second digit in the secret code:") secret_code["3"] = input("pick the third digit in the secret code:") secret_code["4"] = input("pick the fourth digit in the secret code:") # 清空屏幕(原代码的循环打印空行) for _ in range(100): print() # 比较猜测与秘密代码的函数 def compare_guess(secret_code, guess): num_spaceship = 0 num_aliens = 0 # 统计位置正确的(S) for key in ["1", "2", "3", "4"]: if guess[key] == secret_code[key]: num_spaceship += 1 # 统计数字正确但位置错误的(A),排除已统计为S的数字 secret_values = list(secret_code.values()) guess_values = list(guess.values()) # 复制列表避免修改原数据 temp_secret = secret_values.copy() temp_guess = guess_values.copy() # 移除位置匹配的元素 for i in range(4): if secret_values[i] == guess_values[i]: temp_secret.remove(secret_values[i]) temp_guess.remove(guess_values[i]) # 统计剩余元素中的匹配数 for digit in temp_guess: if digit in temp_secret: num_aliens += 1 temp_secret.remove(digit) return f"{num_spaceship}S{num_aliens}A" # 游戏主循环 while True: # 每次循环重新获取用户猜测 guess = {} guess["1"] = input("enter the first digit of the secret code:") guess["2"] = input("enter the second digit of the secret code:") guess["3"] = input("enter the third digit of the secret code:") guess["4"] = input("enter the fourth digit of the secret code:") result = compare_guess(secret_code, guess) if result == "4S0A": print("congratulations, you broke the secret code") break else: print(result)
关键修改点
- 重命名循环变量:将函数内的循环变量改为
_,避免覆盖传入的字典参数。 - 重构匹配逻辑:拆分位置匹配(S)和数字匹配(A)的统计逻辑,避免重复计数。
- 修复类型错误:移除
guess = "0000"的错误赋值,每次循环重新获取用户的猜测字典。 - 修正存在性判断:改为检查数字是否在秘密代码的值列表中,而非键列表。
- 完善循环终止:当猜测完全正确时,用
break终止循环,结束游戏。
内容的提问来源于stack exchange,提问作者Thai Ngo
相关产品推荐
相关产品推荐

