Navin
Navin

Reputation: 57

IndexError: string index out of range, the index is in the range

import random

four_digit_number = random.randint(1000, 9999) # Random Number generated


def normal():
    four_digit = str(four_digit_number)
    while True: # Data Validation
        try:
            guess = int(input("Please enter your guess: "))
        except ValueError or len(str(guess)) > 4 or len(str(guess)) < 4:
            print("Please enter a 4 digit number as your guess not a word or a different digit number")
        else:
            break
    guess = str(guess)
    counter = 0
    correct = 0
    while counter < len(four_digit):
        if guess[counter] in four_digit:
            correct += 1
        counter += 1
    if correct == 4:
        print("You got the number correct!")
    else:
        print("You got " + str(correct) + " digits correct")

normal()

I don't understand why it says the index is not in range. When I use 0 instead of actually using counter it works. This only happens when I enter a value under 4 and when I enter a value over 4 the loop does not restart but it breaks out of the loop.

Upvotes: 1

Views: 390

Answers (1)

Paweł Kordowski
Paweł Kordowski

Reputation: 2768

I would propose such a solution:

def normal():
    four_digit = str(four_digit_number)
    while True: # Data Validation
        try:
            guess = str(int(input("Please enter your guess: ")))
            assert len(guess) == 4
        except (ValueError, AssertionError):
            print("Please enter a 4 digit number as your guess not a word or a different digit number")
        else:
            break
    correct = sum(a == b for a, b in zip(four_digit, guess))
    if correct == 4:
        print("You got the number correct!")
    else:
        print("You got " + str(correct) + " digits correct")

Upvotes: 3

Related Questions