简体   繁体   中英

can anyone tell me what is wrong with my if condition?

import random
end_of_game = False
word_list = ["ardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)
lives = 6
#Testing code
print(f'Pssst, the solution is {chosen_word}.')
display = []
for _ in range(word_length):
    display += "_"
while end_of_game == False:
    guess = input("Guess a letter: ").lower()
    for position in range(word_length):
        letter = chosen_word[position]
        if letter == guess:
            display[position] = letter
    if guess != chosen_word:
        lives -= 1
        if lives == 0:
            end_of_game = True
            print("You lose.")
    print(f"{' '.join(display)}")
    if "_" not in display:
        end_of_game = True
        print("You win.")

I have a problem with this part only

if guess != chosen_word: 
    lives -= 1 
    if lives ==0        
        end_of_game = True

when ever i picked a wrong word then my lives should go down but no matter what if only gives me 6 tries what am i doing wrong''' enter code here

Change

if guess != chosen_word:

to

if guess not in chosen_word:

so then you only lose a life if the letter you guessed is wrong.

You're comparing one letter guess to the whole word chosen_word . They'll never be equal, so you always decrement lives .

Instead, check if _ is still in display , just as you do when determining whether to display You win .

if "_" in display:
    lives -= 1
    if lives == 0:
        end_of_game = True
        print("You lose.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM