Python Forum
else condition not called when if condition is false
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
else condition not called when if condition is false
#1
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/Study2.py", line 12, in <module>
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.

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")
Reply
#2
Python string method index() determines if string str occurs in string or in a substring of string if starting index beg and ending index end are given. This method is same as find(), but raises an exception if sub is not found
Reply
#3
Hi @deanhystad,
Thank you for the reply. Find() is not a list attribute. I am using a list of strings to enter guesses. As just a string, I was unable to replace a position in the string.
Reply
#4
Answer is the same though. When the guess is not in the list index throws an exception.

There is no reason the word can't be a string. The word doesn't change. Here's a "Wheel of Fortune" version of Hangman. It matches multiple positions if a letter occurs in the word more than once.
import random

def find_all(letter, word):
    """Return array of indices where letter appears in word"""
    return [i for i, x in enumerate(word) if x == letter]

def hangman(word):
    """Play a game of hangman"""
    # Initialize to empty board
    word = word.upper()
    count = len(word)
    letters = ['_']*count
    remaining = count
    misses = 0

    # Begin play.  Play continues until player guesses the word or runs out of misses
    while remaining > 0 and misses < 6:
        """Draw the letters and remaining misses.  Get letter guess"""
        print(' '.join(letters))
        letter = input(f'Misses = {misses}.  Enter letter: ').upper()

        """Find all matches"""
        matches = find_all(letter, word)
        if len(matches) == 0:
            misses += 1  # No match
        else:
            for i in matches:
                letters[i] = letter # Replace blanks with letter
            remaining -= len(matches)

    # Did they win?
    if remaining == 0:
          print('Congratulations!')
    print(f'The word was "{word}"\n')
        

# Allow for multiple plays
words = ['Orangatan', 'Hippopotomus', 'Giraffe', 'Cheetah', 'Chimpanzee']
random.shuffle(words)

# Play until out of words or the player wants to quit.
first = True
for word in words:
    if not first:
        if input('Would you like to play again? ').upper()[0] != 'Y':
              break
    first = False
    hangman(word)
Reply
#5
@deanhystad thanks for code. I m still understanding the functions and parameters in it. its pretty awesome. i was having trouble using strings.

as for my code, i removed index function from the if condition and rewrote the code. its working now. Both errors are addressed.

print("=====Hangman =====\nGuess the letters to fill the blanks")
w = ["f", "l", "a", "m", "e", "s"]
b = ["_", "_", "_", "_", "_", "_"]
wrong = 0

while b != w and wrong <6:
    print(b)
    x = input("Enter your guess:  ")
    if x in w:
        i = w.index(x)
        b[i] = x
    else:
        wrong += 1
        print("Wrong guesses : " + str(wrong))
        if wrong == 6:
            print("Your are out of guesses")
if b == w:
    print(b)
    print("\n You Win !!")
Output:
=====Hangman ===== Guess the letters to fill the blanks ['_', '_', '_', '_', '_', '_'] Enter your guess: a ['_', '_', 'a', '_', '_', '_'] Enter your guess: s ['_', '_', 'a', '_', '_', 's'] Enter your guess: q Wrong guesses : 1 ['_', '_', 'a', '_', '_', 's'] Enter your guess: w Wrong guesses : 2 ['_', '_', 'a', '_', '_', 's'] Enter your guess: e ['_', '_', 'a', '_', 'e', 's'] Enter your guess: f ['f', '_', 'a', '_', 'e', 's'] Enter your guess: l ['f', 'l', 'a', '_', 'e', 's'] Enter your guess: z Wrong guesses : 3 ['f', 'l', 'a', '_', 'e', 's'] Enter your guess: x Wrong guesses : 4 ['f', 'l', 'a', '_', 'e', 's'] Enter your guess: v Wrong guesses : 5 ['f', 'l', 'a', '_', 'e', 's'] Enter your guess: b Wrong guesses : 6 Your are out of guesses
Reply
#6
Very nice!
Reply
#7
import random

data = ["orange", "mango", "fridge", "mad", "smart", "love", "curtain", "chair", "table", "cable", "cake", "magic",
        "rapid", "talcum", "absent", "music", "radio", "house", "sofa", "kitchen", "napkin",
        "bucket", "awkward", "floor", "ceiling", "television", "handbag", "washbasin", "door", "window", "playground",
        "cricket", "basketball", "vehicle", "driver", "mirror", "bathroom", "photograph", "window"]

print(
    """         
                Welcome to HANGMAN game
         Guess alphabets to find the right word
       you got same chances as count of alphabets
              Enter 'play' - to start game
              Enter 'quit' - to quit game
    """)
player_wish = input("Enter your choice: ").lower()
while player_wish == "play":

    Name = data.pop(random.randint(1, len(data) - 1))
    word = [j for j in Name]
    word2 = word.copy()
    hangman = []
    for i in range(len(word)):
        hangman.append("_")

    guess_count = len(word) - 1
    attempt = []

    while hangman != word or guess_count == 0:
        print("Guess this word")
        print(' '.join(hangman))
        print("\n")
        print(f"You got {guess_count} chances left")
        alphabet = input("guess an alphabet: ").lower()
        attempt.append(alphabet)
        if alphabet in word:
            correct_index = word.index(alphabet)
            hangman.pop(correct_index)
            hangman.insert(correct_index, alphabet)
            while alphabet in word2:
                correct_index2 = word2.index(alphabet)
                word2.pop(correct_index2)
                word2.insert(correct_index2, "*")
                hangman.pop(correct_index2)
                hangman.insert(correct_index2, alphabet)
            print(f"\nYou got this one correct\nand \nyour attempted letters : {attempt}")
        else:
            print("\noops! wrong answer")
            print(f"You have {guess_count} chance left\n your attemped letters : {attempt}")
            if guess_count == 0:
                break
            guess_count -= 1
    if guess_count != 0:
        print("you won!!\nYou guessed the word correctly")
        print(' '.join(hangman))
        print("Want to play again?")
        player_desire = input("Enter 'yes' or 'no': ").lower()
        if player_desire == "yes":
            player_wish = "play"
        else:
            player_wish = "quit"
            print("Thanks for playing.")
    else:
        print(f"sorry, you lost the game\n The word was  '{' '.join(word)}' ")
        print("Want to play again?")
        player_desire = input("Enter 'yes' or 'no': ").lower()
        if player_desire == "y":
            player_wish = "play"
        else:
            player_wish = "quit"
            print("Thanks for playing.")
I have made hangman with little more interactive and can play over and over.
Professional Dentist(32years) fell in love with Python during COVID-19 Lockdown.

"Nothing can stop you from learning new things except your own will"

Reply
#8
(Apr-20-2020, 03:40 AM)deanhystad Wrote: There is no reason the word can't be a string. The word doesn't change.

hi @deanhystad

i have basically taken apart the wheel of fortune HANGMAN code you sent. Since i am just stating off in python it took me a while. But i learnt quite a few things which is uniquely interesting about python, specially list comprehension.
And i have understood that strings cannot be re-assigned as per index. Even in the code the string is converted into a list(array) and dealt with therein. while strings have a great many functions, it is not possible to reassign a character in the string by index.
Please let me know if you think otherwise.
Error:
Traceback (most recent call last): File "C:/Study/App1_1/Study2.py", line 15, in <module> b[i] = x TypeError: 'str' object does not support item assignment

(Apr-24-2020, 02:13 AM)Shahmadhur13 Wrote: I have made hangman with little more interactive and can play over and over.

@Shahmadhur13 thank you for the code. i must say you have maintained most of the operation as a string.
it is quite interactive.
you have put in a lot of effort for the code. During my lessons i read somewhere its best to keep code to minimum. while your code internal logic is approx 30 lines. The code sent by @deanhystad is only 10 lines.
i am not counting the interactive menu code. if i understand correctly you have used all the string functions to create this program, which is why it is long. but in assigning the index you have used a list(array). so if you start using the letters and words as array elements from the beginning, you could save a lot of code lines.

this is just my observation. each persons logic is unique.
let me know what you think.
Reply
#9
Yes sir, you're right.
I know I have far more code lines than actually needed.
For me, right now is to get things done with whatever I have learned till now. "enumerate" function i didn't learn till i see above post. Enumerate function only can trim my code line by approximately 10 lines.
I will focus on optimization of python code once i completely learn all basic functions.
Thank you for your advice. I will surely keep this in mind.
Professional Dentist(32years) fell in love with Python during COVID-19 Lockdown.

"Nothing can stop you from learning new things except your own will"

Reply
#10
Added a piece to Shahmadhur13's code. Replace the data[] part with
file = 'words_alpha.txt'
data = []
count = 0
with open(file,'r') as words:
    for word in words:
        data.append(word.replace('\n', ''))
and using the link to the text file below you will have a list of words counting 370,104 words.
words_alpha.txt
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Get an average of the unique values of a column with group by condition and assign it klllmmm 0 252 Feb-17-2024, 05:53 PM
Last Post: klllmmm
  unable to remove all elements from list based on a condition sg_python 3 412 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Python Alteryx QS-Passing pandas dataframe column inside SQL query where condition sanky1990 0 722 Dec-04-2023, 09:48 PM
Last Post: sanky1990
  Multiple variable inputs when only one is called for ChrisDall 2 481 Oct-20-2023, 07:43 PM
Last Post: deanhystad
  Sent email based on if condition stewietopg 1 849 Mar-15-2023, 08:54 AM
Last Post: menator01
  Replacing values ​​in Mysql with a condition stsxbel 0 629 Mar-05-2023, 08:20 PM
Last Post: stsxbel
  Couldn't install a go-game called dlgo Nomamesse 14 3,073 Jan-05-2023, 06:38 PM
Last Post: Nomamesse
  create new column based on condition arvin 12 2,216 Dec-13-2022, 04:53 PM
Last Post: jefsummers
Question Running an action only if time condition is met alexbca 5 1,305 Oct-27-2022, 02:15 PM
Last Post: alexbca
  How to assign a value to pandas dataframe column rows based on a condition klllmmm 0 822 Sep-08-2022, 06:32 AM
Last Post: klllmmm

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020