【问题标题】:Why does my variable suddenly stop counting after the first loop?为什么我的变量在第一个循环后突然停止计数?
【发布时间】:2022-11-02 03:53:19
【问题描述】:

我正在编写一个计算单词中字母数量的程序。除了我用于计算字母数量的变量(numberOfLetters)在第一个循环后突然停止计数之外,一切似乎都运行良好。这是我的代码:

import random
# Choosing a random word
with open("Random Words.txt", "r") as file:
    allText = file.read()
    allWords = list(map(str, allText.split('\n')))
    chosenWord = random.choice(allWords)
# Resetting variables
correctLetters = []
incorrectLetters = []
hiddenWord = []

numberOfLetters = 0

for i in range(12):  # Loop 12 times
    print(numberOfLetters)
    for letter in chosenWord:  # Loop once for every letter in the word
        numberOfLetters = numberOfLetters + 1  # Count the number of letters in the word

        if ''.join(correctLetters) in chosenWord:  # If a letter is guessed, show it. Otherwise, censor it.
            hiddenWord.append(chosenWord[numberOfLetters])
        else:
            hiddenWord.append('_')
        print(hiddenWord)
        hiddenWord = []
    userGuess = input('Guess a letter:')
    if userGuess in chosenWord:  # If the user guesses a letter correctly, we'll add it to the list of letters guessed
        correctLetters.append(userGuess)
        print(userGuess)
    else:
        incorrectLetters.append(userGuess)
#    print(hiddenWord)

print('Chosen word:' + chosenWord)
# UserGuess = input('\n')
print('Number of letters:')
print(numberOfLetters)
print('Correct letters:')
print(correctLetters)
print('Incorrect letters:')
print(incorrectLetters)

输出:

0
['b']
['u']
['n']
['d']
['a']
['n']
['t']
Traceback (most recent call last):
  File "C:\Users\Dr Hani Attar\PycharmProjects\Hangman\main.py", line 34, in <module>
    hiddenWord.append(chosenWord[numberOfLetters])
IndexError: string index out of range

Process finished with exit code 1

【问题讨论】:

  • 你写了 =+ 1,它是 += 1 。 =+1 意味着您在每个循环中将值 1 分配给您的变量,因此所有这些
  • @robinood 我试过了,这是输出:IndexError: string index out of range
  • numberOfLetters = numberOfLetters + 1?
  • @BluBalloon 这个错误在哪里? numberOfLetters += 1 之后还有一些代码吗?因为我看不出它在你给我们的代码中的位置
  • @BluBalloon 你确定你试过 robinood 说的话吗? numberOfLetters += 1?

标签: python loops for-loop


【解决方案1】:

字符串索引是从 0 开始的。但是您的代码将其视为基于 1 的。请注意,在您的示例输出中,所选单词 'abundant' 中的 'a' 从未打印过——您从索引 1 开始。

chosenWord[numberOfLetters] 将在 numberOfLetters == len(chosenWord) 时失败——它将在最后通过循环时执行 for letter in chosenWord:

您可以做的一件事是使用 chosenWord[numberOfLetters-1] 并包含该行

numberOfLetters = 0

在 for 循环的开头。否则,您将在第二次循环中出现另一个字符串索引超出范围错误。

for 循环本身似乎没有动力。为什么假设用户会准确猜测 12 次?使用while循环会更有意义。在还有字母要猜的时候循环。

【讨论】:

    猜你喜欢
    • 2019-01-10
    • 2021-09-15
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多