Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding matches in two lists

I’am creating my first python project called hangman. And i’am stuck in place, where i need to compare letters from given word and if all letters is correct (not depending from order), program shows, that i won.

import random

class HangMan():

    def __init__(self):
        self.words_list = 'sunny', 'number', 'darius', 'calendar', 'table'
        self.words_randomizer = random.choice(self.words_list)




    def guess_letter(self):
        word_splitter = list(self.words_randomizer)
        empty_list = []
        while True:
            guess_letter = str(input('Please enter letter'))
            empty_list.append(guess_letter)
            if guess_letter in word_splitter:
                print(f'You are correct, there is letter - {guess_letter}, please guess another !')
                continue
            elif sorted(empty_list) == sorted(word_splitter):
                print('Congrats ! You won')
                break



8hm = HangMan()
print(hm.words_randomizer)
hm.guess_letter()

I thought, if i’ll create empty list and append guessing letters it will work. But it dont.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to only add the letter to the list when it’s correct, also don’t use an elif, finding a letter isn’t an excluding condition for solving the exercice, that’s the opposite, you need to find letter to solve it so put the winning condition into the valid-guessing block

def guess_letter(self):
    word_splitter = sorted(self.words_randomizer)
    guesses = []
    while True:
        guess_letter = input('Please enter letter: ')

        if guess_letter in guesses:
            print("You already test that")
            
        elif guess_letter in word_splitter:
            print(f'You are correct, there is letter - {guess_letter}, please guess another !')
            guesses.append(guess_letter)
            if sorted(guesses) == word_splitter:
                print('Congrats ! You won')
                break

Also

  • check for already tested letter
  • input already returns a string
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading