IndexError:字符串索引超出范围,索引在

时间:2016-01-21 19:39:29

标签: python python-3.x

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()

我不明白为什么它说索引不在范围内。当我使用0而不是实际使用计数器时它起作用。这只发生在我输入一个低于4的值时,当我输入一个超过4的值时,循环不会重新启动,但它会突然出现循环。

1 个答案:

答案 0 :(得分:3)

我会提出这样的解决方案:

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")