While loop with inputs - python

I'm doing a simple game for a school project. It's simply a guess the word game, and I've gotten most of it down, except for when answer is wrong or completed. Here's my code so far.
guess = input('Guess a letter.')
blank_answer = list('_ _ _ _ _ _')
correct_answer ='banana'
correct_answer_final = 'b a n a n a'
guess_num = 4
index_num = 0
while guess_num > 0 and "".join(blank_answer) != correct_answer_final:
index_num = 0
for letter in correct_answer:
if letter == guess:
blank_answer[index_num] = letter
index_num += 2
if letter != guess:
guess_num -= 1
print('The Word so far is ' + "".join(blank_answer)
guess = input('Guess a letter. (You have ' + str(guess_num) + ' guesses remaining)')
if "".join(blank_answer) == correct_answer_final:
print('Good job ')
if guess_num == 0:
print('sorry you ran out of guesses')
The main problem I'm having is after the first guess it'll say '3' guesses remaining then it'll jump to 2 after a few more guesses even if they are correct. Also it doesn't jump out of the loop right away after guessing correctly. If it is correct you have to input a correct letter once again. This was done in a graphical window, so I've changed all imported commands to default python to make it easier to understand. Any help would be great!

Not sure if this will fix the issue you're having but the condition for your while loop seems incorrect. I think what you're looking for is
while guess_num > 0 and "".join(blank_answer) != correct_answer_final
(The difference here being the and vs. the or)
This way the loop will exit if either the guesses run out OR the correct answer is guessed.

Related

Hangman Issue: How do I make my loop reset when the letter entered is not present and how do I make the letter appear more than once in the word?

The word_chosen is "apple". However, when I enter the letter p, it only appears once in the word. I would also like to make my loop reset when the letter entered is not correct.
def guesses():
guess = 0
hangman_word = "_____"
while guess < 5:
guess_player = input("What is your letter? ")
for i in range(len(word_chosen)):
if guess_player == word_chosen[i]:
guess_player = (hangman_word[:i]) + word_chosen[i] + hangman_word[i + 1:]
print(guess_player)
continue
elif guess_player != word_chosen[i]:
guess += 1
Some issues:
The following assignment is wrong:
guess_player = (hangman_word[:i]) + word_chosen[i] + hangman_word[i + 1:]
You should not update guess_player which is the input letter. Instead you should update hangman_word. So:
hangman_word = (hangman_word[:i]) + word_chosen[i] + hangman_word[i + 1:]
The following condition will always be true when the execution gets there:
elif guess_player != word_chosen[i]:
The opposite was already checked in the preceding if statement, so the only possibility left is that the guess was wrong. No need to test that again.
guess += 1 should not appear within the loop. If the guess does not match the first letter, that doesn't mean it cannot still match with the second letter. So it is wrong to increment this counter when the comparison has not yet been made with all remaining letters of the secret word.
You can make use of the in operator to check whether there is at least one occurrence of the guessed letter:
if guess_player in word_chosen:
# ... here comes your loop to update `hangman_word` ... (without `elif`)
else:
guess += 1
The while loop should exit not only when the player has made five wrong guesses, but also if the player has found the word! You can do that as follows:
while guess < 5 and "_" in hangman_word:
When the while loop exits, you should probably report on the outcome of the game. Was it a success or not? It could be:
if "_" in hangman_word:
print("You guessed 5 times wrong. Game over.")
else:
print("You guessed the word. Well done!")
There should probably be some message when the player repeats a good guess a second time (optional).
Here is your code with corrections for the above points:
def guesses():
guess = 0
hangman_word = "_____"
while guess < 5 and "_" in hangman_word:
guess_player = input("What is your letter? ")
if guess_player in hangman_word:
print("But...but... you already guessed that letter!?")
elif guess_player in word_chosen:
print("Good going!")
for i in range(len(word_chosen)):
if guess_player == word_chosen[i]:
hangman_word = (hangman_word[:i]) + word_chosen[i] + hangman_word[i + 1:]
else:
print("That letter does not occur in the word.")
guess += 1
print(hangman_word)
if "_" in hangman_word:
print("You guessed 5 times wrong. Game over.")
else:
print("Well done!")
A couple aspects of the code can be improved.
def guesses():
# PreEnter the word for referece
word_chosen = "hangman"
guess = 0
# Creating a list instead of a string, to be able to update it, rather than creating new ones.
hangman_word = ["_" for _ in range(len(word_chosen))]
# Storing entered letters in a list for fair play in case wrong letters are entered.
entered_letters = []
while guess < 5:
guess_player = input("Enter a Letter: ")
# Checking if enterd string contains a single letter
if len(guess_player) > 1:
print("You can only enter one letter at a time.")
continue
if guess_player in entered_letters:
print("You already guessed that letter")
continue
# Using for loop only after checking if the letter is in the word.
elif guess_player in word_chosen:
for i in range(len(word_chosen)):
if guess_player == word_chosen[i]:
hangman_word[i] = guess_player
else:
print("That was an incorrect choice!")
guess += 1
# appending the entered letter to the list of entered letters.
entered_letters.append(guess_player)
# Using "".join to print the string from the list.
word = "".join(hangman_word)
print(word)
# Checking if the word is complete.
if word == word_chosen:
return "You Win!"
# If the player runs out of guesses, the game is over.
return "You Lose!"
print(guesses())
Since you are a beginner, try understanding the code through comments and see if you can figure out which aspects of your code I altered. Feel free to point out anything you have doubts about.

Infinite While Loop while making a simple logic game "Bagels"

I am using The Big Book of Small Python projects to increase my skills in python, and on the very first project, which is making a simple logic game, On the first try, the code goes all the way however if you get it wrong you it won't run properly.
Here is the code and a description of the game, the while loop with chances is supposed to run for the whole game, until you run out of chances, the second while loop is supposed to run in case user enters below or more than length three for the number
import re
import random
#In Bagels, a deductive logic game, you
#must guess a secret three-digit number
#based on clues. The game offers one of
#the following hints in response to your guess:
#“Pico” when your guess has a correct digit in the
#wrong place, “Fermi” when your guess has a correct
#digit in the correct place, and “Bagels” if your guess
#has no correct digits. You have 10 tries to guess the
#secret number.
choice_of_nums=['123','345','674','887','356','487','916']
random_three_num=random.choices(choice_of_nums)
count_bagel=0
count_fermi=0
Chances=10
while Chances!=0:
guess = input(f'Guess the three digit number! You have {Chances} to guess! ')
while len(guess)!=3:
guess=input('You must choose a three digit number! Try again! ')
for i in range(0,len(random_three_num)):
if guess==random_three_num:
print('YOU WIN! Well done')
break
elif guess[i] not in random_three_num:
count_bagel+=1
if count_bagel==len(random_three_num):
print('Bagels')
Chances=Chances-1
elif guess[i]==random_three_num[i]:
count_fermi+=1
Chances=Chances-1
print('Fermi')
elif guess in random_three_num:
print('Pico')
import random
choice_of_nums = ['123', '345', '674', '887', '356', '487', '916']
random_three_num = random.choice(choice_of_nums)
count_bagel = 0
count_fermi = 0
chances = 10
while chances > 0:
guess = input(f'Guess the three digit number! You have {chances} to guess! ')
while len(guess) != 3:
guess = input('You must choose a three digit number! Try again! ')
while not guess.isdigit():
guess = input('You must choose integer values! ')
number_is_present = any(number in guess for number in random_three_num)
if guess == random_three_num:
print('YOU WIN! Well done')
chances = 1 # combined w/ the last line, chances will become = 0
elif not number_is_present:
print('Bagel')
else:
index_is_right = False
for i in range(len(guess)):
if guess[i] == random_three_num[i]:
index_is_right = True
if index_is_right:
print('Fermi')
else:
print('Pico')
chances -= 1
(06/28/22) added chances = 1 if the guess is right, so to exit the while loop
random.choices returns a list
you don't need the re module
use snake case as suggested in PEP8
The break after print('YOU WIN! Well done') exits the for loop not the while loop. Put Chances = 0 before the break:
if guess==random_three_num:
print('YOU WIN! Well done')
Chances = 0
break
You should never check a while loop with a condition like x != 0. Always use <= or >=. The reason being, that if somehow the number zero is skipped and you end up at -1 then the loop will still exit.
Couldn't your check if guess==random_three_num: be done before the for loop? Then the break statement would actually break the while loop. Now it's only breaking the for loop. This is one reason that could lead to a infinite loop.
Your second to last line elif guess in random_three_num: should probably be elif guess[1] in random_three_num:.
Chances=Chances-1 could probably be outside the for loop also, as the number of chances should decreasing only one per guess. Currently the number of chances decreases up to 3 times during the for loop (every time you hit 'Fermi'). This could lead to issue described in "1."

Hangman from Python 2 to Python 3

sRealWord = input("Write the Hangman Word in Capital Letters: ")
lShownWord = ["_"] * len(sRealWord)
sInput = ""
iAllowedGuesses = 10
iLetterNumber = 0 #was []
iRightGuesses = 0 #was []
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
print("Let the Game Begin!")
print("Type END to close game, or complete your 10 guesses")
while(sInput != "END" and iAllowedGuesses != 0):
print("The word you're looking for is: " + str(lShownWord)) ##FIXED
print("You have: " + str(iAllowedGuesses) + " guesses left") ##FIXED
sInput = input("Enter letter in Capital Letters: ")
iAllowedGuesses -= 1 ##VALUE 1 ##FIXED
while(iLetterNumber < len(sRealWord)) : **###THIS IS NOT WORKING**
if (sRealWord[iLetterNumber] == sInput) :
lShownWord[iLetterNumber] == sInput
iRightGuesses += 1
iLetterNumber += 1
iLetterNumber = 0
elif (iRightGuesses == len(sRealWord)): ###**THIS IS NOT WORKING**
print("Woho!, You've won!")
elif (iAllowedGuesses == 0):
print("You are out of guesses, Game Over!") ###fixed
break
I decided to take an old Hangman code from Python 2 and migrate into Python 3 for practice.
The lines that I think are preventing the code from working correctly are commented out and in bold.
What am I missing or doing wrong in the code or those lines that needs to be done differently or fixed in order for the game to work?
FYI
The output for running out of guesses is working. Although, the output of getting right guesses is not working, therefore, when you get the word right it just continues as if they are wrong.
There are multiple issues that I see. But none seem to have to do with python2 vs python3.
You probably want to assign the sInput to the lShownWord[iLetterNumber] if it is correct. For that, you need only a single =.
There is no point in incrementing iLetterNumber right before setting it to zero. I assume what you want to do is check every letter of the word, every time the user enters a word. You can do that with a while loop and resetting the variable manually, but it's more idiomatic and slightly leass error prone with a for loop. The for loop resets the counter variable automatically, and increments it every loop iteration.
Careful with the indentation. You don't want to first have the user try iAllowedGuesses times before showing the correct characters. Both the while loop and the ifs were in the wrong place. And once you put the if statements to the correct level of indentation, elif does not make sense there anymore.
You probably also want to break if the user has won.
This leaves us with this code.
sRealWord = input("Write the Hangman Word in Capital Letters: ")
lShownWord = ["_"] * len(sRealWord)
sInput = ""
iAllowedGuesses = 10
iRightGuesses = 0 #was []
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
print("Let the Game Begin!")
print("Type END to close game, or complete your 10 guesses")
while(sInput != "END" and iAllowedGuesses != 0):
print("The word you're looking for is: " + str(lShownWord)) ##FIXED
print("You have: " + str(iAllowedGuesses) + " guesses left") ##FIXED
sInput = input("Enter letter in Capital Letters: ")
iAllowedGuesses -= 1 ##VALUE 1 ##FIXED
for iLetterNumber in range(len(sRealWord)) :
if (sRealWord[iLetterNumber] == sInput) :
lShownWord[iLetterNumber] = sInput
iRightGuesses += 1
if (iRightGuesses == len(sRealWord)):
print("Woho!, You've won!")
break
if (iAllowedGuesses == 0):
print("You are out of guesses, Game Over!")
break

How to make a hangman game in Python

I found an exercise on a website to make a hangman game. Here is what I did:
score = int(5)
word = 'orange'
guess = str(input('Enter your guess: '))
while score > 0 or guess == 'o' and 'r' and 'a' and 'n' and 'g' and 'e' or 'orange'
if 'o' or 'r' or 'a' or 'n' or 'g' or 'e' or 'orange' == guess:
print('CORRECT')
else:
score = score - 1
print('Your score is ' + score)
print('WRONG')
This code just doesn't work! Especially the while loop ruins everything! How to make this actually work? I have written this code in the Jupyter notebook.
This is a working example of the guessing game, with some removal of code redundancy and a bit of clean-up. Important: break-statement inserted inside the if-statement to avoid infinite looping, and new guess prompt inserted in the else-statement:
score = 5
word = 'orange'
guess = str(input('Enter your guess: '))
while (score > 0) or (guess in ('o', 'r', 'a', 'n', 'g', 'e', 'orange')):
if guess in ('o', 'r', 'a', 'n', 'g', 'e', 'orange'):
print('CORRECT')
break
else:
score -= 1
print('WRONG')
print('Your score is ' + str(score))
guess = str(input('Enter your guess: '))
Example run:
Enter your guess: u
WRONG
Your score is 4
Enter your guess: o
CORRECT
There's lots here to do - 1st, your code only allows for a game of hangman for which the word to be guessed is "orange". Fine for a single game, but useless for the second round, unless all players have acute memory problems.
So you need to abstract a little - write some pseudo-code down, think about the steps your program is going to need to take in order to perform the operations required in the game.
This is like writing down instructions for a human, just in a form that's also close to your final programming language.
So something like:
# choose a word to play the game with, save it to the variable called word
word = 'orange'
# Reserve a list of letters that have been guessed.
# Start off with it empty - do the same to keep track of
# good and bad guesses
guesses = []
good_guesses = []
bad_guesses = []
# Reserve a number of bad tries allowed before game over
bad_tries_before_game_over = 5
# Reserve a number of bad tries so far
bad_tries_so_far = 0
# Start a loop, we'll come back to this point each time
# the player makes a new guess.
# There are two conditions when to not loop and those are:
# 1. when the player has won by guessing all the letters or
# 2. when the player has lost by getting too many wrong tries
# we'll use a variable called "finished" to track whether either of these conditions is met
finished = False
while not finished:
guess = str(input('Enter your guess: '))
# Check whether the person already guessed this letter
if guess in guesses:
print ( "You already guessed that letter.")
print ( "Try using a letter you've not already guessed.")
print ( guesses )
else:
# if guess is correct, then great, otherwise, add bad tries + 1
if guess in word:
print ( "Yes, {g} is in the word.".format(g=guess) )
guesses.append(guess)
good_guesses.append(guess)
else:
print ( "No, {g} is not in the word.".format(g=guess) )
guesses.append(guess)
bad_guesses.append(guess)
bad_tries_so_far = bad_tries_so_far + 1
if bad_tries_so_far > bad_tries_before_game_over:
print ( "Hangman. Game over. ")
finished = True
if set(word)==set(good_guesses):
print ( "Hooray, you saved the man!.")
finished = True
Over time, you'll naturally think in python and it will kind of become its own pseudo code. But it's best to at least try and work your ideas out on paper, or in English (or whatever language is your natural one) first, just to set out the logical flow that you want the game to have.
If you want to check guess against a set of different options, use in; you can't use and or or like that due to different precedences.
if guess in ('o', 'r', 'a', 'n', 'g', 'e', 'orange'):
would work better for you (though that's probably not the only problem in your code).
Well, here's one that I made. It's slightly more interactive and realistic, but making the words are kind of annoying. If you want to make it more fun, try adding more words with a random word generator or something like that, make the hangman more realistic, or adding game modes and VS matches.
I hope this helps =)
If you're still wondering how this code works, I'll try and explain as much as possible. First of all, I imported time to make pauses, making it more dramatic. If you want to remove the pauses, be my guest.
The first bunch of code is just the beginning and all that. You could delete/change it if you want
After, it asks you to input your name. Like I said, completely optional.
Next, it tells you to enter a number. Each number has a specific word.
Then, it's time to guess. I should explain what will happen. Let's say the word is secret. That's 6 letters.
It would look like this:
_
_
_
_
_
_
Then it asks you to start guessing. If you had your 10 tries, you lose. Let's say you managed to guess an "s". This happens:
s
_
_
_
_
_
Hope this explains everything. I'm working on this code and planning to add a party mode next.
Have a great day =)
Phantom
import time
time.sleep(5)
print('Welcome to... hangman!')
time.sleep(2)
print("Are you ready? Ok, let's start.")
time.sleep(3)
name =input("What is your name? ")
time.sleep(1)
print("Hello, " + name + ". Time to play hangman! I wish you good luck- you'll need it.")
time.sleep(3)
darealword=int(input('Please enter a number. 1-30 only> '))
if darealword==1:
word='hypothesize'
elif darealword==2:
word='tube'
elif darealword==3:
word='blow'
elif darealword==4:
word='volume'
elif darealword==5:
word='parachute'
elif darealword==6:
word='biography'
elif darealword==7:
word='paragraph'
elif darealword==8:
word='abortion'
elif darealword==9:
word='exaggerate'
elif darealword==10:
word='complain'
elif darealword==11:
word='diagram'
elif darealword==12:
word='produce'
elif darealword==13:
word='abnormal'
elif darealword==14:
word='account'
elif darealword==15:
word='interactive'
elif darealword==16:
word='jump'
elif darealword==17:
word='goalkeeper'
elif darealword==18:
word='glimpse'
elif darealword==19:
word='story'
elif darealword==20:
word='coal'
elif darealword==21:
word='weave'
elif darealword==22:
word='dynamic'
elif darealword==23:
word='credibility'
elif darealword==24:
word='rhythm'
elif darealword==25:
word='trunk'
elif darealword==26:
word='admire'
elif darealword==27:
word='observation'
elif darealword==28:
word='rough'
elif darealword==29:
word='representative'
else:
word='thought'
time.sleep(3)
print("Start guessing... you can do this.")
time.sleep(1)
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print(char,)
else:
print("_",)
failed += 1
if failed == 0:
time.sleep(5)
print('Aaaaaaand... you...')
time.sleep(3)
print('won!!!!! I congratulate you, '+ name +'.')
break
print
guess = input("Guess a character> ")
guesses += guess
if guess not in word:
turns -= 1
print("Sorry, this character isn't in the word. Don't get it wrong next time.")
# print("You have", + turns, 'more guesses')
if turns == 0:
print("Aaaaaaand... you...")
time.sleep(3)
print("lost. I feel bad. Better luck next time. And if you're wondering, the word is "+ word +'.')

