简体   繁体   中英

Why do I get IndexError: string index out of range?

I did google it a lot, and I think I figured out what was causing it, but I don't understand why.

When I would try to run this code:

from random import randint
 
def getNums():
    nums = set()
    nums = randint(100, 999)
    return str(nums)
 
def askUser():
        try:
            guess = int(input("Choose 3 digits to play the game: "))
        except:
            print("Please enter numbers only.")
        return guess
 
def compare(num, guess):
    try:
        if guess == num:
            print("Guessed!")
            print(f"The number was {num}")
        elif guess[0] in num or guess[1] in num or guess[2] in num:
            print("Match")
        elif num != guess:
            print("Nope")
    except IndexError:
        pass
 
#GET RANDOM DIGITS
num = getNums()
 
#ASK THE USER TO ENTER THEIR GUESS
 
 
 
#GAME
while True:
 
    guess = askUser()
    guess = str(guess)
    compare(num, guess)
    if num == guess:
        break 

I would get

---> 23     elif guess[0] in num or guess[1] in num or guess[2] in num:
     24         print("Match")
     25     elif num != guess:

IndexError: string index out of range

When I would try with 0.

Removing the int(input) and casting the int variables to string seems like it fixed it, but I don't know why there was a problem to start with since they had the same length. Thank you

When you enter a number like '012' , and you convert it to an int ( 12 ), then the resulting string will be '12' .

As you can see, you no longer have a string of length 3 in this example, but of length 2.

So you get an IndexError when accessing guess[2] , since that index does not exist (at least you get the IndexError when you remove the try/except statement).


A simple way around this would be to store the user input in the variable without trying to parse as int, and then just use int() without changing guess.

Something like this:

def askUser():
    try:
        guess = input("Choose 3 digits to play the game: ")
        int(guess)
    except:
        print("Please enter numbers only.")
    return guess

There are other things that can be improved, like only returning guess when there's no error (otherwise you'll get an exception), only catching a ValueError instead of all exceptions, and actually testing if the user input is exactly three characters long.

If I am understanding your code and question, when you cast the int to a string, you are able to parse it as a string hence, why it works. If you pass it as an int, you cannot parse an int by positional reference such as guess[0].

To me, you corrected the issue by casting it to a string that allowed for your parsing.

Also, by using the Python "in" keyword, it will check to see if the value is in the string so, you do not need to parse through the string as "in" will return True or another output if you use an "if" statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM