我正在用Python 2开发一个简单的Hangman游戏。到目前为止,我的代码是我所要做的基础工作,但似乎没有用。如果我可以简单地叫醒我编写的代码不起作用怎么办,我将不胜感激。
代码:
secret_word = 'tracy'
secret_word_list = []
for letter in secret_word:
secret_word_list += letter
print secret_word_list
def get_guess(guess = input("Guess: ")):
while len(guess) != 1:
print "Your guess must be exactly one character!"
guess = input("Guess: ")
while guess.isalpha() == False:
print "Your guess must be a lowercase letter!"
guess = input("Guess: ")
while guess.islower == False:
print "Your guess must be a lowercase letter!"
guess = input("Guess: ")
else:
return guess
while True:
if str(get_guess) in secret_word_list:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
get_guess(guess = input("Guess: "))
输出:
答案 0 :(得分:1)
这里有几个问题,但是最大的问题是您没有调用函数,因此您将函数本身与秘密进行了比较。
带修复的代码:
secret_word = 'tracy' # Don't make secret_word_list, there's no point; just use the str itself since you only test len 1 strings against it anyway
print secret_word
def get_guess(guess): # Don't make the default call input, that'll prompt once for an input and store it as the permanent default
while True:
# Test each condition and break loop only if all past; original code would never
# recheck length if new value entered after testing isalpha
if len(guess) != 1:
print "Your guess must be exactly one character!"
elif not guess.islower(): # Add missing call parens on islower; use not, never compare to False; islower implicitly verifies isalpha, so avoid testing isalpha
print "Your guess must be a lowercase letter!"
else:
break # Passed all tests, break loop
# Get new guess if any test failed
guess = raw_input("Guess: ") # Use raw_input on Python 2, never input (which eval's the result of raw_input)
# Removed else (loop always ends by breaking, using else nonsensical but harmless in original code too
return guess
while True:
# Move guess getting to if, because having it in else case never actually checked it
if get_guess(raw_input("Guess: ")) in secret_word:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
注意:我保留了让get_guess
接受参数的一种奇怪的行为,但是随后提示您进行失败的猜测。一个更明智的解决方案是完全删除guess
参数,并将guess = raw_input("Guess: ")
移动到while
循环的顶部(在最后删除else
块)。 / p>
答案 1 :(得分:0)
get_guess
是一个函数,您需要在其后放置()
来调用该函数。
您不应将对input()
的调用作为默认参数。定义函数时,将对默认值进行一次评估,而不是每次调用该函数时都会评估一次。您应该在函数内分配guess
。
您应该在一个循环中测试所有无效输入。
def get_guess():
while True:
guess = input("Guess:")
if len(guess) != 1:
print "Your guess must be exactly one character!"
continue
if not guess.isalpha() or not guess.islower():
print "Your guess must be a lowercase letter!"
continue
break
return guess
while True:
guess = get_guess()
if guess in secret_word_list:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"