'for char in word:' not working in Python

Question:

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" )
Asked By: Chazza Moo

||

Answers:

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.

Answered By: Marcin Cuprjak
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.