我的代码无法正常工作。我想要的是使单词正确显示而没有任何其他消息。我究竟做错了什么?为简单起见,我只输入一个单词(“周末”),以便每次运行代码时都可以轻松检查我的代码错误。
def hangman():
j=0
word='weekend'
new_word=len(word)*'_ '
while j<20:
letter=input('Give a letter: ')
for i in range(len(word)):
if word[i]==letter and new_word[i]=='_':
new_word=new_word.replace(new_word[i],letter)
if new_word.replace(' ','')==word:
print('You won!')
break
j+=1
print(new_word)
hangman()
答案 0 :(得分:0)
您将所有字母替换为用户输入的第一个字母的原因是因为以下一行:
new_word=new_word.replace(new_word[i],letter)
之所以会这样,是因为new_word[i]
等于'_'
,并且new_word
仅由短破折号组成(除了空格,ofc),因此所有'_'
都将被替换通过输入字母。
这有效:
def hangman():
j=0
word='weekend'
new_word=len(word)*'_'
while j<20:
letter=input('Give a letter: ')
for i in range(len(word)):
if word[i]==letter and new_word[i]=='_':
new_word = new_word[:i] + letter + new_word[i+1:]
if new_word.replace(' ','')==word:
print('You won!')
break
j+=1
print(new_word)
hangman()
此代码与您的代码之间的唯一区别是将上述行替换为:
new_word = new_word[:i] + letter + new_word[i+1:]
下面的代码更具可读性:
def hangman(word, tries):
new_word = '_' * len(word)
for _ in range(tries):
if '_' not in new_word:
return print('You won! :)')
letter = input('Give a letter: ')
for i, l in enumerate(word):
if l is letter:
new_word = new_word[:i] + letter + new_word[i+1:]
print(new_word)
print('You lost! :(')
hangman('weekend', 20)
答案 1 :(得分:0)
$or: [{x: 10, y: 20},{x: 20, y: 70}]
此代码可以完成您想做的事情。您原始代码中的错误:
def hangman():
j=0
word='weekend'
new_word=len(word)*'_'
while j<20:
letter=input('Give a letter: ')
print("letter =" + letter)
for i in range(len(word)):
if word[i]==letter and new_word[i]=='_':
new_word = list(new_word)
new_word[i] = letter
new_word = ''.join(new_word)
if new_word.replace(' ','')==word:
print('You won!')
break
j+=1
print(new_word)
hangman()
(最后注意空格。这弄乱了索引)
`new_word=len(word)*'_ '`
这导致new_word=new_word.replace(new_word[i],letter)
被new_word
取代!这样就变成了letter
(如果有人输入了wwwwwww
)
w
易于理解的在特定索引处替换字符的方法是将其转换为列表,然后在该索引处用 new_word = list(new_word)
new_word[i] = letter
new_word = ''.join(new_word)
进行替换。我们稍后将列表转换回字符串。