这是一个python hangman程序。当用户猜错答案时,我希望变量guesss_left减少1。无论猜出什么,它都剩下9个不正确的猜想。如何解决此问题,使它从1一直下降到0?谢谢!
#initializes the secret word and starts with empty dashes list
secret_word = "eggplant"
dashes_list = []
def get_guess(guesses_left):
#prompts user for a guess
guess = input("Guess: ")
dashes = "-"
#if the guess is not one character
if len(guess) != 1:
print ("Your guess must have exactly one character!")
#if the guess is not lowercase
elif not guess.islower():
print ("Your guess must be a lowercase letter!")
#assigns this position_of_letter variable to be used later
position_of_letter = 0
for letter in secret_word:
if guess == letter:
print ("Letter is in secret word.")
update_dashes(secret_word, dashes, guess)
return
else:
position_of_letter += 1
if position_of_letter == len(secret_word):
print ("Letter is not in the secret word.")
if guesses_left==0:
print("You lose. The word was "+secret_word)
exit()
guesses_left=guesses_left-1
print (str(guesses_left)+" incorrect guesses left.")
#This goes through the word and makes sure to update
#the dashes at the right place
def update_dashes(secret_word, dashes, guess):
position_of_letter_dashes_list = 0
for letter in secret_word:
if letter == guess:
dashes_list[position_of_letter_dashes_list] = guess
position_of_letter_dashes_list += 1
#adds a dash mark for each letter so there is now a list of dashes
for i in range(len(secret_word)):
dashes_list.append("-")
#The .join breaks the dashes list into a continuous string of dashes
#The "" is there so that nothing comes before each dash
guesses_left=10
while True:
print ("".join(dashes_list))
get_guess(guesses_left)
if "-" not in dashes_list:
print("Congrats! You win. The word was "+secret_word+".")
break
Presently you pass
guesses_left
intoget_guess
as an argument and when you decrement it, you don't affect the global variable. You can rectify this by returning the number of guesses left fromget_guess
and storing this intoguesses_left
, by updating the following (marked) lines: