Hangman Python Repeats Functions - python

When I try to run the code it keeps repeating,"So far you have guessed" when I only want it to repeat once. The output for the name when a guess is made should be like : secret_word = hello , then after every word it should be h???o or h?ll?
def get_secret_word():
while True:
secret_word = input('Please enter a word to be guessed\nthat does not contain ? or whitespace:')
if not ('?' in secret_word or ' ' in secret_word or secret_word == ''):
return secret_word
def is_game_over(wrong_guess, secret_word, output, chars_guessed):
if wrong_guess == 7:
print('You failed to guess the secret word:', secret_word)
return True
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '?'
if not ('?' in output):
print('You correctly guessed the secret word:', secret_word)
return True
else:
return False
def display_hangman(wrong_guess):
if wrong_guess == 1:
print('\n |')
elif wrong_guess == 2:
print('\n |', '\n O')
elif wrong_guess == 3:
print('\n |', '\n O', '\n |')
elif wrong_guess == 4:
print('\n |', '\n O', '\n/|')
elif wrong_guess == 5:
print('\n |', '\n O', '\n/|\\')
elif wrong_guess == 6:
print('\n |', '\n O', '\n/|\\', '\n/')
elif wrong_guess == 7:
print('\n |', '\n O', '\n/|\\', '\n/', '\\')
def display_guess(secret_word, chars_guessed):
output = ''
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '\nSo far you have guessed: '
for guess in chars_guessed:
output += guess + ","
print(output.strip(","))
def get_guess(secret_word, chars_guessed):
while True:
guess_character = input('Please enter your next guess: ')
if guess_character == '':
print('You must enter a guess.')
continue
elif len(guess_character) > 1:
print('You can only guess a single character.')
elif guess_character in chars_guessed:
print('You already guessed the character:', guess_character)
else:
return guess_character
def main():
wrong_guess = 0
chars_guessed = []
secret_word = get_secret_word()
output = ''
while not is_game_over(wrong_guess, secret_word, output, chars_guessed):
display_hangman(wrong_guess)
display_guess(secret_word, chars_guessed)
guess_character = get_guess(secret_word, chars_guessed)
chars_guessed.append(guess_character)
chars_guessed.sort()
if not guess_character in secret_word:
wrong_guess += 1
return wrong_guess
pass
if __name__ == '__main__':
main()

so issues that I can see are:
indentation issues(as pointed out by some of the other posters already):
- get_secret_word() function with the if statement
- display_hangman() function with all the elif's
also with the below bit of code from the main function
if not guess_character in secret_word:
wrong_guess += 1
return wrong_guess
pass
this exits out of the app for me and as far as I can see the return and pass lines are not needed. The return exits from the main function when an incorrect guess is made and so pass is never reached and since the wrong_guess is a "global" variable in the main function the new count is available to everything in that function for the length of time that the function is active.
as for the repeated looping with displaying the users guesses it is the way in how you are looping in the display_guess() function. in the case that the character being guessed is not in the secret word it loops over everything twice, once for the outer for loop and then again for the inner loop.
I think you should change the display_guess() to something like the below. this way a user will always see what they have previously guessed
def display_guess():
output = "\nSo far you have guessed: "
count = 0
if len(chars_guessed) > 0:
for guess in chars_guessed:
if count < len(chars_guessed) and count != 0:
output += ','
output += guess
count +=1
print output
as for displaying the secret word with the guessed characters and the rest as ?'s, it doesn't seem that you are printing the value of the output variable from the is_game_over() function anywhere. i haven't tested it but adding a print just after that for loop should sort that out.
on a side note you might wish to add validation on user input as it excepts numbers and special characters

Related

Loop breaks without executing the last print statement

