简体   繁体   English

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

[英]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. 当我使用0而不是实际使用计数器时它起作用。 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. 这只发生在我输入一个低于4的值时,当我输入一个超过4的值时,循环不会重新启动,但它会突然出现循环。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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