Python 3 hangman for a beginner - python

print("Welcome to hangman. Are you ready to have some fun?")
def play():
import random
List = ["random", "words", "list"]
word = str(random.choice(List))
mistake = 7
alreadySaid = set()
board = "_" * len(word)
print(" ".join(board))
while mistake > 0:
while True:
guess = input("Please guess a letter: ")
if len(guess) <= 1:
break
else:
print("Too long. Enter only one letter.")
if guess in word:
alreadySaid.add(guess)
print("Correct!",guess, " was in the word!")
board = "".join([guess if guess in word else "_" for str in word])
if board == word:
print("Congratulations! You´re correct!!!")
elif guess not in word:
mistake -= 1
print("Wrong!", mistake," mistakes remaining.")
if mistake <= 0:
print("Game Over")
print(" ".join(board))
play()
I'm trying to make hangman with python 3 but whenever I input a correct letter it comes out as a word of only that letter. For example for random when I input r the output is r r r r r r when I want r _ _ _ _ _. What do you think is wrong? Also do I have any other problems?

Might I suggest you take a step back and try a different, cleaner approach? Besides that, I suggest you keep your hidden word as a list, since strings are immutable and do not support item assignment, which means you cannot reveal the character if the user's guess was correct (you can then join() it when you need it to display it to the user as a string):
import random
word_list = [
'spam',
'eggs',
'foo',
'bar'
]
word = random.choice(word_list)
guess = ['_'] * len(word)
chances = 7
while '_' in guess and chances > 0:
print(' '.join(guess))
char = input('Enter char: ')
if len(char) > 1:
print('Please enter only one char.')
continue
if char not in word:
chances -= 1
if chances == 0:
print('Game over!')
break
else:
print('You have', chances, 'chances left.')
else:
for i, x in enumerate(word):
if x == char:
guess[i] = char
else:
print(''.join(guess))
print('Congratulations!')

Related

How to solve this for loop error?. I tried to add a letter in order, in each cycle

I tried to make a simple version of the hangman game. But when I run it, I can't add the letters in order.
The 'count' variable may be the problem. Any can help me ?
Thank you! :)
word = 'houses'# <--just for testing
word = list(word)
print(word)
p2 = ' __ ' * len(word)
p2 = p2.split()
print(p2)
lives = len(word)
print("lives: ", lives)
count = 0
while word != p2:
letter = input("enter a letter: ")
if letter in word:
for x in word:
if x == letter:
p2[count] = letter
#print("cont: ", count)
else:
continue
count+=1
print("p2: ",p2)
else:
lives -= 1
print("You have {} lives left".format(lives))
if lives == 0:
break
Well i wasn't able to understand your point of view about the Hangman but following code is the optimized form of your code and also the my playing interpretation of this game e.g. how this should be played
word = 'houses'# <--just for testing
word = list(word)
print(word)
p2 = ' __ ' * len(word)
p2 = p2.split()
print(p2)
lives = len(word)
print("lives: ", lives)
while word != p2:
letter = input("enter a letter: ")
if letter in word and letter not in p2:
locations = [i for i, x in enumerate(word) if x == letter ]
for location in locations:
p2[location] = letter
print("p2: ",p2)
else:
lives -= 1
print("You have {} lives left".format(lives))
if lives == 0:
break
print('You LOST' if lives == 0 else 'You WON')
Screenshot of the Both Executions of the game (Win & Loss)

How do I make it so every time I play_again in my hangman game, a new word is generated?

