1

I am somewhat familiar with Python and decided to tackle a simple hangman game and it kinda works with bugs. My program is posted below after which I will explain what the issue is:

import random

with open('L:\document.txt', 'r') as d:
    file = d.read()
country_list = file.split('\n')

def game():


    n = random.randint(0, len(country_list))
    word = str.lower(country_list[n])
    c = 0
    hidden = ''
    for i in range(0, len(word)):
        hidden = hidden + '#'
        hidden_updated = hidden
    print("The country name is "+ hidden)
    list_hidden = list(hidden)
    list_hu = list(hidden_updated)

    while(c<=20):

        list_hu = list_hidden
        guess = input("Guess a letter")
        for j in range(0, len(word)):
            #print(guess+word[j])
            if(guess == word[j]):
                list_hidden[j] = guess

            #print(str(list_hu))
            #print(str(list_hidden))
        #print(list_hu)
        if list_hu == list_hidden:
            print("Sorry guess again " + str(20 - c) + " tries left")
            c += 1

        else:
            print("Correct! " + guess + " is in the word!")

        #print(str(list_hidden))

        compare = ''.join(list_hidden)
        print(compare)
        if compare == word:
            winningscenario()
        if(c>20):
            losingscenario(word)



def winningscenario():
    print("Congratulations. You won")
    nextchoice()

def losingscenario(a):
    print("Sorry. Maximum attempts exceeded")
    print("Word was "+a)
    nextchoice()

def nextchoice():
    choice = input("Next Word (N) or quit (Q)?")
    if choice == 'q':
        print("Thanks for playing!!")
        quit()
    else:
        game()


game()

The logic

A random country name is generated from a text file and I create a list called hidden which is initially set to all # and is progressively revealed as the user guesses the correct letters. Now notice the while loop in the game() funtion. I create two variables one called list_hidden which gets updated as the user guesses the correct letter and list_hu to act as a control. On each iteration list_hu gets set to list_hidden. Then the user inputs a guess. A for loop inserts the guessed letter in the respective indices of list_hidden if the guess is correct. Then an if else statement checks whether list_hidden came out unchanged or it got changed n the for loop by comparing with list_hu and accordingly prints a message. There are 20 tries available.

The issue

Whether the guess is correct or not, it seems the if statement following the for loop always gets triggered. I've tried debugging by checking the value of list_hu and list_hidden outside the for loop. The for loop seems to be updating both list_hidden and list_hu with the guessed letters.

Why is the program behaving so?

0 Answers0