Hangman program in python 3.x - python

print("Welcome to Hangman! Guess the mystery word with less than 6 mistakes!")
words= ['utopian','fairy','tree','monday','blue']
i=int(input("Please enter a number (0<=number<10) to choose the word in the list: "))
if(words[i]):
print("The length of the word is: " , len(words[i]))
guess=input("Please enter the letter you guess: ")
if(guess in words[i]):
print("The letter is in the word.")
else:
print("The letter is not in the word.")
guesses=1
while guesses<6:
guess=input("Please enter the letter you guess: ")
if(guess in words[i]):
print("The letter is in the word.")
guesses=guesses+1
else:
print("The letter is not in the word.")
guesses=guesses+1
if guesses==6:
print("Failure. The word was:" , words[i])
Just started on this Hangman program in python. I'm doing this on a step by step based on a set of instructions and I'm at the point where I want to write some simple code that checks whether the letter entered is found in the chosen word at all. I'm ignoring the position of the matches, only concerned with counting the number of bad guesses. So far so good it seems, but I've encountered a small but big (if that makes sense) problem. On the sixth bad guess I want the loop to finish and let the user know that they failed and the computer won. I noticed that in my case the loop finishes once the user has entered their sixth guess, whether it be bad or good. So if the word is 'fairy' or whatever, no matter how many correct letters that the user guessed the loop will finish regardless on their 6th go. I want the loop to finish only when the user has entered six bad guesses, so in the example of the word 'fairy' if the user inputs 'f' which would be correct and if the next six guesses are incorrect the "failure" message will be printed as opposed to what I have now.

You have this code:
if(guess in words[i]):
print("The letter is in the word.")
guesses=guesses+1
If you remove that last line, then good guesses won't be counted against you.
Also, I'd be careful about your whitespace. The way you have the question now, only the one guess=input("Please enter the letter you guess: ") line is in the while loop. I'm guessing that is a simple mistake putting the code on StackOverflow, though.

It's a slightly unconventional answer, but here's some edited code with commentary.
print("Welcome to Hangman! Guess the mystery word with less than 6 mistakes!")
words= ['utopian','fairy','tree','monday','blue']
i=int(raw_input("Please enter any number to choose the word in the list: "))%5
#the %6 here means divide the input by six and take the remainder as the answer. I found the instructions a little confusing, and this allows the user to be competely unrestricted in the number that they choose while still giving you a number (0, 1, 2, 3, or 4) that you want. Increasing the number after the % will give you a larger variety of choices.
# if(words[i]):
#this line is unnecessary with the above code, and also would not prevent errors futher along in the code if i was not a number between 0 and 4.
print "Your chosen word is", len(words[i]), "characters long."
# slight wording change here
#guess=input("Please enter the letter you guess: ")
#if(guess in words[i]):
#print("The letter is in the word.")
#else:
#print("The letter is not in the word.")
#guesses=1
# all of this is already accomplished in the loop you wrote below.
incorrect_guesses = 0
# it's always nice to initialize a variable
while incorrect_guesses<6:
guess=str(raw_input("Please enter a letter to guess: "))
# Unless you're using python 3, I would use raw_input rather than input.
if((guess) in words[i]):
print('Correct! The letter "' + guess + '" appears in the word ' + str(words[i].count(str(guess))) + ' times.')
else:
print('Sorry, the letter "' + guess +
'" is not in the word.')
incorrect_guesses=incorrect_guesses+1
# Plusses instead of commas clean up the output a bit, and str(words[i].count(str(guess))) gives you the string form of the number which indicates how many times the guess appears in the word. This is useful in words like "tree".
print("Failure. The word was:" , words[i])
# This is outside the while loop because it gets triggered as soon as incorrect guesses go over 6.
# You can still improve the program by adding a feature which tells the players that they have guessed all of the correct letter and telling them what the word was, and possibly by increasing the word list. You can also tell players when they have already guessed a letter in case they've forgotten.
Hopefully this will be helpful to you in your future python endeavors.

Related

Which variable should I use on Python to uppercase results in type word guessing game