Basically the title. I want my hangman game to generate a new random word from an imported file list every time I play again. However, when I do it it simply utilizes the same word as before. Here is the code.
import random
with open("English_Words", "r") as file:
allText = file.read()
words = list(map(str, allText.split()))
word = random.choice(words)}
def play_again():
print("Do you want to play again (Yes or No)")
response = input(">").upper()
if response.startswith("Y"):
return True
else:
return False
def singleplayer():
guessed = False
word_completion = "_" * len(word)
tries = 6
guessed_letters = []
while not guessed and tries > 0:
print(word_completion)
print(hangman_error(tries))
print(guessed_letters)
guess = input("Guess a letter:").lower()
if guess in guessed_letters:
print("You have already guessed that letter.")
elif guess not in word:
print("[INCORRECT] That letter is not in the word!")
guessed_letters.append(guess)
tries -= 1
if tries == 0:
print("You ran out of tries and hanged the man! The word or phrase was: " + str(word))
elif guess in word:
print("[CORRECT] That letter is in the word!")
guessed_letters.append(guess)
word_as_list = list(word_completion)
indices = [i for i, letter in enumerate(word) if letter == guess]
for index in indices:
word_as_list[index] = guess
word_completion = "".join(word_as_list)
if "_" not in word_completion:
guessed = True
if tries == 0:
print("You ran out of tries and hanged the man! The word or phrase was: " + str(word))
if "_" not in word_completion:
guessed = True
if guessed:
print("You win, the man was saved! The word was:" + str(word))
while True:
singleplayer()
if play_again():
continue
else:
break
You need to call word = random.choice(words) inside of your singleplayer() function. Preferrably at the top, either right above or right below the guess = False line.
This way, you're program is going to call that random choice line everytime you call the singleplayer function.
def singleplayer():
word = random.choice(words)
guessed = False

How terminate this loop after a a given number of attempts?

For the most part it seems to be working, but not how I'm trying to get it to work. When I run it I am allowed unlimited tries to guess every single letter in the word until I spell out the word.
But that's not what I am going for, I'm trying to give the users 5 guesses with single letters if the letter is in the word then it will tell them "Yes", there is a(n) (users guess) in my word, but if the letter is not in my word then it will tell them "No", there is not a(n) (users guess) in my word.
After 5 attempt's at guessing different letters I want them to have to guess the full word but I can't figure out how.
This is what I have now:
import random
def get_word():
words = ['cat', 'dog', 'man', 'fox', 'jar']
return random.choice(words).upper()
def check(word,guesses,guess):
status = ''
matches = 0
for letter in word:
if letter in guesses:
status += letter
else:
status += '*'
if letter == guess:
matches += 1
count = 0
limit = 5
if matches > 1:
print ('Yes! there is a(n)',guess,' in my word.')
guesses += guess
elif matches ==1:
print ('Yes! there is a(n)',guess,' in my word.')
guesses += guess
while count > limit:
input('What do you think my word is')
else:
print('No, there is not a(n)',guess,' in my word.')
guesses += guess
while count > limit:
input('What do you think my word is')
return status
def main():
word = get_word()
guesses = ""
guessed = False
print ('I am thinking of a 3 letter word with no repeating letters. You get five guesses of the letters in my word and then you have to guess the word.')
while not guessed:
text = 'Guess a letter in my word:'
guess = input(text)
guess = guess.upper()
count = 0
limit = 5
if guess in guesses:
print ('You already guessed "' + guess + '"')
elif len(guess) == len(word):
guesses += guess
if guess == word:
guessed = True
else:
print('No, there is not a(n) "' + guess + '"')
elif len(guess) == 1:
guesses += guess
result = check(word,guesses,guess)
if result == word:
guessed = True
else:
print (result)
else:
print ('Invalid entry.')
print ('Yes! you correctly guessed')
main()
For starters while not guessed: will continue until guessed is true -> the word was guessed. Next if you want there to be 5 guesses then an answer guess you want to do for i in range(0, 5): then run your guess logic replacing
if result == word:
guessed = True
with
if result == word:
guessed = true
break
to break out of the loop on a correct guess. Then to allow a guess afterwards, outside of the loop, check if already guessed and allow a guess if not.
Also as a side note you should check that they enter one character with something like
guess = input(text)
while len(guess) != 1:
guess = input(text)
I tried to mostly keep your original code and trail of thought. The main changes I made was getting rid of the check-function as I felt it didn't do anything too useful. I also changed the guessed-variable into a list, and utilized it's properties for your evaluations.
import random
def get_word():
words = ['cat', 'dog', 'man', 'fox', 'jar']
return random.choice(words).upper()
def main():
word = get_word()
guesses = []
guessed = False
print('I am thinking of a 3 letter word with no repeating letters.'
' You get five guesses of the letters in my word and then you have'
' to guess the word.\n')
while not guessed and len(guesses)<5:
text = 'Guess a letter in my word:\n'
guess = input(text)
guess = guess.upper()
if guess in guesses:
print ('You already guessed "', guess, '"\n')
elif len(guess) > 1:
guesses.append(guess)
if guess == word:
guessed = True
else:
print('No, ', guess, 'is not the word!\n')
elif len(guess) == 1:
guesses.append(guess)
if guess in word:
print('Yes there is a(n) ', guess, 'in the word!\n')
else:
print('No, there is not a(n)', guess, 'in the word!\n')
else:
print ('Invalid entry.\n')
if guessed:
print ('You correctly guessed the word!\n')
else:
correct_guesses = [guess for guess in guesses if guess in word]
print('Last chance, what is the full word? (HINT: You have'
'correctly guessed ', str(correct_guesses), ')"')
fword = input()
if fword.upper() == word:
print('You correctly guessed the word!\n')
else: print('Tough luck! You are out of chances! The correct'
'word was ', word, '\n')
main()
playing = True
while playing:
print('Would you like to play again?')
answ = input()
if answ.upper() == 'YES':
main()
else:
print('Thank you for playing.')
playing = False

