Loop wont run as expected - python

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.")

Related

How to stop Hangman python program when the user has guessed the correct words?

I'm making a simple hangman program using while-loops. The program that I've written works, but I don't know how to make it stop once the user has guessed the correct letters.
Here is what I have so far:
word = input("What's the secret word? ")
lives = int(input("Amount of lives? "))
while True:
guess = input("Guess a letter: ")
if guess in word:
print("Correct, the letter is in the secret word.")
else:
lives -= 1
print(f"The letter {guess} is not in the secret word.")
if lives > 0:
print(f"You have {lives} lives left, try again.")
else:
print("You have no lives left.")
break
The simplest way I see is to add some counter of correctly guessed letters, so you can reason when the word itself is guessed correctly.
guessed_so_far = 0
already_guessed = []
while True:
guess = input("Guess a letter: ")
if guess in word and guess not in already_guessed:
print("Correct, the letter is in the secret word.")
guessed_so_far += 1
already_guessed.append(guess)
if guessed_so_far == len(set(word)):
break
As Joshua correctly suggested, you have to compare with len(set(word))
Your guess = input(...) code has a subtle bug: what if the user inputs a len(guess) > 1 string? Ignoring that possibility for a moment:
word = input("What's the secret word? ")
letters = set(word)
...
# if the guess (assumed single character) is in the set of letters
if guess in letters:
print("Correct, the letter is in the secret word.")
# reduce the set of letters remaining by the current guess
letters = letters - set(guess)
# if there aren't any letters left to guess
if len(letters) == 0:
print("Congrats! You won!")
break

cant figure out how to loop for hangman in python

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.

How to improve guessing game and condense

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

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)

How do I end my program after you correctly guess the word?

I am creating this game called "Fruit Guessing". I have a list of 9 fruits and I have the game working properly up until you guess all of the letters correct. Unfortunately, I can't seem to figure out how to get the game to end. I tried to get it to end on line 44 of the code I made a variable and everytime you guess a correct letter it adds 1 to that variable. The variable is called letters_guessed_correct. I tried to get it so that when letters_guessed_correct is equal to the length of the random fruit that was chosen it would say "congratulations! You guessed the fruit I was thinking of!" but I can't get that part to work and if I got it to work I'm still not sure how to get it to end the game. This is a project for school and it is due on Tuesday. It is my 15% of my grade in Computer Science Principles. Please help me.
I am running Python 3 on a website called repl.it
Here is the full code:
import random
def beginning_of_program():
user_value = input('Would you like to look at the instructions?:')
if user_value=='yes':
instructions_page()
elif user_value=='no':
user_value=input('Are you ready to play Fruit Guessing?:')
if user_value=='yes':
run_game()
def instructions_page():
print()
print('1. I am going to come up with random fruits.')
print()
print('2. Try and guess the letters in the word')
print()
print('3. Write all of your guesses in lowercase letters')
print()
print('4. If you guess wrong 7 times then the game ends')
print()
user_value=input('Are you ready to play Fruit Guessing?:')
if user_value=='no':
print('Okay, have a good day')
elif user_value=='yes':
run_game()
def run_game():
wordlist=['apple','orange','grape','kale','kiwi','mango','cherry','peach','plum']
randfruit=random.choice(wordlist)
blanks='_ '*len(randfruit)
letters_guessed_correct=0
print()
print("Word: ",blanks)
newblanks=blanks
count=7
while count>0:
letters_guessed_correct=0
letters_guessed_list=[]
letters_guessed_correct_list=[]
print()
guess=input('Guess a letter from the fruit that I am thinking of:')
if letters_guessed_correct==len(randfruit):
print('Congratulations! You guessed the correct fruit I was thinking of!')
exit()
elif guess in letters_guessed_list:
print('You have already guessed this letter, please guess again.')
elif len(guess) !=1:
print('Guess one letter at a time!')
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print('Please only guess letters')
else:
for letters in randfruit:
if guess==letters:
if guess not in letters_guessed_list:
letterindex=randfruit.index(guess)
newblanks=newblanks[:letterindex*2]+guess+newblanks[letterindex*2+1:]
print(newblanks)
print('Guess is correct!')
letters_guessed_correct += 1
letters_guessed_correct_list.append(guess)
letters_guessed_list.append(guess)
break
if guess not in randfruit:
if count!=0:
count -= 1
letters_guessed_list.append(guess)
print("Guess is wrong!",count,"more failed attempts left.")
print()
print("Word:",newblanks)
print("Guess is wrong!",count,"more failed attempts left.")
print()
print("Word:",randfruit)
print()
print('You guessed,',str(letters_guessed_list))
print("Guess is wrong!",count,"more failed attempts left."
import random
def beginning_of_program():
user_value = raw_input('Would you like to look at the instructions?:')
if user_value.lower() == 'yes':
instructions_page()
elif user_value.lower() == 'no':
user_value=raw_input('Are you ready to play Fruit Guessing?:')
if user_value=='yes':
run_game()
def instructions_page():
print('I am going to come up with random fruits.')
print('Try and guess the letters in the word')
print('Write all of your guesses in lowercase letters')
print('If you guess wrong 7 times then the game ends')
user_value=raw_input('Are you ready to play Fruit Guessing?:')
if user_value=='no':
print('Okay, have a good day')
elif user_value=='yes':
run_game()
def run_game():
wordlist=['apple','orange','grape','kale','kiwi','mango','cherry','peach','plum']
randfruit=random.choice(wordlist)
blanks='_ '*len(randfruit)
letters_guessed_correct=0
print()
print("Word: ",blanks)
newblanks=blanks
count=7
while count>0:
letters_guessed_correct=0
letters_guessed_list=[]
letters_guessed_correct_list=[]
print()
guess=raw_input('Guess a letter from the fruit that I am thinking of:')
if guess in letters_guessed_list:
print('You have already guessed this letter, please guess again.')
elif len(guess) !=1:
print('Guess one letter at a time!')
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print('Please only guess letters')
else:
for letters in randfruit:
if guess==letters:
if guess not in letters_guessed_list:
letterindex=randfruit.index(guess)
newblanks=newblanks[:letterindex*2]+guess+newblanks[letterindex*2+1:]
print(newblanks)
print('Guess is correct!')
letters_guessed_correct += 1
letters_guessed_correct_list.append(guess)
letters_guessed_list.append(guess)
break
if guess not in randfruit:
count -= 1
letters_guessed_list.append(guess)
print("Guess is wrong!",count,"more failed attempts left.")
print()
print("Word:",newblanks)
if newblanks.replace(" ", "") == randfruit:
print('Congratulations! You guessed the correct fruit I was thinking of!')
exit()
if __name__ == "__main__":
beginning_of_program()

Categories

Resources