I've written a hangman program in python. The program is finished, but I have a problem with my main function. If I set a win or loss, it no longer execute my print statements from before. This means that if I have to guess a word, for example, it doesn't fill in the last letter in the placeholder, it just breaks out the loop without filling in the last letter. The same goes with my hangman. If I don't have any more attempts left, it won't finish drawing my hangman (just leave out the last part). Who knows why that is? Please help
Here is my code:
##### HANGMAN IN PYTHON #####
count_attempts = 0
guess_word = []
def guidance():
print('Welcome to Hangman in Python!')
print('''The point here is to guess a word by trying out letter combinations and
defining them with ENTER.''')
print('''For each word, you have 10 tries! If you can not solve the word,
the game is over.''')
print('You have 9 attempts to guess the word.')
print('Have fun!')
print('')
def user_word():
userinput = str(input("Type in the word you want to be guessed: "))
for character in userinput:
if character.isdigit():
print('There is a number in your word!')
userinput = str(input('Please try again: '))
return userinput.upper()
def change(userinput):
global guess_word
list_WordToBeGuessed = list(userinput)
for characters in list_WordToBeGuessed:
guess_word.append(' _')
def play_game(userinput):
global count_attempts
length_word = len(userinput)
user_guessed = []
print('Word to guess: ', *guess_word)
print("")
list_WordToBeGuessed = list(userinput)
guess = str(input('Guess a letter: ')).upper()
for number in guess:
if number.isdigit():
guess = str(input('Input not valid. Guess a letter: ')).upper()
if guess in user_guessed:
print('You have already given this letter. ')
elif guess in list_WordToBeGuessed:
user_guessed.append(guess)
print("You've guessed a letter correctly!")
for i in range(0, length_word):
if list_WordToBeGuessed[i] == guess:
guess_word[i] = guess
else:
count_attempts += 1
user_guessed.append(guess)
print('Sry your given letter is not in the word!')
print("You have failed", count_attempts, "of 5 attempts")
def draw_hangman(count_attempts):
print('-------' )
print(' | ' + ('|' if count_attempts > 0 else ''))
print(' | ' + ('O' if count_attempts > 1 else ''))
print(' | ' + ('/ \\' if count_attempts > 2 else ''))
print(' | ' + ('|' if count_attempts > 3 else ''))
print('--- ' + ('/ \\' if count_attempts > 4 else ''))
print("")
def main():
guidance()
userinput = user_word()
change(userinput)
while True:
draw_hangman(count_attempts)
play_game(userinput)
if count_attempts >= 5:
print("You haven't any attempts left. Bad luck")
break
elif ' _' not in guess_word:
print("")
print('You won, congratulation!')
break
main()
you are breaking out of a loop before it can draw the hangman and word.
in the endgame conditions, you can simply call draw_hangman(count_atttempts) before each print statement and change(userinput) as well.
Edit:
You will have to redraw the word as well. Since this is built into your play_game() function it is difficult, but you can use
for i in guess_word:
guess = guess + i + " "
print(guess)
before the print statements along with the draw_hangman(count_attempts) change you made before. Please note you will need to create a new variable called guess in your main() function prior to adding this code.
Since you have a "break" in your endgame condition, the loop stops and last "draw_hangman(count_attempts)" is not called. You can simply add "draw_hangman(count_attempts)" before "print("You haven't any attempts left. Bad luck")"

How terminate this loop after a a given number of attempts?