How to know which letters in hangman the user guessed and how to store them in the final list accordingly to their index in the secret word

I am posting for the first time on Stackoverflow and I don't know if I am doing this the right way, but I am looking to store all letters that the user guessed in a list and if the list is equal to the word, the user wins.
thanks :)
CODE :
word = "apache"
word_list = [x for x in word]
print("The word is ", "_ " * len(word))
final = []
while True:
guess = input("Your guess : ").lower().strip()
if guess.isalpha() and len(guess) == 1 or len(guess) == len(word):
if guess == word or final == word_list:
print("Good joby you have guessed the word!")
break
elif guess in word:
final = "".join(x if x in guess else "_ " for x in word_list)
print("".join(final))
elif len(guess) == len(word) and guess != word:
print("Sorry mate, wrong word")
elif guess not in word:
print("Wrong guess")
else:
print("\nYou need to either enter a word of the same length or a letter\n")
This is the bug I get :
Your guess : a,
a_ a_ _ _
Your guess : p,
_ p_ _ _ _
Your guess : c,
_ _ _ c_ _
Your guess :
It won't store all the letters I guessed before but only the letter I just recently guessed
The first problem is as #Paritosh Singh said you overwrite final. You are also declaring final as a list and overwrite it with a string (which is legal in python). final is probably a string and you need to update it not overwrite it :
word = "apache"
word_list = [x for x in word]
print("The word is ", "_ " * len(word))
final = ""
while True:
guess = input("Your guess : ").lower().strip()
if guess.isalpha() and len(guess) == 1 or len(guess) == len(word):
if guess == word or final == word_list:
print("Good joby you have guessed the word!")
break
elif guess in word:
final = "".join(x if x in guess or x in final else "_ " for x in word_list)
if final == word:
print("Good joby you have guessed the word!")
break
else:
print(final)
elif len(guess) == len(word) and guess != word:
print("Sorry mate, wrong word")
elif guess not in word:
print("Wrong guess")
else:
print("\nYou need to either enter a word of the same length or a letter\n")

HANGMAN assignment python

