Reputation: 1
I am trying to do a hangman code in python 2.7 and I'm getting the type error around the line that says
print char.
I'm sorry, I forgot to add the rest of the code. Here's the full code. Word is coming from a dictionary file.
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
print " ", len(wordlist), "words loaded."
return wordlist
def choose_word(wordlist):
return random.choice(wordlist)
wordlist = load_words()
print "Welcome to Hangman where your wits will be tested!"
name = raw_input("Input your name: ")
print ("Alright, " + name + ", allow me to put you in your place.")
word = random.choice(wordlist)
print ("My word has ")
print len(word)
print ("letters in it.")
guesses = 10
failed = 0
for char in word:
if char in guesses:
print char,
else:
print "_",
failed += 1
if failed == 0:
print "You've Won. Good job!"
break
#
guess = raw_input("Alright," + name + ", hit me with your best guess.")
guesses += guess
if guess not in word:
guesses -= 1
print ("Wrong! I'm doubting your intelligence here," + name)
print ("Now, there's only " + guesses + " guesses left until the game ends.")
if guesses == 0:
print ("I win! I win! I hanged " + name + "!!!")
Upvotes: 0
Views: 4946
Reputation: 122023
You try:
if char in guesses:
However, guesses
is just the count of the number of guesses left, an integer, so you can't iterate over it. Perhaps you should also store the previous guesses and use that:
guess_list = []
...
if char in guess_list:
...
guess_list.append(guess)
For the same reason, if you got that far
guesses += guess
would fail - guess
is a string and guesses
an integer, which can't be added together.
Upvotes: 1