For the most part it seems to be working, but not how I'm trying to get it to work. When I run it I am allowed unlimited tries to guess every single letter in the word until I spell out the word.
But that's not what I am going for, I'm trying to give the users 5 guesses with single letters if the letter is in the word then it will tell them "Yes", there is a(n) (users guess) in my word, but if the letter is not in my word then it will tell them "No", there is not a(n) (users guess) in my word.
After 5 attempt's at guessing different letters I want them to have to guess the full word but I can't figure out how.
This is what I have now:
import random
def get_word():
words = ['cat', 'dog', 'man', 'fox', 'jar']
return random.choice(words).upper()
def check(word,guesses,guess):
status = ''
matches = 0
for letter in word:
if letter in guesses:
status += letter
else:
status += '*'
if letter == guess:
matches += 1
count = 0
limit = 5
if matches > 1:
print ('Yes! there is a(n)',guess,' in my word.')
guesses += guess
elif matches ==1:
print ('Yes! there is a(n)',guess,' in my word.')
guesses += guess
while count > limit:
input('What do you think my word is')
else:
print('No, there is not a(n)',guess,' in my word.')
guesses += guess
while count > limit:
input('What do you think my word is')
return status
def main():
word = get_word()
guesses = ""
guessed = False
print ('I am thinking of a 3 letter word with no repeating letters. You get five guesses of the letters in my word and then you have to guess the word.')
while not guessed:
text = 'Guess a letter in my word:'
guess = input(text)
guess = guess.upper()
count = 0
limit = 5
if guess in guesses:
print ('You already guessed "' + guess + '"')
elif len(guess) == len(word):
guesses += guess
if guess == word:
guessed = True
else:
print('No, there is not a(n) "' + guess + '"')
elif len(guess) == 1:
guesses += guess
result = check(word,guesses,guess)
if result == word:
guessed = True
else:
print (result)
else:
print ('Invalid entry.')
print ('Yes! you correctly guessed')
main()
For starters while not guessed: will continue until guessed is true -> the word was guessed. Next if you want there to be 5 guesses then an answer guess you want to do for i in range(0, 5): then run your guess logic replacing
if result == word:
guessed = True
with
if result == word:
guessed = true
break
to break out of the loop on a correct guess. Then to allow a guess afterwards, outside of the loop, check if already guessed and allow a guess if not.
Also as a side note you should check that they enter one character with something like
guess = input(text)
while len(guess) != 1:
guess = input(text)
I tried to mostly keep your original code and trail of thought. The main changes I made was getting rid of the check-function as I felt it didn't do anything too useful. I also changed the guessed-variable into a list, and utilized it's properties for your evaluations.
import random
def get_word():
words = ['cat', 'dog', 'man', 'fox', 'jar']
return random.choice(words).upper()
def main():
word = get_word()
guesses = []
guessed = False
print('I am thinking of a 3 letter word with no repeating letters.'
' You get five guesses of the letters in my word and then you have'
' to guess the word.\n')
while not guessed and len(guesses)<5:
text = 'Guess a letter in my word:\n'
guess = input(text)
guess = guess.upper()
if guess in guesses:
print ('You already guessed "', guess, '"\n')
elif len(guess) > 1:
guesses.append(guess)
if guess == word:
guessed = True
else:
print('No, ', guess, 'is not the word!\n')
elif len(guess) == 1:
guesses.append(guess)
if guess in word:
print('Yes there is a(n) ', guess, 'in the word!\n')
else:
print('No, there is not a(n)', guess, 'in the word!\n')
else:
print ('Invalid entry.\n')
if guessed:
print ('You correctly guessed the word!\n')
else:
correct_guesses = [guess for guess in guesses if guess in word]
print('Last chance, what is the full word? (HINT: You have'
'correctly guessed ', str(correct_guesses), ')"')
fword = input()
if fword.upper() == word:
print('You correctly guessed the word!\n')
else: print('Tough luck! You are out of chances! The correct'
'word was ', word, '\n')
main()
playing = True
while playing:
print('Would you like to play again?')
answ = input()
if answ.upper() == 'YES':
main()
else:
print('Thank you for playing.')
playing = False

Basic hang man game Python

word = input('Enter a word to guess: ')
for n in range(50):
print('')
Lives = 10
playing = True
lettersGuessed = ''
while playing == True:
print(str(Lives)+' Lives left')
if Lives == 0:
playing = False
print('You lose')
else:
for char in word:
if char in lettersGuessed:
print(char, end=' ')
else:
print('_', end=' ')
guess = input('\nEnter a letter to guess: ')
if guess in word:
lettersGuessed += guess
else:
Lives = Lives-1
How would i be able to add a way that the user can win? I've tried comparing the letters guessed with the original word but that didn't work. Any help is greatly appreciated.
The easiest implementation. Add a boolean variable won that is initialized to True; if any _ is printed, set it to False. It remains True only if no _ was printed:
won = True
for char in word:
if char in lettersGuessed:
print(char, end=' ')
else:
print('_', end=' ')
won = False
if won:
print("Hey, you win!")

Hangman Python Error

