1

我遇到了一个错误真的很艰难。每次我输入一个比秘密词少字符的猜测词时,我都会得到“IndexError:string out of range”。我试图让我的代码在秘密词中找到猜测词的匹配字母。如何让它检查单词的每个索引而不会出现此错误?如果字符长度小于或大于 6 个字母,则不必打印表情符号颜色。我想继续要求新的猜测,直到猜测长度为 6 个字符。我也只能将这些基本功能用于课堂作业,仅此而已。

任何帮助,将不胜感激!

WHITE_BOX: str = "\U00002B1C"
GREEN_BOX: str = "\U0001F7E9"
YELLOW_BOX: str = "\U0001F7E8"

secret_word: str = "python"
length_of_secret = len(secret_word)

guess_word: str = input(f"What is your {length_of_secret} letter guess? ")
length_of_guess = len(guess_word)

i: int = 0
check_index: int = 0
emoji_color: str = ""

while check_index < length_of_secret:
    if guess_word[check_index] in secret_word[check_index]:
        emoji_color += GREEN_BOX
    else:
        emoji_color += WHITE_BOX
    check_index += 1

while i < length_of_secret:
    if length_of_guess < length_of_secret:
        guess_word = input(f"That was not {length_of_secret} letters! Try again: ")
        length_of_guess = len(guess_word)
        if guess_word == secret_word:
            print(emoji_color)
            print("Woo! You got it!")
            break
        if length_of_guess == length_of_secret:
            print(emoji_color)
            print("Not quite. Play again soon!")
            break
    if length_of_guess > length_of_secret:
        guess_word = input(f"That was not {length_of_secret} letters! Try again: ")
        length_of_guess = len(guess_word)
        if guess_word == secret_word:
            print(emoji_color)
            print("Woo! You got it!")
            break
        if length_of_guess == length_of_secret:
            print(emoji_color)
            print("Not quite. Play again soon!")
            break
    i += 1
    if guess_word == secret_word:
        print("Woo! You got it!")
        print(emoji_color)
        break
    if length_of_guess == length_of_secret:
        print(emoji_color)
        print("Not quite. Play again soon!")
        break

4

1 回答 1

0

您应该在分析输入字符串之前执行长度检查。在做任何其他依赖于该假设的事情之前,您应该验证您对长度的假设。

secret_word: str = "python"
length_of_secret = len(secret_word)

guess_word = ""
while len(guess_word) != length_of_secret:
    guess_word: str = input(f"What is your {length_of_secret} letter guess? ")
    if len(guess_word) != length_of_secret:
        print(f"That was not {length_of_secret} letters! Try again.")
于 2022-02-06T19:37:38.490 回答