Python 为什么for会创建一个无限循环?
我一直在尝试编码,为了好玩我做了这个小刽子手游戏Python 为什么for会创建一个无限循环?,python,python-3.x,Python,Python 3.x,我一直在尝试编码,为了好玩我做了这个小刽子手游戏 from random import randint import sys used_letters = [] life = 3 wordList = ['apple','bee','castle','house','train','computer','snake','program','cellphone','microphone'] word = wordList[randint(0,(len(wordList)-1))] wordLi
from random import randint
import sys
used_letters = []
life = 3
wordList = ['apple','bee','castle','house','train','computer','snake','program','cellphone','microphone']
word = wordList[randint(0,(len(wordList)-1))]
wordList = [letter for letter in word]
amountLetters = 0
word_holder = []
for letter in wordList:
word_holder.append(amountLetters)
amountLetters += 1
while life > 0:
fail_counter = 0
user_input = (input('What is your guess?')).lower()
if user_input == word:
print('You win')
sys.exit(0)
elif user_input == 'word':
print(word_holder)
elif user_input == 'letters':
print(used_letters)
elif wordList.count(user_input) > 0:
for letter in wordList:
if user_input == letter:
indexNb = wordList.index(letter)
word_holder.insert(indexNb, letter)
wordList.insert(indexNb, '0')
print(f'You found the letter {letter}')
else:
fail_counter = fail_counter + 1
if fail_counter == len(wordList):
print('You lost a life')
used_letters.append(letter)
life -= 1
if life == 0:
print('You lose!')
在工作期间,我一直在尝试不同的方法,但我做不到。这似乎是一个好方法,但它不断进入一个无限循环,用同一个字母重复打印。因此,基本上我想知道为什么“for”会进入无限循环,尽管“wordList”中的“letter”应该是有限的。从经验上讲,wordList不是有限的:在迭代时附加到它,这扩展了列表。在循环中使用print语句来跟踪您的值,您将看到问题所在。在找到的字母前面插入一个0。这封信在一个位置被撞到了右边,你在下一次执行时会找到同一封信
for letter in wordList:
if user_input == letter:
indexNb = wordList.index(letter)
word_holder.insert(indexNb, letter)
wordList.insert(indexNb, '0')
print('You found the letter', letter)
print(' wordList is now', wordList)
相反,请使用replace方法或从原始字符串生成新字符串。例如,只需将此循环替换为
wordList.replace(letter, '0')
print('You found the letter', letter)
另外,请注意一个明显的问题:您正在处理整个单词列表,而不是一个单词;我还没有修复那部分。欢迎来到Stackoverflow社区。for循环中的以下行可能导致无限循环,请更新代码
wordList.insert(indexNb, '0')
您将在当前正在检查的索引处插入单词列表,这意味着您通过在当前位置添加“0”将要检查的字母推出,这意味着在下一个循环中再次找到该字母
因此,在第一个循环中,在['x','y','z']中搜索'x',在索引0处找到x,然后在该索引处插入'0',将列表更新为['0','x','y','z']。在下一个循环中,它将列表迭代器的内部索引从0前进到1,并再次放入找到的值“x”!写信。然后它插入'0'以获得['0','0','x','y','z']。我想你可以从这里遵循逻辑;您将插入无限多个“0”,因为每个“0”都会将您的目标推出另一个索引,您会立即再次找到它。欢迎使用StackOverflow。然而,你应该让你的问题更明确。你到底在问我们什么?你是否要求对代码进行修改,使循环不再是无限的?我想知道为什么“for”会进入无限循环,尽管单词列表中的字母是有限的。我接受任何形式的评论或帮助。当你得到一个解决方案时,请记住投有用的票,接受你最喜欢的答案,即使你必须自己写,这样Stack Overflow可以正确地存档问题。wordList是一个列表。列表上没有替换方法。你是说单词表[indexNb]=“0”吗?