python - 为什么这段代码会产生错误“int is not subscriptable”?
问题描述
我已将变量转换为字符串,但是 Python 仍然无法识别它并说整数不可下标。
我已经尝试过查看具有相同“整数不可下标”问题的其他问题,但没有一个专门回答我的问题。
在错误发生之前,我已经明确地将变量转换为字符串。
import random
num = random.randint(1000, 9999)
tot_correct = 0
tot_tries = 0
while tot_correct != 4:
tot_correct = 0
tot_tries += 1
guess = input("Guess the number: ")
guess = str(guess)
#check 1st number
if guess[0] == num[0]:
tot_correct += 1
#check 2nd number
if guess[1] == num[1]:
tot_correct += 1
#check 3rd number
if guess[2] == num[2]:
tot_correct += 1
#check 4th number
if guess[3] == num[3]:
tot_correct += 1
print("You got " + tot_correct + " numbers right.")
print("You have guessed the number correctly! It took you " + tot_tries + " tries.")
我希望字符串成为一个字符串数组,(但它仍然没有,并返回相同的错误),然后确定单个数字是否与已经匹配的数字匹配
解决方案
你的代码没有按照你的想法做。现在您正在输入一个数字,将其转换为字符串并将猜测字符串的第一个字符与不可索引的数字的第一个索引进行比较num[0]
。
编辑:您的代码实际上做错了很多事情。您遇到的一个大问题是您tot_correct = 0
在 while 循环中进行设置,这意味着它将永远运行并且永远不会完成。
但是退后一步,我认为您使这个问题变得太复杂了。让我们谈谈我认为您正在尝试做的伪代码。
num_guessed = 0
number_to_guess = 4
total_guesses = 0
while num_guessed < number_to_guess:
# each pass we reset their guess to 0 and get a new random number
guess = 0
# get a new random number here
while guess != random:
# have a user guess the number here
total_guesses += 1 # we can increment their total guesses here too
# it would be a good idea to tell them if their guess is higher or lower
# when they guess it right it will end the loop
num_guessed += 1
# down here we can tell them game over or whatever you want
该代码至少应该让您了解如何在不为您解决问题的情况下解决问题。
推荐阅读
- c++ - boost的“windows_shared_memory”和boost的“managed_windows_shared_memory”有什么区别?
- node.js - Dockerized Nginx 反向代理到 NodeJS 应用程序不返回 PDF
- html - 为什么我的锚标签在移动视图中不起作用?
- ssms - SQL Server Management Studio 日志文件存储在哪里?
- java - IllegalStateException:会话/EntityManager 已关闭
- javascript - 从一个孩子到另一个孩子反应道具
- java - JsonFormat 的模式选项的常量
- typescript - 是否可以从其泛型类型自动生成类属性?
- php - 如何在 guzzle 响应中获取身份验证并发送到视图
- sql - 在 where 子句中使用 CASE 表达式