I'm writing a word guessing game like, what I'm expecting is that results appear in uppercase when is on the right spot. Until now, I write the program and it completely works but, let me show you... This is how it goes:
print("Welcome to the word guessing game!")
print(" ")
secret_word = "heaven"
guess_count = 0
display = '_'*len(secret_word)
(len(secret_word)-1)
word = ["_"] * len(secret_word)
while True:
guess = input("What is your guess? ")
for i in range(len(secret_word)):
if guess == secret_word[i]:
word[i] = guess
if guess == secret_word:
print("")
print("You guessed it!")
break
else:
print("".join(word))
guess_count = guess_count+1
print(f"It took you {guess_count} guesses")
So, I'm not sure where to put the uppercase function.
Since the letters are not present at all in the secret word, it shows an "_".
The letters that are present in the secret word, but in a different spot should be shown as lowercase.
The Letters that are present in the secret word at that exact spot, shown in uppercase.
I tried to find the answer on YT and other sites without success. I just want to understand which functions using (.uppercase) I can use to make it.
Hope you can help me, guys. Thanks in advance!
I do not understand. In your code, it seems as though the guess is a single character, but you do not ask for the spot which is needed to determine if it must be uppercase or lowercase. I tried to answer your question based on wordle, so I guessed the player would have to enter a word.
You'd need something like:
for i in range(len(secret_word)):
if guess[i] = secret_word[i]:
word[i] = guess[i].upper()
elif guess[i] in secret_word:
word[i] = guess[i].lower

Simple hangman game using while and if-else loop does not iterate correctly

I am trying to design a hungman game using simple while loop and if else statement.
Rules of the game:
1.Random word is selected from a list of words
2.User is informed when the word is selected and asked to provide his/ her first guess
3.If the user's guess is correct, the letter is console and inform the user how many letters left
The user will get only 5 lives to play the game.
1.import random
2.import string
3.def hungman():
4.words = ["dog", "monkey", "key", "money", "honey"]
5.used_letters = []
6.word = words[random.randrange(len(words))]
7.lives=5
8.while len(word) > 0 and lives > 0:
9.guess = input("Please guess the letter: ")
10.if 'guess' in word:
11.print(guess, " is a correct guess")
12.used_letters.appened(guess)
13.if used_letters.len == word.len:
14.print("Congratulation, You have guessed the correct letter: ",word)
15.else:
16.remaining_letters = word.len - used_letters.len
17.print("You have", remaining_letters, "left")
18.else:
19.lives = lives - 1
20.if lives == 0:
21.print("Sorry! you don't have more lives to continue the game")
22.print("Correct word is: ", word)
23.break
24.else:
25.print("You have", lives , " left")
26.hungman()
The program should ask for the user input which will store in guess variable. If the letter given by the user is one of the letters of word string then the code prompts that the given input is correct and append the letter in the used_letters list. Else it shows the length of the remaining letters for wrong user input. Additionally, if the user fails to guess the letter correctly he or she will lose 1 life as well.
However, as per my code after the while loop in line number 8 the control goes to line no. 18 although I provided correct letter as user input. Line 10 to 17 totally discarded. I could not find the reason of this nature.
Please help me in this regard.
Thank you
You have a couple of issues in your code.
The one you mentioned is because of quotation marks in line 10. Should be
if guess in word:
in line 12 you have a typo
used_letters.append(guess)
to get the length of a list you should use function len(), e.g.
if len(used_letters) == len(word)
And finally you have an issue with exiting the loop in case of the correct answer. You should use
while len(word) > len(used_letters) and lives > 0:

Can't determine why program terminates early