I keep getting an EOF error when I try to run the code. I was wondering how I can fix this? Thanks in advance.When I try to remove if_name_ the program does not have any syntax errors but it does not run.
Here is a link that shows the error: codepad.org/d5p1Mgbb
def get_secret_word():
while True:
secret_word = input('Please enter a word to be guessed\nthat does not contain ? or whitespace:')
if not ('?' in secret_word or ' ' in secret_word or secret_word == '' ):
return secret_word
def is_game_over(wrong_guess,secret_word,output,chars_guessed):
if wrong_guess == 7:
print('You failed to guess the secret word:',secret_word)
return True
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '?'
if not('?' in output):
print('You correctly guessed the secret word:',secret_word)
return True
else:
return False
def display_hangman(wrong_guess):
if wrong_guess == 1:
print('\n |')
elif wrong_guess == 2:
print('\n |','\n 0')
elif wrong_guess == 3:
print('\n |','\n 0','\n |')
elif wrong_guess == 4:
print('\n |','\n 0','\n/|')
elif wrong_guess == 5:
print('\n |','\n 0','\n/|\\')
elif wrong_guess == 6:
print('\n |','\n 0', '\n/|\\','\n/')
elif wrong_guess == 7:
print('\n |','\n 0','\n/|\\','\n/','\\')
def display_guess(secret_word,chars_guessed):
print("")
output = ''
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '?'
if '?' in output:
output += '\nSo far you have guessed: '
for guess in chars_guessed:
output += guess + ","
print(output.strip(","))
def get_guess(secret_word,chars_guessed):
while True:
guess_letter = input('Please enter your next guess: ')
if guess_letter == '':
print('You must enter a guess.')
continue
elif len(guess_letter) > 1:
print('You can only guess a single character.')
elif guess_letter in chars_guessed:
print('You already guessed the character:',guess_letter)
else:
return guess_letter
def main():
wrong_guess = 0
chars_guessed = []
secret_word = get_secret_word()
output=''
while not(is_game_over(wrong_guess,secret_word,output,chars_guessed)):
display_hangman(wrong_guess)
display_guess(secret_word, chars_guessed)
guess_character = get_guess(secret_word, chars_guessed)
chars_guessed.join(guess_letter)
chars_guessed.sort()
if not guess_letter in secret_word:
wrong_guess += 1
return wrong_guess
pass
if __name__ == '__main__':
main()
A few things I found...
guess_character and guess_letter appear to be the same variable, but guess_letter is used before defined.
input allows for the entry of variable names or any block of python code. In order to use input as strings you must force input to string or (much easier) use raw_input
You were attemption to do a join operation on a list. This isn't possible. You can add an item to a list with append though.
So, here's the code with a few fixes. You'll have to fix the print loops but it should be better and get you past the earlier errors.
def get_secret_word():
while True:
secret_word = raw_input('Please enter a word to be guessed\nthat does not contain ? or whitespace:')
if not ('?' in secret_word or ' ' in secret_word or secret_word == '' ):
return secret_word
def is_game_over(wrong_guess,secret_word,output,chars_guessed):
if wrong_guess == 7:
print('You failed to guess the secret word:',secret_word)
return True
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '?'
if not('?' in output):
print('You correctly guessed the secret word:',secret_word)
return True
else:
return False
def display_hangman(wrong_guess):
if wrong_guess == 1:
print('\n |')
elif wrong_guess == 2:
print('\n |','\n 0')
elif wrong_guess == 3:
print('\n |','\n 0','\n |')
elif wrong_guess == 4:
print('\n |','\n 0','\n/|')
elif wrong_guess == 5:
print('\n |','\n 0','\n/|\\')
elif wrong_guess == 6:
print('\n |','\n 0', '\n/|\\','\n/')
elif wrong_guess == 7:
print('\n |','\n 0','\n/|\\','\n/','\\')
def display_guess(secret_word,chars_guessed):
print("")
output = ''
for guess in secret_word:
if guess in chars_guessed:
output += guess
else:
output += '?'
if '?' in output:
output += '\nSo far you have guessed: '
for guess in chars_guessed:
output += guess + ","
print(output.strip(","))
def get_guess(secret_word,chars_guessed):
while True:
guess_letter = raw_input('Please enter your next guess: ')
if guess_letter == '':
print('You must enter a guess.')
continue
elif len(guess_letter) > 1:
print('You can only guess a single character.')
elif guess_letter in chars_guessed:
print('You already guessed the character:',guess_letter)
else:
return guess_letter
def main():
wrong_guess = 0
chars_guessed = []
secret_word = get_secret_word()
output=''
while not(is_game_over(wrong_guess,secret_word,output,chars_guessed)):
display_hangman(wrong_guess)
display_guess(secret_word, chars_guessed)
guess_character = get_guess(secret_word, chars_guessed)
chars_guessed.append(guess_character)
chars_guessed.sort()
if not guess_character in secret_word:
wrong_guess += 1
return wrong_guess
pass
if __name__ == '__main__':
main()

