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')
Related
Hangman. As you probobly understand i am new to coding and python, sorry for bad code.
The best way i can think of to describe this problem is through the following way: In the "try:" section i try to index = list_of_letters.index(guesssed_letter_string). i want to check if the guessed_letter_string is in list_of_letters: i earlier in the code translate the input from well the only input() in the code to guessed_letter_string (its the same thing). when you input a letter in the middel of the word it works like index[3] but when you input the first letter in the word the index locks at 0 and every other letter replaces it. is there a way to fix this
import random
list_of_words = ["mom", "dad", "sister", "brother"]
random_word = random.choice(list_of_words)
list_of_letters = list(random_word)
print(random_word)
print(list_of_letters)
rounds_failed = 1
rounds_max = 16
list_of_letters_guessed = []
under_grejer = []
count_of_right_letters_list = []
print(f"You have {rounds_max - rounds_failed} rounds left to find out the word")
for every in list_of_letters:
under_grejer.extend("_")
while True:
if rounds_failed == rounds_max:
print("To many attempts, no more rounds")
break
if len(list_of_letters) == 0:
print("YOU FUCKING WON")
break
print(f"This is round: {rounds_failed}")
print(" ".join(under_grejer))
print("Letters that are correct(not in order): "+", ".join(count_of_right_letters_list))
print("List of letters guessed: "+", ".join(list_of_letters_guessed))
guess = input("NAME A Letter: ")
guess_letters_list = (list(guess))
guess_count_letters = len(guess_letters_list)
if guess_count_letters > 1:
print("Dummy you just need to input a letter, nothing else")
guesssed_letter_string = " ".join(guess_letters_list)
try:
index = list_of_letters.index(guesssed_letter_string)
print("Congrats you got the letter: " + guesssed_letter_string)
print(f"thats the {index + 1}nd letter in the word")
rounds_failed += 1
count_of_right_letters_list.extend(guesssed_letter_string)
print(index)
list_of_letters.pop(index)
under_grejer[index] = guesssed_letter_string
except ValueError:
print("try again mate that letter was not in the word")
list_of_letters_guessed.append(guesssed_letter_string)
rounds_failed += 1
continue
It's not about the first letter only. Your problem is that with list_of_letters.pop(index) you remove the guessed letter form list_of_letters; parts of your code rely on this to check if you guessed all occurrences of that letter before already, but on the other hand this reduces the index of all letters behind the guessed one for later iterations.
For example, for brother, if you guess r it correctly says position 2, but if you then guess o next, it again says position 2 because your list_of_letters now reads ["b","o","t","h","e","r"].
You could either try to work with list_of_letters_org = list_of_letters.copy() which you will never change, and pick the right one for every task, or you could for example change the program structure by adding a list of booleans that store which letters were guessed already.
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:
I want to create the hangman python game, so I created a simpler piece of the game. The idea of the game is to guess the letters in a randomly generated word. Here is what I have so far. I listed the problem and questions I have at the bottom.
import random
words = ['holiday', 'american', 'restaurant', 'computer', 'highschool', 'programming']
random_word = random.choice(words)
count = 0
while True: #repeatedly asks you to guess the letter in a random word
guess = str(input("Guess a letter: "))
guess = guess.lower()
if guess in random_word: #checks if the letter you input is in the random generated word
print("Yay, its in the word")
else:
count += 1
print("Not in the word, attempts: %d" % count)
if count > 5:
print("You have reached max attempts")
print("Sorry, but hangman died! You lose")
break
else:
continue
The problem I have: When the user guesses a letter, they can guess it again infinite times. How can I make it so that the user can't repeatedly guess the same letter?
Is there a way to make sure the user doesn't guess the same letter? This could be a problem in an actual hangman game when there are several letters that are the same. Any help/feedback appreciated, thanks!
Here is one way of doing it.
import random
words = ['holiday', 'american', 'restaurant', 'computer', 'highschool', 'programming']
random_word = random.choice(words)
count = 0
guess_list = []
while True: #repeatedly asks you to guess the letter in a random word
guess = str(input("Guess a letter: "))
guess = guess.lower()
if guess not in guess_list:
if guess in random_word: #checks if the letter you input is in the random generated word
print("Yay, its in the word")
else:
count += 1
print("Not in the word, attempts: %d" % count)
if count > 5:
print("You have reached max attempts")
print("Sorry, but hangman died! You lose")
break
else:
print("You have already guessed {}. Try again".format(guess))
print(set(guess_list))
guess_list.append(guess)
Sample output (word is computer):
Guess a letter: c
Yay, its in the word
Guess a letter: e
Yay, its in the word
Guess a letter: e
You have already guessed e. Try again
{'e', 'c'}
Guess a letter: e
You have already guessed e. Try again
{'e', 'c'}
Guess a letter: w
Not in the word, attempts: 1
Guess a letter: m
Yay, its in the word
Guess a letter: m
You have already guessed m. Try again
{'w', 'm', 'e', 'c'}
Guess a letter:
Notes:
A guess_list is created that keeps record of all the guesses.
After each guess the letter is appended to the list.
When the user repeats the guess they are warned. We use a set so only the unique elements in the guess list are displayed.
The code can be refined further, but must do the job.
Depending on the word, you may need to allow multiple guesses if the letter appears more than once. (this may not be your requirement. Not familiar with the game.)
Approach
What you need is a store that keeps track of the number of occurrences of each letter in the word.
Something like:
letterCounts = Counter("hello") # word: 'hello' => {'h': 1, 'e': 1, 'l': 2, 'o': 1}
I'm using the counter collection here.
Then you can decrement the count of the guessed letter
if guesses_letter in list(letterCounts.elements()):
if (letterCounts[guessed_letter] > 0):
letterCounts[guessed_letter] -= 1
else:
# the letter can't be repeated now. do the needful here.
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.
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.