首页 > 解决方案 > 为什么这段代码会产生错误“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.")

我希望字符串成为一个字符串数组,(但它仍然没有,并返回相同的错误),然后确定单个数字是否与已经匹配的数字匹配

标签: python

解决方案


你的代码没有按照你的想法做。现在您正在输入一个数字,将其转换为字符串并将猜测字符串的第一个字符与不可索引的数字的第一个索引进行比较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

该代码至少应该让您了解如何在不为您解决问题的情况下解决问题。


推荐阅读