Hangman game trouble with keep_playing

So I'm new to python and went trough a tutorial to write a hangman game in python 2.7 on my new pi. Well, anyway I liked the code and everything, and it ran fine but then I wanted to add something to make it ask ,"if you wanted to continue playing", and I did a lot of research and talked on some chat rooms about it and came up with/found this script to exit:
while keep_playing == False:
user = raw_input("\n\tShall we play another game? [y|n] ")
again = "yes".startswith(user.strip().lower())
if again:
keep_playing = True
if not again:
break
raw_input ("\n\n\nPress enter to exit")
but I get this error:
Traceback (most recent call last):
File "/home/pi/Desktop/Scripts/scrappy/ls/ls/hangman3.py", line 40, in <module>
while keep_playing == False:
NameError: name 'keep_playing' is not defined
when its ran with this script
import random
import urllib
print 'time to play hangman'
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
secret = random.choice(animals)
guesses = 'aeiou'
turns = 5
while turns > 0:
missed = 0
for letter in secret:
if letter in guesses:
print letter,
else:
print '_',
missed += 1
print
if missed == 0:
print 'You win!'
break
guess = raw_input('guess a letter: ')
guesses += guess
if guess not in secret:
turns -= 1
print 'Nope.'
print turns, 'more turns'
if turns < 5: print ' O '
if turns < 4: print ' \_|_/ '
if turns < 3: print ' | '
if turns < 2: print ' / \ '
if turns < 1: print ' d b '
if turns == 0:
print 'The answer is', secret
while keep_playing == False:
user = raw_input("\n\tShall we play another game? [y|n] ")
again = "yes".startswith(user.strip().lower())
if again:
keep_playing = True
if not again:
break
raw_input ("\n\n\nPress enter to exit")
Can anyone help me?
****edit*****
someone can close this tread using the tips provided i have solved my problem this is the final code
import random
import urllib
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
while True:
print 'time to play hangman'
secret = random.choice(animals)
guesses = 'aeiou'
turns = 5
while turns > 0:
missed = 0
for letter in secret:
if letter in guesses:
print letter,
else:
print '_',
missed += 1
print
if missed == 0:
print 'You win!'
break
guess = raw_input('guess a letter: ')
guesses += guess
if guess not in secret:
turns -= 1
print 'Nope.'
print turns, 'more turns'
if turns < 5: print ' O '
if turns < 4: print ' \_|_/ '
if turns < 3: print ' | '
if turns < 2: print ' / \ '
if turns < 1: print ' d b '
if turns == 0:
print 'The answer is', secret
break
user = raw_input("\n\tShall we play another game? [y|n] ")
again = "yes".startswith(user.strip().lower())
if not again:
raw_input ("\n\n\nPress enter to exit")
break
I'm not into python, but I can see you're indeed trying to compare an empty/undefined variable "keep_playing" to false. To my knowledge, you can't compare a variable to something, if you haven't declared the variable before the comparison, not sure if this is different in Python though.
What happens if you write this line along the other variables:
keep_playing = False
so you'll get :
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
secret = random.choice(animals)
guesses = 'aeiou'
turns = 5
keep_playing = False
animals = urllib.urlopen('http://davidbau.com/data/animals').read().split()
secret = random.choice(animals)
guesses = 'aeiou'
turns = 5
keep_playing = False
if guess not in secret:
turns -= 1
print 'Nope.'
print turns, 'more turns'
if turns < 5: print ' O '
if turns < 4: print ' \_|_/ '
if turns < 3: print ' | '
if turns < 2: print ' / \ '
if turns < 1: print ' d b '
if turns == 0:
print 'The answer is', secret
keep_playing = False
This should do it

Categories

Resources