I was working on this assignment for the EdX MIT Python course and decided I wanted the output to display differently. Based on my code, I thought that the task program would end when guesses = 0. However, I'm either getting "IndexError: list assignment index out of range" or the program ends at guess 2. This appears to depend on the length of the secretWord. Can anyone point me in the right direction?
def hangman(secretWord):
'''
secretWord: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secretWord contains.
* Ask the user to supply one guess (i.e. letter) per round.
* The user should receive feedback immediately after each guess
about whether their guess appears in the computers word.
* After each round, you should also display to the user the
partially guessed word so far, as well as letters that the
user has not yet guessed.
Follows the other limitations detailed in the problem write-up.
'''
trackedguess = []
letcount = ()
letterlist = []
guess = ''
for i in range(0, (len(secretWord)-1)):
trackedguess.append('_')
letcount = len(secretWord)
guessesleft = 8
for i in range(0, 7):
if ''.join(trackedguess) == secretWord:
print('You win!')
break
if guessesleft < 1:
print('You have 0 guesses remaining.')
break
print(trackedguess)
print("You have ", guessesleft, " guesses remaining.")
guess = input('Please guess a letter and press return: ')
if guess in letterlist:
print("You've already guessed that. Try again.")
else:
guessesleft -= 1
letterlist.append(guess)
for i in range(0, len(secretWord)):
if secretWord[i] in letterlist:
coordinate = i
trackedguess[coordinate] = secretWord[i]
hangman(chooseWord(wordlist))
A few things stick out to me:
range uses an exclusive end. That means range(0, (len(secretWord)-1) will iterate one time less than the length of secretWord. You want the lengths to match. More straightforward, less error-prone approaches would be just: trackedGuess = ['_'] * len(secretWord) or trackedGuess = list('_' * len(secretWord)).
You should verify your assumptions. For example, the above case could have been caught easily if you did assert(len(trackedGuess) == len(secretWord)).
for i in range(0, 7) suffers from the same problem as your earlier usage of range(). If you want to iterate 8 (guessesleft) times, then you should use range(0, 8). However, you're also decrementing guessesleft inside the loop and exiting when it reaches 0. Do one or the other, but not both. As your code currently is, if someone enters a guess that they've already made, it will count one iteration against them (which I'm not sure is what you want).
It's a very good attempt, but there are some things that are wrong. I'm going to try to walk through them one by one.
Instead of a for loop, I'd suggest using a while guessesleft>0. In the current implementation the for loop will run for 8 times regardless of whether or not there are any guesses left (for example, try providing the same letter as a guess every time). With the while, however, you gain much more control over the loop.
The trackedguess generation is flawed. It will always miss the last letter of the secretword (this is also the reason you were getting the IndexError) Try for i in range(len(secretWord)) instead. You'll also find it much more concise and readable.
I also took the liberty of moving the win or lose condition down in the loop. Previously, if you won on the last guess, you'd still lose (because the win check condition happened before the input and after that the loop ended); also, the guess wasn't printed if you won (because the loop would break before the print statement).
Revised code below:
def hangman(secretWord):
'''
secretWord: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secretWord contains.
* Ask the user to supply one guess (i.e. letter) per round.
* The user should receive feedback immediately after each guess
about whether their guess appears in the computers word.
* After each round, you should also display to the user the
partially guessed word so far, as well as letters that the
user has not yet guessed.
Follows the other limitations detailed in the problem write-up.
'''
trackedguess = []
letterlist = []
for i in range(len(secretWord)):
trackedguess.append('_')
guessesleft = 8
while guessesleft > 0:
print(trackedguess)
print("You have ", guessesleft, " guesses remaining.")
guess = input('Please guess a letter and press return: ')
if guess in letterlist:
print("You've already guessed that. Try again.")
else:
guessesleft -= 1
letterlist.append(guess)
for i in range(0, len(secretWord)):
if secretWord[i] in letterlist:
coordinate = i
trackedguess[coordinate] = secretWord[i]
if ''.join(trackedguess) == secretWord:
print(trackedguess)
print('You win!')
break
if guessesleft < 1:
print('You have 0 guesses remaining.')
break
hangman('test')
Hope that helps.

Can't debug basic python program

I'm new to python and have been working through a book. At the end of the chapter there was a challenge to create a game where the computer picks a random word and the player has to guess that word. The computer tells the player how many letters are in the word. The player gets five chances to ask if the letter is in the word. The computer responds with only a yes/no. The player then has to guess the word. Here is my attempt at this:
print ("\t\t\tWelcome to the guess my word challenge")
print ("\nThe computer will pick and random word and you have to guess it in five tries")
import random
#create sequence of words
WORDS = ("computer","laptop","mouse","keyboard")
#pick random word
word=random.choice(WORDS)
correct=word
tries=0
print ("This word has ",len(word), "letters")
i=""
while word != "" and tries<5:
for i in word:
i=input("Guess a letter: ")
if i not in word:
print ("No")
else:
print ("\nYes")
tries+=1
if tries==5:
print("You've run out of tries")
final=input("\nGuess my word: ")
if word==correct:
print ("Well done that was my word!")
else:
print ("Better luck next time")
input ("\n\nPress the enter key to exit")
Now the problem I'm having is I can't get the tries bit to work, eventually the program will say you've run out of tries but I want it to say that after 5 tries. Also, no matter what word I put in at "guess my word", it always displays its correct even if it isn't.
There are two problems with your code.
You ask the user for a letter for each letter in the word, and only then increment the tries counter, then ask again for each letter in the word. Remove the for i in word: loop.
You compare the word to correct, which is just the word itself. Instead, you have to compare it to the user's final guess, i.e. if word==final:
With those two fixes, it should work.
You want to count down the number of times the player guesses. The for loop
for i in word:
will cycle one time for each letter in the word, setting i equal to that letter, but you then reassign i to user input. So if you remove the for loop, it should run as intended.
i=""
while word != "" and tries<5:
i=input("Guess a letter: ")
if i not in word:
print ("No")
else:
print ("\nYes")
tries+=1
if tries==5:
print("You've run out of tries")
[EDIT] Also you're not comparing the correct word to the user input, so you want to say
if correct == final :
import random
word = random.choice(['computer','laptop','mouse','keyboard'])
def guess(tries = 0):
letter = input('Guess a letter: ')
if letter in word:
print('\nYes')
else:
print('No')
tries += 1
if tries == 5:
return
guess(tries)
print('\t\t\tWelcome to the guess my word challenge')
print('\nThe computer will pick and random word and you have to guess it in five tries')
print('This word has {0} letters'.format(len(word)))
guess()
final = input('\nGuess my word: ')
if final == word:
print('Well done that was my word!')
else:
print('Better luck next time')
input('\n\nPress the enter key to exit')

Why is my python program not running the code in the right order?

I just started out in python and I am programming a hangman game base on a book. May I know why is my code below not running in the order that I want it to run?
When I execute the program, the letter guessed in guess is suppose to go into used to indicate which letters has the player already guessed to find out the right word. However, this only happens every 2 turns and not every 1 turn. I've indicated the hangman ACSII art at the start of the program in an image file for reference, below the image are the code. Would gladly appreciate any help. Thanks!
MAX_WRONG = len(HANGMAN)-1
WORDS = ("book","toy","paper","school","house","computer","television")
word=random.choice(WORDS)
so_far = "-"*len(word)
wrong = 0
used = []
print "Welcome to hangman! Guess the the word before the the man is hang dead!"
print "You can only guess one letter at a time!"
while wrong < MAX_WRONG and so_far!=word:
print HANGMAN[wrong]
print "\nYou've used the following letters:\n",used
print "\nSo far, the word is:\n", so_far
guess = raw_input("\n\nEnter your guess:")
guess = guess.lower()
if guess in word:
used+=guess
print "\nYou've used the following letters:\n",used
print"\nYes!",guess,"is in the word!"
new=""
for i in range(len(word)):
if guess == word[i]:
new+=guess
else:
new+=so_far[i]
so_far=new
else:
used+=guess
print "\nYou've used the following letters:\n",used
print "\nSo far, the word is:\n", so_far
print"\nSorry,",guess,"isn't in the word."
guess = raw_input("\n\nEnter your guess:")
wrong+=1
while guess in used:
print "You've already guessed the letter:",guess
print "\nYou've used the following letters:\n",used
print "\nSo far, the word is:\n", so_far
guess = raw_input("Enter your guess:")
guess = guess.lower
if wrong == MAX_WRONG:
print HANGMAN[wrong]
print "\nYou've been hanged!"
else:
print "\nYou guessed it!"
print "\nThe word was",word
raw_input("\n\nPress the enter key to exit.")
It appears to be happening 2 turns, but that is not the case. The problem is that your program prompts the user twice in a single turn. At the start of the loop you ask the user for a letter. If it was tell me it was wrong, then you ask for another letter. Then your loop repeats and you ask for a letter again.
The problem is that you are asking for a letter twice within the loop, not once. In programming we have what is called the DRY principle which means don't repeat yourself. Your code shows one of many reasons not to repeat yourself. You thought that your loop was running twice, but you were actually just running the same code multiple times in your loop.

Categories

Resources