How to improve guessing game and condense - python

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()

Related

Guess the word - Python (more guesses than should be)

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'm trying to create a guessing game but when I run my code, nothing happens

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!

Basic guessing game doesn't give any output

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.

Loop wont run as expected

I am just learning python, and I am trying to make hangman, but I am having two problems. First, when you enter the same letter twice, it follows two of my conditions, and the prompt for both gets printed twice. For example:
> C:\Users\Me\PycharmProjects\Python\venv\Scripts\python.exe C:/Users/Me/PycharmProjects/Python/Hangman.py
shark
There are 5 letters in this word.
You have 3 wrong guesses left.
Guess a letter.
s
Good guess. That letter was in the word.
You have 3 wrong guesses left.
Guess a letter.
s
*You already entered that letter.
Good guess. That letter was in the word.*
You have 3 wrong guesses left.
Guess a letter.
Another issue I am having is making the win condition. If the correct_guesses reaches zero, it should end the game, but it doesnt actually work, as it always ends the game after 4 correct inputs.
import random
my_list = ["hangman", "dragon", "tiger", "octopus", "shark", "money", "school", "stadium", "biker", "whale", "sphinx"]
my_list2 = []
word = random.choice(my_list)
print(word) #Delete later
print("There are", len(word), "letters in this word.")
def start():
guesses_left = 3
correct_guesses = len(set(word))
while guesses_left > -1:
print("You have", str(guesses_left), "wrong guesses left.\n")
guess = input("Guess a letter. \n").lower()
if len(guess) != 1:
print("Please enter a single letter.")
continue
if guess in my_list2:
print("You already entered that letter.")
continue
if guess not in my_list2:
my_list2.append(guess)
if guess in word:
print("Good guess. That letter was in the word.")
correct_guesses -= 1
continue
if guess not in word:
print("That letter isn't in the word.")
guesses_left -= 1
continue
if correct_guesses == 0:
print("Congratulations! You won the game.")
break
if guesses_left <= 1:
print("Sorry, you lost. Play again.")
start()
print(my_list2) #Delete later
The second time 's' is entered it still matches:
if guess in word:
print("Good guess. That letter was in the word.")
correct_guesses -= 1
How about:
if guess in word and guess not in my_list2:
print("Good guess. That letter was in the word.")
correct_guesses -= 1
Or you could change the overall structure to:
if
...
elif
...
else
...
I see you've edited the code signigicantly based on the other answer. Your last problem of it not stopping to say that you've won is because the code never reaches the win condition, as if the entered letter is correct or not, it will hit a continue before you test for correct_guesses == 0. You can fix that by simply moving the test to the start of the loop instead of the end.
def start():
guesses_left = 3
correct_guesses = len(set(word))
while guesses_left > -1:
if correct_guesses == 0: #
print("Congratulations! You won the game.") # Move it here
break #
print("You have", str(guesses_left), "wrong guesses left.\n")
guess = input("Guess a letter. \n").lower()
if len(guess) != 1:
print("Please enter a single letter.")
continue
if guess in my_list2:
print("You already entered that letter.")
continue
if guess not in my_list2:
my_list2.append(guess)
if guess in word:
print("Good guess. That letter was in the word.")
correct_guesses -= 1
continue
if guess not in word:
print("That letter isn't in the word.")
guesses_left -= 1
continue
if guesses_left <= 1:
print("Sorry, you lost. Play again.")

How to end a program if the user guesses the secret phrase. My code runs in a never ending loop

