编辑:解决了。谢谢,布鲁诺·德斯特里尔!
我在做一个学校作业的Hangman游戏,我遇到了一个错误。我的程序不会正确识别何时作出正确的猜测,而是会说每个猜测都是错误的。
我将分解我的程序的主循环。所有的代码之前和之后都是介绍性对话和结束性对话,效果与预期一致。问题是猜这个词。
我的代码的这一部分很好--这是处理不同类型的无效输入。
while "_" in placeholder:
guess = input("Guess a letter: ").lower()
if not guess.isalpha():
print("Please enter a letter.")
elif not len(guess) == 1:
print("Please enter one letter only.")
elif guess in previous_guesses:
print("You have already guessed that letter. Please guess a letter")这是问题的部分。这是程序检查猜测字母是否在单词中的地方。word_letters只是由word.split()组成的单词中的字母列表
elif guess in word_letters:
print("'" + guess + "'" + " is in the word. Good guess!")
previous_guesses.append(guess)
index = word_letters.index(guess)
for index, letter in enumerate(word_letters):
if letter == guess:
placeholder[index] = guess再一次,这里的这个部分很好用。只有在猜错的时候才会发生,但即使猜测是对的也会发生。
else:
print("'" + guess + "'" + " is not in the word. Try again.")
previous_guesses.append(guess)
stage += 1
Hangman.draw(stage)我真的不明白为什么这不能正常工作。我创建了一个测试块,它准确地模拟了主程序中发生的事情,并且工作正常。
placeholder = ['_', '_', '_', '_', '_']
word_letters = ['h', 'e', 'l', 'l', 'o']
guess = input("guess ")
if guess in word_letters:
print("It works")
index = word_letters.index(guess)
for index, letter in enumerate(word_letters):
if letter == guess:
placeholder[index] = guess
print(placeholder)
else:
print("It didn't work")有人能向我解释一下我的主程序到底有什么问题吗?
发布于 2017-05-31 11:04:20
"word_letters只是单词中由word.split()构成的字母列表。“
那就别再看了-- word_letters不是你想的那样:
>>> word = "hello"
>>> word_letters = word.split()
>>> word_letters
['hello']
>>> "h" in word_letters
Falsestr.split(sep=None)实际上将在sep上拆分字符串,默认为任何“空格”字符:
>>> "hello word".split()
['hello', 'word']
>>> "hello\nword".split()
['hello', 'word']
>>> "hello\tword".split()
['hello', 'word']要对字符串的字符创建list,必须使用list(yourstring),即:
>>> word_letters = list(word)
>>> word_letters
['h', 'e', 'l', 'l', 'o']
>>> "h" in word_letters
True但是这里甚至没有必要这样做,因为string是序列,并且已经支持包含测试:
>>> word
'hello'
>>> 'h' in word
Trueindex方法也是如此:
>>> "hello".index("h")
0
>>> "hello".index("o")
4https://stackoverflow.com/questions/44281956
复制相似问题