Search code examples
pythonrandomchar

'for char in word:' not working in Python


I'm making a simple hangman game and I've got a word list on my computer with about 5,000 word, I made a list out of those words then used the random function to choose one at random for the game, but it prints one too many of these: '-', when trying to guess the word, I used the command 'for char in word:' to count the characters and print the right amount of '-'.

import time
import random

List = open("nouns.txt").readlines()

name = input("What is your name? ")

print ("Hello, ", name, "Time to play hangman!")

time.sleep(1)

print ("Start guessing...")
time.sleep(0.5)

Word = random.choice(List)

guesses = ''
turns = 20

while turns > 0:         

    failed = 0

    for char in Word:      

        if char in guesses:    

            print (char)

        else:

            print ("_")     

            failed += 1    

    if failed == 0:        
        print ("\nYou won" ) 

        break              

    guess = input("guess a character:") 

    guesses += guess                    

    if guess not in Word:  

        turns -= 1        

        print ("Wrong")    

        print ("You have", + turns, "more guesses")

        print ("The word was ", Word)

        if turns == 0:           

            print ("You Loose" )

Solution

  • The reason here is that you read lines from file and each line has a 'new-line' ('\n') character at the end. When you iterate over characters you get this one as the last character.

    You can use strip() method to get rid of it: Word = random.choice(List).strip()

    And I think you should use raw_input() instead of input() methods here, or maybe you work with python 3.x then it would be ok.