想象一下,用户输入了(编辑)字母'f'
。然后弹出以下错误。
wrdsplit = list('ferret')
guess = input('> ')
# user inputs `f`
print(wrdsplit.index(guess))
但这导致ValueError: 'f' is not in list
。
答案 0 :(得分:2)
import random
import time
import collections
def pics():
if count == 0:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /|\ ")
print ("| / \ ")
print ("| ")
print ("| ")
elif count == 1:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /|\ ")
print ("| / ")
print ("| ")
print ("| ")
elif count == 2:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /|\ ")
print ("| ")
print ("| ")
print ("| ")
elif count == 3:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| /| ")
print ("| ")
print ("| ")
print ("| ")
elif count == 4:
print (" _________ ")
print ("| | ")
print ("| 0 ")
print ("| | ")
print ("| ")
print ("| ")
print ("| ")
elif count == 5:
print (" _________ ")
print ("| | ")
print ("| GAME OVER ")
print ("| YOU LOSE ")
print ("| ")
print ("| ")
print ("| (**)--- ")
print("Welcome to HANGMAN \nHave Fun =)")
print("You can only get 5 wrong. You will lose your :\n1. Right Leg\n2.Left Leg\n3.Right Arm\n4.Left Arm\n5.YOUR HEAD... YOUR DEAD")
print("")
time.sleep(2)
words = "ferret".split()
word = random.choice(words)
w = 0
g = 0
count = 0
correct = []
wrong = []
for i in range(len(word)):
correct.append('#')
wrdsplit = [char for char in "ferret"]
while count < 5 :
pics()
print("")
print("CORRECT LETTERS : ",''.join(correct))
print("WRONG LETTERS : ",wrong)
print("")
print("Please input a letter")
guess = input("> ")
loop = wrdsplit.count(guess)
if guess in wrdsplit:
for count in range(loop):
x = wrdsplit.index(guess)
correct[x] = guess
wrdsplit[x] = '&'
g = g + 1
if "".join(correct) == word:
print("Well done... You guessed the word in", g ,"guesses and you got", w , "wrong")
print("YOU LIVED")
break
elif guess not in wrdsplit:
wrong.append(guess)
w = w + 1
g = g + 1
count = count +1
pics()
print("The correct word was : ",word)
答案 1 :(得分:0)
我在这里看到的唯一错误(基于您之前的代码)是:
if guess in wrdsplit:
for count in range(len(wrdsplit)):
x = wrdsplit.index(guess)
wrdsplit[x] = '&'
correct[x] = guess
g = g + 1
wrdsplit[x] = '&' # x is out of scope
if "".join(correct) == word:
print("Well done... You guessed the word in", g ,"guesses and you got", w , "wrong")
print("YOU LIVED")
break
现在,如果你继续在这里寻找f重试,它将无效,因为你已经将'f'改为'&amp;'所以你会得到f不在列表中的错误。你刚陷入一个讨厌的小虫子周期。
您应该考虑使用词典代替。
答案 2 :(得分:0)
尝试使用此代码查看它是否有效并执行您想要的操作
# Get this from a real place and not hardcoded
wrdsplit = list("ferret")
correct = ["-"]*len(wrdsplit) # We fill a string with "-" chars
# Ask the user for a letter
guess = input('> ')
if guess in wrdsplit:
for i, char in enumerate(wrdsplit):
if char == guess:
correct[i-1] = guess
# Calculate the number of guesses
if "-" in correct:
g = len(set(correct)) - 1
else:
g = len(set(correct))
# Print the right word
print("".join(correct))
该集合生成一个没有重复的数组来计算他做了多少猜测,如果&#34; - &#34;被发现,一个被减去,因为那个角色不是猜测。