IndexError: string index out of range


This isn't an exercise, I am just trying to create something from what I've learned here

Traceback (most recent call last):
File "", line 20, in
if b[1] == a[1]:
IndexError: string index out of range

If the second letter in the guess matches the second letter of the code it should say " You got the second Digit right"

from random import randint
from sys import exit

print "Open the lock"

code = "%d%d%d" % (randint(0,9),randint(0,9),randint(0,9))
guess = raw_input("[KEYPAD]: ")
guesses = 1

a = str(code)
b = str(guess)

while guess != code and guesses < 10:
    print "Bzzt"
    guesses += 1
    if b[0] == a[0]:
        print "You got the first digit right"
    if b[1] == a[1]:
        print "You got the second digit right"
    if b[2] == a[2]:
        print "You go the third digit right"
    guess = raw_input("[KEYPAD]: ")

if guess == code:
        print "You Win"
        print "The bomb goes off and you die."


it makes more sense to store the code as list, then convert the user input to integer. Working with numbers as string is asking for problems


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.