我正在为CodeHS的python课程入门进行项目开发,但我不知道为什么这段代码会产生错误消息或根本无法工作。
我尝试删除了破折号,没有它,程序运行正常。由于某种原因,此新变量导致代码的最后一部分出现问题。
secret_word = "banana"
x = 0
dashes = ""
wordlist = list(secret_word)
for x in range(len(secret_word)):
dashes = dashes + "-"
def get_guess():
while x < 1:
guess = input("Guess: ")
if len(guess) > 1:
print "Your guess must have exactly one character!"
elif not guess.islower():
print "Your guess must be a lowercase letter"
else:
return guess
while dashes != secret_word:
print dashes
guess = get_guess()
if guess in wordlist:
print "That letter is in the word"
else:
print "That letter is not in the word"
我希望程序会要求输入以猜测单词内的字母;但是,该程序要么永远运行,要么出现错误消息。该程序未完成;任何帮助修复此错误消息或使其更流畅地运行的帮助,将不胜感激!
答案 0 :(得分:0)
您在此处定义了x
:
secret_word = "banana"
x = 0
dashes = ""
wordlist = list(secret_word)
并在此处重新分配值:
for x in range(len(secret_word)):
dashes = dashes + "-"
然后,循环条件始终为False
。因此get_guess()
什么也不做。
def get_guess():
while x < 1:
guess = input("Guess: ")
这是一个很好的示例,展示了短变量名和全局变量的危险性。