For an assignment I need to write a basic HANGMAN game. It all works except this part of it...
The game is supposed to print one of these an underscore ("_") for every letter that there is in the mystery word; and then as the user guesses (correct) letters, they will be put in.
E.G
Assuming the word was "word"
User guesses "W"
W _ _ _
User guesses "D"
W _ _ D
However, in many cases some underscores will go missing once the user has made a few guesses so it will end up looking like:
W _ D
instead of:
W _ _ D
I can't work out which part of my code is making this happen. Any help would be appreciated! Cheers!
Here is my code:
import random
choice = None
list = ["HANGMAN", "ASSIGNEMENT", "PYTHON", "SCHOOL", "PROGRAMMING", "CODING", "CHALLENGE"]
while choice != "0":
print('''
******************
Welcome to Hangman
******************
Please select a menu option:
0 - Exit
1 - Enter a new list of words
2 - Play Game
''')
choice= input("Enter you choice: ")
if choice == "0":
print("Exiting the program...")
elif choice =="1":
list = []
x = 0
while x != 5:
word = str(input("Enter a new word to put in the list: "))
list.append(word)
word = word.upper()
x += 1
elif choice == "2":
word = random.choice(list)
word = word.upper()
hidden_word = " _ " * len(word)
lives = 6
guessed = []
while lives != 0 and hidden_word != word:
print("\n******************************")
print("The word is")
print(hidden_word)
print("\nThere are", len(word), "letters in this word")
print("So far the letters you have guessed are: ")
print(' '.join(guessed))
print("\n You have", lives,"lives remaining")
guess = input("\n Guess a letter: \n")
guess = guess.upper()
if len(guess) > 1:
guess = input("\n You can only guess one letter at a time!\n Try again: ")
guess = guess.upper()
while guess in guessed:
print("\n You have already guessed that letter!")
guess = input("\n Please take another guess: ")
guess = guess.upper()
guessed.append(guess)
if guess in word:
print("*******************************")
print("Well done!", guess.upper(),"is in the word")
word_so_far = ""
for i in range (len(word)):
if guess == str(word[i]):
word_so_far += guess
else:
word_so_far += hidden_word[i]
hidden_word = word_so_far
else:
print("************************")
print("Sorry, but", guess, "is not in the word")
lives -= 1
if lives == 0:
print("GAME OVER! You ahve no lives left")
else:
print("\n CONGRATULATIONS! You have guessed the word")
print("The word was", word)
print("\nThank you for playing Hangman")
else:
choice = input("\n That is not a valid option! Please try again!\n Choice: ")
You have hidden_word = " _ " * len(word)
This means that at start for a two letter word, you have [space][underscore][space][space][underscore][space].
When you then do word_so_far += hidden_word[i], for i = 0, you will append a space, not an underscore.
The quickest fix would seem to be:
Set hidden_word to just be _'s (hidden_word = " _ " * len(word))
When you print out the word, do
hidden_word.replace("_"," _ ") to add the spaces around the underscores back
#Foon has showed you the problem with your solution.
If you can divide your code up into small functional blocks, it makes it easier to concentrate on that one task and it makes it easier to test. When you are having a problem with a specific task it helps to isolate the problem by making it into a function.
Something like this.
word = '12345'
guesses = ['1', '5', '9', '0']
def hidden_word(word, guesses):
hidden = ''
for character in word:
hidden += character if character in guesses else ' _ '
return hidden
print(hidden_word(word, guesses))
guesses.append('3')
print(hidden_word(word, guesses))
Below code solves the problem.you can do some modifications based on your requirement.If the Guessed letter exists in the word.Then the letter will be added to the display variable.If not you can give a warning .But note that it might tempt you to write ELSE statement inside the for loop(condition:if guess not in word).If you do like that then the object inside the Else statement will be repeated untill the For loop stops.so that's why it's better to use a separete IF statement outside the for loop.
word="banana"
display=[]
for i in word:
display+="_"
print(display)
while True:
Guess=input("Enter the letter:")
for position in range(len(word)):
if Guess==word[position]:
display[position]=word[position]
print(display)
if Guess not in word:
print("letter Doesn't exist")

Categories

Resources