So my problem with my code is that I can't figure out how I can check if the correct guesses equal the random Secret Phrase given. Thus I want to check if the user has guessed all the letter in the secret phrase. Basically, my code is running in a never ending loop. I have tried making if statements to check if the guesses from the user equals to the secret phrase but it will not work.
#Define a filename
filename = "puzzles.txt".lower()
#Imports
import random
import string
#Open the file and read
with open(filename) as f:
lines = f.readlines()
randomSecretPhrase = (random.choice(lines)) #Choose random phrase from file
#***Output secret word to screen test***
print(randomSecretPhrase)
#Initalize
correct = []
incorrect = []
count = 0
def game():
for i in randomSecretPhrase:
if i in correct:
print(i,end=' ')
#elif i != ' ':
elif i in string.ascii_letters:
print('_',end=' ')
else :
print(' ',end=' ')
print("\n\n")
print('Number of times guessed: ', count)
print('~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
def guessed_letters():
#Will check the user input to verify valid letter is entered
while True:
guess = input("Guess a letter: ").lower()
if guess in correct or guess in incorrect:
print("You have already guessed that letter. Please guess again.")
print(count)
elif guess.isnumeric():
print("Please enter only letters not numbers! Guess again.")
elif len(guess) > 1:
print("Please enter only one letter at a time. Please guess again.")
elif len(guess) == 0:
print("Please enter a letter.")
elif len(correct) == len(randomSecretPhrase):
print('You win')
else:
break
#Keep track of correct and incorrect guesses
if guess in randomSecretPhrase:
correct.append(guess)
print('~~~~~~~~~~~~~~~~~~~~~~~~')
print("You have guessed correctly!")
print('\n')
else:
print('~~~~~~~~~~~~~~~~~~~~~~~~')
incorrect.append(guess)
print("You have guessed incorrectly!")
print('\n')
#Main program
while True:
#Call game()
game()
#Call guessed_letters()
guessed_letters()
#Count how many times guesses
count += 1
check()
Output Example:
Number of times guessed: 6
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Guess a letter: w
~~~~~~~~~~~~~~~~~~~~~~~~
You have guessed correctly!
a c l e a n s w e e _
Number of times guessed: 7
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Guess a letter: p
~~~~~~~~~~~~~~~~~~~~~~~~
You have guessed correctly!
a c l e a n s w e e p
Number of times guessed: 8
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Guess a letter:
You mean something like this:
def check():
for i in randomSecretPhrase:
if i not in correct:
return False
return True
Your main program is this:
while True:
#Call game()
game()
#Call guessed_letters()
guessed_letters()
#Count how many times guesses
count += 1
check()
which, hopefully clearly, never ends.
You can give them a maximum number of tries like this:
while count < 3: #or other maximum
#Call game()
game()
#Call guessed_letters()
guessed_letters()
#Count how many times guesses
count += 1
check()
Of course, you would have to vary this for the length of the phrases.
In order to find out if they guessed ok, you need guessed_letters to tell you what its already figured out - if the guess is right or not.
You can changed this to return a value:
def guessed_letters():
#Will check the user input to verify valid letter is entered
while True:
guess = input("Guess a letter: ").lower()
if guess in correct or guess in incorrect:
print("You have already guessed that letter. Please guess again.")
print(count)
elif guess.isnumeric():
print("Please enter only letters not numbers! Guess again.")
elif len(guess) > 1:
print("Please enter only one letter at a time. Please guess again.")
elif len(guess) == 0:
print("Please enter a letter.")
elif len(correct) == len(randomSecretPhrase):
print('You win')
else:
break
#Keep track of correct and incorrect guesses
if guess in randomSecretPhrase:
correct.append(guess)
print('~~~~~~~~~~~~~~~~~~~~~~~~')
print("You have guessed correctly!")
print('\n')
return True
else:
print('~~~~~~~~~~~~~~~~~~~~~~~~')
incorrect.append(guess)
print("You have guessed incorrectly!")
print('\n')
return False
Now, you can check in the while loop:
while True:
#Call game()
game()
#Call guessed_letters()
if guessed_letters(): #<-- check the return code
break #<-- done if correct
#Count how many times guesses
count += 1
check()
In order to proclaim "You have won", you need to think about the stopping coniditon.
You will a list, correct with the guessed letters. and compare the length of this to the length of the randomSecretPhrase, which is a string.
Just on "sweep" the letters will be ['s', 'w', 'e', 'p'] when the guess is corrected.
You need to move the check after you collect the new guess and just check the letters are correct:
def guessed_letters():
#Will check the user input to verify valid letter is entered
while True:
guess = input("Guess a letter: ").lower()
if guess in correct or guess in incorrect:
print("You have already guessed that letter. Please guess again.")
print(count)
elif guess.isnumeric():
print("Please enter only letters not numbers! Guess again.")
elif len(guess) > 1:
print("Please enter only one letter at a time. Please guess again.")
elif len(guess) == 0:
print("Please enter a letter.")
else:
break
#Keep track of correct and incorrect guesses
if guess in randomSecretPhrase:
correct.append(guess)
print('~~~~~~~~~~~~~~~~~~~~~~~~')
print("You have guessed correctly!")
print('\n')
else:
print('~~~~~~~~~~~~~~~~~~~~~~~~')
incorrect.append(guess)
print("You have guessed incorrectly!")
print('\n')
if len(correct) == len(set(randomSecretPhrase)):
print('You win')
return True
return False
This will count unique letters in the randomSecretPhrase, and compare with the correct letters after adding the guess.
You will find it easier to make small functions and tests these one at a time.
For example, when you read the file lines you include the line ending so need to remove this:
with open(filename) as f:
lines = f.readlines()
phrase = (random.choice(lines)) #Choose random phrase from file
randomSecretPhrase = phrase.strip()
#***Output secret word to screen test***
print(randomSecretPhrase)

Categories

Resources