Correcting user input to meet a specific requirement for Hangman

I need the user input to only equal 1 character but there is a bug in the code that lets me enter more than one character at a time. I need to be able to prompt the user to say you can only enter one character at a time and then go back to let them enter the character but without the character counting toward the game.
print ("lets play guess this word.") #time to play
secret_word = input("Enter a secret word to guess: ") # gather the secret word
secret_word = secret_word.lower() # convert to lower
guesses = "" # this is the string that will show what has been guessed later
turns = 6 # how many chances they get to enter a wrong character.
# a very very tricky while loop.
while turns > 0: # will be true until the turns counter makes turns = 0
count = 0 # this count determines wether to print _ or the character
for char in secret_word: # looking at characters in the secret word
if char in guesses: # this is used to display the correct letters and _'s
print (char, end="")
else:
print ("_ ",end="") # this print the _ for every char in secretword
count += 1 # ends the for loop continues to the next part
if count == 0: # you won the game end the loop.
print ()
print ("You win")
break
print ()
print ()
print ()
guess = input("guess a character:")
count2 = 0
if len(guess) > 1:
count2 += 1
while count2 > 0:
print ("you can only guess 1 character at a time")
count2 -= 1
guess = guess.lower() #lower # it is time to guess the letters.
guesses += guess
if guess not in secret_word: # if statement for if guess is not in word
turns -= 1 # subtract from turns
print ()
print ()
print ("Wrong")
print ("Letters guessed so far: ",guesses) # end of loop show guessed letters
print ("You have", + turns, 'more guesses') # show turns left
if turns == 0: # END GAME
print ("The word was",secret_word,"You Loose")
Screenshot showing the code does work in Python:
I also need help with making it only accept 1 character at a time and also no numbers. I also added this part of code while trying to accomplish this task but it does not stop the multiple characters being entered from counting toward the word.
count2 = 0
if len(guess) > 1:
count2 += 1
while count2 > 0:
print ("you can only guess 1 character at a time")
count2 -= 1
Here is my output:
lets play guess this word.
Enter a secret word to guess: computer
_ _ _ _ _ _ _ _
guess a character:abcdefghijklmnopqrstuvwxyz
you can only guess 1 character at a time
Wrong
Letters guessed so far: abcdefghijklmnopqrstuvwxyz
You have 5 more guesses
computer
You win
All you're missing is the statement to loop back around after warning if the user enters invalid input. With the structure you've got, the statement you want is continue, which jumps to the next iteration of a loop:
while turns > 0:
# Print current guesses; get input; etc...
# Check for invalid input
if len(guess) > 1:
print("you can only guess 1 character at a time")
continue # This makes us return to the top of the while loop.
# We definitely have valid input by the time we get here, so handle the new guess.
This is simplified a little from your version; I've taken out count2, for instance, because it wasn't doing anything important. But the premise is the same: after you warn the user about their invalid input, you need to ask for new input--jump to the top of the loop--instead of just moving ahead.

Categories