Python: Else condition not called when if condition is false

i was creating a simple guessing game where in the guess is matched to the original string and completes the word.
Encountering 2 errors.

  1. When wrong guess is made, the else condition is not called and python returns an error.
    Traceback (most recent call last):
    File “C:/Users/PycharmProjects/”, line 12, in
    if w.index(x):
    ValueError: ‘b’ is not in list
  2. The first letter is not replaced in the guessed word inspite of guessing correctly.

Python Code: (Double-click to select all)

print ( "=====Hangman =====\nGuess the letters to fill the blanks" )

w = [ "o" , "r" , "a" , "n" , "g" , "e" ]

b = [ "_" , "_" , "_" , "_" , "_" , "_" ]

wrong = 0

while b ! = w and wrong < = 6 :
          print (b)
          x = input ( "Enter your guess: " )

          if w.index(x):
                     i = w.index(x)
                      b[i] = x
           else :
                      wrong + = 1

if wrong = = 6 :

print ( "Your are out of guesses" )

I’ve edited your post for readability. Please check again your post and make sure it reflect your code.

When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.


1 Like

Thanks @ilenia for the tip.

  1. w.index(x) will throw exception if x is not found. You can either use that by replacing if/else clause with try/except, or need to check differently if character is in list, i.e. if something in my_list:
  2. For index 0 your condition will result in false as 0 is falsy value - 0 == False so the else block is executed.
1 Like

Thanks @sanity . I rewrote code with if condition. The index 0 got fixed on it’s own. I’m still researching what happened there.