I attempted to make a simple word guessing game, where the user has 3 attempts to guess a word. If the user guesses the word within 3 attempt, the program returns "Yay, you win!" If they do not guess within the 3 attempts, the program is supposed to return "Out of attempts! You lost!", however I am not getting any output when the user fails the game.
The program also tells the user how many guesses he has remaining after each incorrect guess, (except the last guess, where the output should be "Out of attempts! You lost!".
secret_word = "giraffe"
guess = ""
guesses_remaining = 3
out_of_guesses = False
while secret_word != guess:
if guesses_remaining != 0:
guess = input("Enter guess: ")
guesses_remaining -= 1
if guesses_remaining != 0:
if secret_word != guess:
print("You have " + str(guesses_remaining) + " guesses remaining!")
else:
out_of_guesses = True
if out_of_guesses == False:
print("Yay, you win!")
else:
print("Out of attempts! You lost!")
I can't figure out why I get no output when the user fails to guess within the three attempts.
Since you said that you're brand new to Python, I started out by changing your code as little as possible so you can see how you could fix what you've written to make it work.
Your problem can be fixed by adding and not out_of_guesses to your while statement condition. You could also have added a line with the keyword break after the line out_of_guesses = True. Using breakends whatever loop you are in right away.
secret_word = "giraffe"
guess = ""
guesses_remaining = 3
out_of_guesses = False
#Changing the condition of the while loop makes sure the loop doesn't continue
#after the player is out of guesses
while secret_word != guess and not out_of_guesses:
if guesses_remaining != 0:
guess = input("Enter guess: ")
guesses_remaining -= 1
if guesses_remaining != 0:
if secret_word != guess:
print("You have " + str(guesses_remaining) + " guesses remaining!")
else:
out_of_guesses = True
if out_of_guesses == False:
print("Yay, you win!")
else:
print("Out of attempts! You lost!")
Example output:
Enter guess: fox
You have 2 guesses remaining!
Enter guess: bear
You have 1 guesses remaining!
Enter guess: mouse
Out of attempts! You lost!
I would like to add that your code can be simplified considerably whilst maintaining its behavior:
secret_word = "giraffe"
guesses_remaining = 3
while guesses_remaining > 0:
guess = input("Enter guess: ")
guesses_remaining -= 1
if guess == secret_word:
print("Yay, you win!")
break
else:
print("Out of attempts! You lost!")
You need to break the loop after three unsuccessful attempts.
Try putting break in else after you turn out_of_guesses True.
Related
I am trying to make a game where the user inputs a word with only three guesses available, but instead it keeps allowing four guesses which I don't want.
When i input a word and my guess_count reaches 3, i am supposed to be sent this msg "You have no more guesses, you lose!" then ask if i want to retry but instead it lets me play one more time thereby exceeding the guess_limit
Here is my code
secret_word = "loading"
guess_word = ""
guess_count = 0
guess_limit = 3
end = False
print("Welcome to the guessing game\nYou have 3 guesses")
guess_word = input("Enter a word: ")
def end_msg(msg):
print(msg)
retry = input("Do you want to play again? ")
if (retry == "yes") :
global end, guess_word, guess_count
end = False
guess_word = ""
guess_count = 0
print("Welcome to the guessing game\\nYou have 3 guesses")
guess_word = input("Enter a word: ")
else:
end = True
while (not(end)) :
if (guess_word != secret_word and guess_count \< guess_limit):
guess_count += 1
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_word = input("Try again: ")
elif (guess_count == 3):
end_msg("You have no more guesses, you lose!")
else:
end_msg("Correct, you win")
I see your query already answered above, In case you want I have adapted your code to make it more organized and structured into two functions
playagain - which asks after winning/losing if the user wants to play the game again
play - the actual program to play the game
I removed some redundancies like end = False variable you used and could have also removed some other variables like guess_limiter (by just assigning the guess limit value in the actual program) but I wanted to retain your code as much as possible in case for your understanding, hope this helps
def playagain():
play_again = input("Do you want to play again? (y/n) ")
if play_again == 'y':
return play()
elif play_again == 'n':
print("Thank you for playing")
else:
print("incorrect input please try again")
playagain()
def play():
secret_word = "loading"
guess_word = ""
guess_count = 1
guess_limit = 3
print("Welcome to the guessing game\nYou have 3 guesses")
while (guess_count != guess_limit + 1):
guess_word = input("Enter a word: ")
if guess_word == secret_word:
print("Correct, you win")
playagain()
break
elif guess_count == guess_limit:
print("You have no more guesses, you lose!")
playagain()
break
else:
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_count += 1
play()
You are getting this bug because you wrote guess_limit = 3. You know Programs count from 0, so you need to enter 1 less from your desire try. It should be guess_limit = 2.
And also you wrote elif (guess_count == 3) :, thats mean if guess_count == 3 your will get "You have no more guesses, you lose!" even, user put the right answer. so it should be
elif (guess_word != secret_word and guess_count == 2):
so your final code should be:
secret_word = "loading"
guess_word = ""
guess_count = 0
guess_limit = 2
end = False
print("Welcome to the guessing game\nYou have 3 guesses")
guess_word = input("Enter a word: ")
def end_msg (msg) :
print(msg)
retry = input("Do you want to play again? ")
if (retry == "yes") :
global end, guess_word, guess_count
end = False
guess_word = ""
guess_count = 0
print("Welcome to the guessing game\\nYou have 3 guesses")
guess_word = input("Enter a word: ")
else:
end = True
while (not(end)) :
if (guess_word != secret_word and guess_count < guess_limit) :
guess_count += 1
print("Incorrect!")
print("You have " + str(3 - guess_count) + " left!")
guess_word = input("Try again: ")
elif (guess_word != secret_word and guess_count == 2) :
end_msg("You have no more guesses, you lose!")
else:
end_msg("Correct, you win")
I am trying to loop over my hangman project but cannot seem to figure out a way without creating an infinite loop. I want to avoid having to ask for user input in multiple places in my guess function and be able to put it in in one place. I feel like I have all the logic down, I would just need to figure out the looping portion. How can I solve this?
from random import choice
print('Welcome to Hangman!!!, Guess the secret word ')
user_guess = input('What is your first guess at the secret word? ')
org_word = choice(['cat','dog','mug','plate'])
word = set(org_word)
already_guessed = ''
chances = 10
def hang_man():
guess()
check_win()
def guess():
global chances
global correct_letters
global already_guessed
#check for valid input
if len(user_guess) > 1 or user_guess.isnumeric():
print('you entered an invalid input and you lost a guess')
chances -= 1
if chances == 0:
print('Sorry you are out of guesses, You Lost :(')
else:
print(f'you now have {chances} guesses left')
#check if letter was already guessed
elif user_guess in already_guessed:
print('you already entered that letter and you lost a guess')
chances -=1
#incorrect guess
elif user_guess not in word:
print('That guess was not in the word and you lost a guess')
chances -= 1
already_guessed += user_guess
if chances == 0:
print('Sorry you are out of guesses, You Lost :(')
else:
print(f'you now have {chances} guesses left')
#correct guess
elif len(user_guess) == 1 and user_guess in word:
print(f'Great, your guess of {user_guess} was in the word')
word.remove(user_guess)
def check_win():
if len(word) == 0 :
print(f'Congrats, you guessed the correct word {org_word}')
hang_man()
You could amend check_win() to return true when guessed correctly:
def check_win():
if len(word) == 0 :
print(f'Congrats, you guessed the correct word {org_word}')
return True
Then while the word hasn't been guessed:
def hang_man():
while not check_win():
guess()
Edit: Thanks for the spot Pranav Hosangadi.
An issue with my guessing game. When I input the correct value for the guess in order to "win" the game, the loop does not pick up the input correctly and fails to catch the word. Any idea on how to simplify this issue or condense code? (Secret_word shown is only printed so I could easily test using the correct # ) Also, ignore my notes.
secret_word = rn.randint(1,20)
guess = ""
guess_count = 0 # how man times the user has guessed
guess_limit = 3 # how many guesses the user has left
out_of_guesses = False # boleean to tell us if they have guesses to keep playing
while guess != secret_word: # as long as they havnt gotten the word and still have guesses
if guess_count < guess_limit: # this check to see if they have guesses
if guess_count == 2:
print("Careful you only have one more guess!")
print(secret_word)
print("Failed guesses: " + str(guess_count))
guess = input("Enter guess: ")
guess_count += 1
if guess == secret_word:
print("Congratulations you win!")
else: # Guess_COUNT was Not less than guess limit they are out of guesses
out_of_guesses = True # This turns the switch "on for out of guesses.
if out_of_guesses: # Tackles two outcomes, you win or you lose
print("Out of guesses, you lose!")
The main problem is that you had to convert your user input into an integer in order to be able to compare it to your secret word which is actually not a word but an integer. Also I fixed the logic of out_of_guesses in your code:
import random as rn
secret_word= rn.randint(1,20)
guess_count = 0
guess_limit = 3
out_of_guesses = True
while guess_count < guess_limit:
print("Hint:", secret_word)
print("Failed guesses: " + str(guess_count))
if guess_count == guess_limit - 1:
print("Careful you only have one more guess!")
guess = input("Enter guess: ")
if int(guess) == secret_word:
print("Congratulations you win!")
out_of_guesses = False
break
guess_count +=1
if out_of_guesses == True:
print("Out of guesses, you lose!")
print("Secret word was", secret_word)
You need to have a integer, a string will not work. So, do
guess = ""
try: # user may input not-number value
guess = int(guess)
except: # user has inputted not-number value
print("Whoops, you didn’t input a valid number! Try again.")
exit()
I'm currently new to programming so I'm trying to create a guessing game as practice but I don't know what I did wrong.
secret_word = "Giraffe" or "giraffe"
guess_word = ""
failed = False
guess_count_limit = 3
guess_count = 0
while guess_word != secret_word and not failed:
if 1 < guess_count:
guess = input("Guess the animal I'm thinking of: ")
guess_count += 1
elif 2 < guess_count:
print("Incorrect but here's a hint: ")
print("It's common in Africa. ")
print("Two guesses left.")
guess = input("Now try again: ")
guess_count += 1
elif 3 < guess_count:
print("Incorrect but here's your last hint: ")
print("It's tall. ")
print("One guess left")
guess = input("Now try again: ")
elif guess_count == guess_count_limit:
print("Nope, out of guesses.")
failed = True
if failed:
print("You win")
else:
print("Wow, you really lost huh.")
When I try to run this program, nothing happens.
This version will work:
secret_word = "giraffe"
guess_word = ""
guess_count_limit = 3
guess_count = 0
while guess_word.lower() != secret_word and guess_count < guess_count_limit :
if 1 > guess_count:
guess_word = input("Guess the animal I'm thinking of: ")
guess_count += 1
elif 2 > guess_count:
print("Incorrect but here's a hint: ")
print("It's common in Africa. ")
print("Two guesses left.")
guess_word = input("Now try again: ")
guess_count += 1
elif 3 > guess_count:
print("Incorrect but here's your last hint: ")
print("It's tall. ")
print("One guess left")
guess_word = input("Now try again: ")
elif guess_count == guess_count_limit:
print("Nope, out of guesses.")
print("Wow, you really lost huh.")
if guess_word.lower() == secret_word :
print("You win")
you made 3 mistakes:
secret_word = "Giraffe" or "giraffe"
As far as I know logical operators does not work with strings. However, you do not need 2 words with different letter cases, you need only one and then change the case of the guesses to check.
when you took the input you stored in guess but in the loop you are comparing guess_word with secret_word!!
you had a problem inside the loop in the condition statements, try to figure it out in order to learn and become better.
good luck!
I've been working on hangman project recently, I have used enumerate to get the locations of a letter that's been guessed so i can put it into a list, but when i try and put it into "guess" list, it comes up with:
Edit: I do understand that you cannot simply change an entire list into a series of ints by doing int(list), it's simply a place holder
Here is my code
import random
lines = []
with open('words.txt', 'r') as f:
for line in f:
line = line.strip()
lines.append(line)
choice = random.choice(lines)
#print("it says", choice)
guessed = False
print("Your word is", len(choice), "letters long!")
answer = ["_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"]
wrong = 0
= 1
print(choice)
while not guessed:
guess = input("Guess a letter!")
#location = choice.find(guess)
location = [i for i, a in enumerate(choice) if a == guess]
print(location)
if wrong == 6:
print("Sorry, you have killed yourself.")
guessed = True
elif not location:
wrong += 1
print("Sorry, that was not part of the word!")
print("You have", (6 - wrong), "guesses left")
elif right == len(choice):
answer[int(location)] = guess
print(answer[0:len(choice)])
print("Congratulations! You have won!")
guessed = True
else:
right += 1
answer[location] = guess
print(answer[0:len(choice)])
Your code has other issues beyond this but as your question at hand, it is here:
elif right == len(choice):
answer[int(location)] = guess
print(answer[0:len(choice)])
print("Congratulations! You have won!")
guessed = True
else:
right += 1
answer[location] = guess
print(answer[0:len(choice)])
Your two statements answer[int(location)] = guess and answer[location] = guess if you print location it is a list, for a 4 letter word example vash, location is a list of range [0,3] you are attempting to pass the entire list as an index which will not work regardless if you convert it to int or not.
Please try this modification, this is not a full solution, I do not want to take away from your journey on this project but this will get your moving:
import random
lines = ['hey', 'this', 'that']
choice = random.choice(lines)
#print("it says", choice)
guessed = False
print("Your word is", len(choice), "letters long!")
answer = ["_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"]
wrong = 0
right = 0
print(choice)
while not guessed:
guess = input("Guess a letter!")
#location = choice.find(guess)
if wrong == 6:
print("Sorry, you have killed yourself.")
guessed = True
elif guess not in choice:
wrong += 1
print("Sorry, that was not part of the word!")
print("You have", (6 - wrong), "guesses left")
elif right == len(choice):
print(answer)
print("Congratulations! You have won!")
guessed = True
else:
right += 1
answer[choice.index(guess)] = guess
print(answer[0:len(choice)])