I need to use 'try and except' to catch an error in this code:
while hand_numbers > 0:
hand_type = input('Enter \'n\'to deal a new hand, \'r\' to replay the last hand, or \'e\' to end game: ')
when i type 'r' i get the following error:
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/mit/mit_w4_pset/ps4a - Copy.py", line 310, in <module>
playGame(wordList)
File "C:/Users/User/PycharmProjects/mit/mit_w4_pset/ps4a - Copy.py", line 295, in playGame
playHand(hand, wordList, HAND_SIZE)
UnboundLocalError: local variable 'hand' referenced before assignment
I neeed to replace this error with the phrase:
'You have not played a hand yet. Please play a new hand first!'
I tried the following:
while hand_numbers > 0:
try:
hand_type = input('Enter \'n\'to deal a new hand, \'r\' to replay the last hand, or \'e\' to end game: ')
except UnboundLocalError as Error:
print('You have not played a hand yet. Please play a new hand first!')
continue
but it is not working.. i have tried also except ValueError and NameError.. nothing works.. any advise please? thanks in advance.
see other code:
def playHand(hand, wordList, n):
"""
Allows the user to play the given hand, as follows:
* The hand is displayed.
* The user may input a word or a single period (the string ".")
to indicate they're done playing
* Invalid words are rejected, and a message is displayed asking
the user to choose another word until they enter a valid word or "."
* When a valid word is entered, it uses up letters from the hand.
* After every valid word: the score for that word is displayed,
the remaining letters in the hand are displayed, and the user
is asked to input another word.
* The sum of the word scores is displayed when the hand finishes.
* The hand finishes when there are no more unused letters or the user
inputs a "."
hand: dictionary (string -> int)
wordList: list of lowercase strings
n: integer (HAND_SIZE; i.e., hand size required for additional points)
"""
# BEGIN PSEUDOCODE <-- Remove this comment when you code this function; do your coding within the pseudocode (leaving those comments in-place!)
# Keep track of the total score
total_score = 0
# As long as there are still letters left in the hand:
while (calculateHandlen(hand)) > 0:
#Display the hand
print('Current hand: ', end='')
displayHand(hand)
# Ask user for input
word = input('Enter a valid word, or a "." to indicate that you are finished: ')
# If the input is a single period:
if word == '.':
# End the game (break out of the loop)
print('Goodbye!')
break
# Otherwise (the input is not a single period):
else:
# If the word is not valid:
if isValidWord(word, hand, wordList) == False:
# Reject invalid word (print a message followed by a blank line)
print('Invalid word, please try again: \n')
# Otherwise (the word is valid):
else:
# Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
score = getWordScore(word, HAND_SIZE)
total_score = total_score + score
print('Score earned: ', getWordScore(word, HAND_SIZE), 'Your current total score is: ', total_score, '\n')
# Update the hand
hand = updateHand(hand, word)
if calculateHandlen(hand) == 0:
print('You have no more letters to play,Game over!')
# Game is over (user entered a '.' or ran out of letters), so tell user the total score
print('Total score for this hand is: '+str(total_score)+' points.')
def playGame(wordList):
"""
Allow the user to play an arbitrary number of hands.
1) Asks the user to input 'n' or 'r' or 'e'.
* If the user inputs 'n', let the user play a new (random) hand.
* If the user inputs 'r', let the user play the last hand again.
* If the user inputs 'e', exit the game.
* If the user inputs anything else, tell them their input was invalid.
2) When done playing the hand, repeat from step 1
"""
# TO DO ... <-- Remove this comment when you code this function
hand_numbers = 10
while hand_numbers > 0:
hand_type = input('Enter \'n\'to deal a new hand, \'r\' to replay the last hand, or \'e\' to end game: ')
choices = ['e','n','r']
if hand_type not in choices:
print('Invalid command.')
elif hand_type == 'e':
print ('Goodbye!')
break
else:
if hand_type == 'n':
hand = dealHand(HAND_SIZE)
playHand(hand, wordList, HAND_SIZE)
elif hand_type == 'r':
playHand(hand, wordList, HAND_SIZE)
hand_numbers -= 1
#print(hand_numbers)
#
# Build data structures used for entire session and play game
#
if __name__ == '__main__':
wordList = loadWords()
playGame(wordList)
while hand_numbers > 0:
hand_type = input('Enter \'n\'to deal a new hand, \'r\' to replay the last hand, or \'e\' to end game: ')
These are not the lines you're looking for. Try-except here will not catch your error.
It is here:
if hand_type == 'n':
hand = dealHand(HAND_SIZE)
playHand(hand, wordList, HAND_SIZE)
elif hand_type == 'r':
playHand(hand, wordList, HAND_SIZE)
The problem is simple: hand is undefined in the second branch (nested under the elif). It is only defined in the first branch (nested under the if). Hence, when you type r, an error occurs.
The solution is equally simple: make sure hand is defined for both if and elif branches. To do this, you can either move the declaration of hand above the if-statement or copy it into the elif branch.
Related
Describing the game if you know what means word guessing dont bother to read
Hey! I know I opened a question about that earlier but again Im stuck in another situation. I making a game that there is a list full of words and computer choses a random word in it. And program asking to person guess a letter. If it is in letter it should write the letter in exact order in that word. Lets say our word is word.
If user input is "w", program will print "w___" and again
if user says "o" program will print "wo__" like that.
What is the issue?
I did achieve to print if user input in that word and in which order in that word but when user guess again when he got right in first letter my print variable refreshing and prints just last guessed letter.
Let me explain
My word again "word" and user guess "w" letter first.
So program will print "w___"
But when user guess again and lets say he/she guessed "o" this time.
Program prints just "_.o__" but not w.
What I want to do
Program should keep the last data as "w___" and add "o" letter to second place.
Program should have an if statment and two variables. First is guess_count and other is error_count.
If player guessed right increase guess_count by one and
if guess_count == 5 # word's total letter number: print("Win"), break the loop
If player guessed wrong increase error_count by one and
if error_count == 3 # if player type 3 wrong letter: print("Lose"), break the loop
My code
Create a loop
run = True
while run:
Create a namelist and chose a random name
name_list = ["sound"]
pick_word = random.choice(name_list)
Create a while loop again # whole code is under this
while True:
Get user input
user_input = input("Guess a letter: ")
Creating if statment if for if input len > 1 get error
Whole if true code in there
if len(user_input) == 1:
*Create a variable that gets user input in order of word as number.
(I cant say that sentence in english)
index = pick_word.index(user_input)
Replace the order number to user input
word_tracker[index] = user_input
Create a string to print it
word = "".join(word_tracker)
Print it
print(word)
Increase guess_count
count += 1
If guess_count is 5 break the loop
if count == 5:
If guess not in word
except ValueError:
print("You couldnt guess the letters.")
guessing += 1
if guessing == 3:
print("Peh")
exit()
If guessed letter not 1 character
else:
print("You allowed to type just one letter")
I hope I wont get ban haha
try changing
word_tracker[index] = user_input
to
word_tracker.append(user_input)
That is if 'word_tracker' is a list
The program asks for a string and outputs the string remaining after removing groups of 3 or more meaning it can be 3, 4, 5, 6, and so on, consecutive identical characters. The removal of the groups continues until no more groups are found to be removed. The program should allow repetition until the user does not want to continue. The code must only use while, if, elif, else and no other functions
#Message
print("Hello! Welcome to Candy Crush!") #Introduces user to the application
#Input data
while True:
decision = str(input("Would you like to add a string? ")) #Asks the user if they would like to enter a string.
#Process data
if decision == "Yes" or decision == "yes": #If the user answers yes, it continues but if the user answers something else other than yes and no, it repeats the option.
stringInput = str(input("Please enter a string: ")) #Asks the user to enter the string.
charactersInput = list(stringInput) #Stores the user input in a list.
print("Your original list is", charactersInput)
print("Your original string: ", stringInput)
idx = 0 #This number helps to keep track of what letter the program is processing.
while idx < len(charactersInput) - 2:
if charactersInput[idx] == charactersInput[idx + 1] == charactersInput[idx + 2]:
charactersInput.pop(idx) #The code removes the first index letter.
charactersInput.pop(idx) #The code removes the second index letter.
charactersInput.pop(idx) #The code removes the third index letter. Once the three letters have been removed the next letters take their place.
idx = 0
else:
idx += 1 #One is added to the index to see if the new index number is followed by repeated letters.
result = "".join(charactersInput)#After the code has ran, the following code takes all the results and adds the strings to charactersInput. The information is stored in the variable result.
#Output data
print("The output of your string is: ", result,"\n") #Prints the information stored in result. The information does not include the consecutive letters.
if decision == "No" or decision == "no":
print("Thank you for playing! Have a great day!") #The user is shown a goodbye message and the code ends.
exit() #The application ends if the user answers no
pop is not allowed. Use remove instead. Also, no use of break.
Code:-
#Message
print("Hello! Welcome to Candy Crush!") #Introduces user to the application
#Input data
while True:
decision = str(input("Would you like to add a string? ")) #Asks the user if they would like to enter a string.
#Process data
if decision == "Yes" or decision == "yes": #If the user answers yes, it continues but if the user answers something else other than yes and no, it repeats the option.
stringInput = str(input("Please enter a string: ")) #Asks the user to enter the string.
charactersInput = list(stringInput) #Stores the user input in a list.
print("Your original list is", charactersInput)
print("Your original string: ", stringInput)
stack = []
char_num=3
for ch in stringInput:
if stack and ch != stack[-1][0] and stack[-1][1] >= char_num:
stack.pop()
if not stack or ch != stack[-1][0]:
stack.append([ch, 1])
else:
stack[-1][1] += 1
if stack and stack[-1][1] >= char_num:
stack.pop()
result = ""
while stack:
item = stack.pop()
result = item[0]*item[1] + result
#Output data
print("The output of your string is: ", result,"\n") #Prints the information stored in result. The information does not include the consecutive letters.
if decision == "No" or decision == "no":
print("Thank you for playing! Have a great day!") #The user is shown a goodbye message and the code ends.
exit() #The application ends if the user answers no
Output:-
Hello! Welcome to Candy Crush!
Would you like to add a string? yes
Please enter a string: aaaabbbcccd
Your original list is ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd']
Your original string: aaaabbbcccd
The output of your string is: d
Other changes i prefer you should do..
(1)No need to check like this if decision == "Yes" or decision == "yes": instead check like if decision.lower()=="yes": same goes for no one also..
I am working on a hangman project and have run into a problem where the main function only runs for part of its entirety, then it stops. I made a smaller version of my original project to focus on the problem more.
import re
import time
import sys
#hangman shows the player how many incorrect guesses they did
hangman =['0','1','2','3','4','5','6','7']
print('\n')
w = input ('type what word you want to guess: ')
for i in range(50):
print('\n')
#blank_list creates a blank list from the word they choose above. It takes all letters and
#turns them into underscores, while special characters are exempt.
blank_list = []
blank_list = re.sub('A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z', '_', w)
blank_list = ' '.join(blank_list)
incorrect = 0
def guesscounter(w,blank_list,incorrect):
#main loop, lets player input their guess
while incorrect < 7:
print(hangman[incorrect])
print(blank_list)
guess = input('What letter would you like to guess? ').upper
#this is where it stops
return guess
for i in range(50):
print('\n')
#makes a player only guess one letter or get penalized
if guess > 0:
print("Ummmm, you can't guess more than one letter at a time. . . Have you played hangman before?")
incorrect = incorrect + 1
return incorrect
for i in range(50):
print('\n')
#determines whether guess is in word
if w.count(guess) == -1:
incorrect = incorrect+1
print("Sorry, {} isn't in the word. Try again!".format(guess))
time.sleep(3)
for i in range(50):
print('\n')
#replaces a blank with its letter when the player guesses correctly
else:
print('Good job! you got one!')
locate = w.find(guess)
blank_list.insert(guess,locate)
return blank_list
time.sleep(3)
for i in range(50):
print('\n')
#tells when the player guesses all of the letters
if blank_list.count('_') == -1:
print('Wow, you win! Nice job!')
sys.exit
#tells when the player runs out of chances
while incorrect == 7:
print('You lose! The word was {}! Better luck next time'.format(w))
guesscounter(w,blank_list,incorrect)
it currently only runs the first section guesscounter, from the top of the function to the guess input (when it ends, the shell says that guess is not defined). I will answer any questions that you have to the best of my abilities.
In your guesscounter function, after you ask the user/player "What letter would you like to guess?", in the next line you do return guess. That returns the value in the function, an explicit return statement immediately terminates a function execution and sends the return value back to the caller code. (you can read more here: https://realpython.com/python-return-statement/). So it doesn't look like you really need that return statement because the code below that is always unreachable, unless there is a reason you can comment on?
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 +'.')
I'm new to coding and am currently trying to make a simplified game of Hangman using Python 3. For the most part, I have it down, except for the most important part, how to hide the letters of the random word, and then how to reveal them once guessed. Mainly, I just need a quick answer. Any help would be greatly appreciated. Here's my code so far (sorry if it's long, like I said, I relatively new at this, and thanks again!):
import random
#list of words for game
hangmanWords = ("Halloween","Hockey","Minnesota","Vikings","Twins","Timberwolves","Wild","Playstation","Achievement","Minecraft","Metallica","Portal","Xbox","Guitar")
#randomizes the word chosen for game
index = random.randint(0,len(hangmanWords)-1)
#assigns radomized word to variable
randomWord = hangmanWords[index]
'''
menu function, provides user with choices for game, user chooses via imput
'''
def menu():
print("""
Welcome to Hangman!
Select a difficulty:
1. Easy (9 Misses)
2. Medium (7 Misses)
3. Advanced (5 Misses)
4. Exit Game
""")
selection = int(input("What difficulty do you pick (1-4)?: "))
return selection
'''
the function for easy mode, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets 9 guesses to figure out word, correct guesses don't
count, returns player to main menu when they lose
'''
def easyMode():
wrongGuesses = 0
listOfGuesses = []
print(randomWord)
while(wrongGuesses != 9):
x = input("Enter a letter: ")
if x.lower() in randomWord.lower():
print(x,"is in the word!")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
else:
print(x,"is not in the word.")
wrongGuesses += 1
print(wrongGuesses, "wrong guesses.")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
print("You lost the game!")
return x
'''
the function for medium mode, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets 7 guesses to figure out word, correct guesses don't
count, returns player to main menu when they lose
'''
def medium():
wrongGuesses = 0
listOfGuesses = []
print(randomWord)
while(wrongGuesses != 7):
x = input("Enter a letter: ")
if x.lower() in randomWord.lower():
print(x,"is in the word!")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
else:
print(x,"is not in the word.")
wrongGuesses += 1
print(wrongGuesses, "wrong guesses.")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
print("You lost the game!")
return x
'''
the function for advanced mode, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets 5 guesses to figure out word, correct guesses don't
count, returns player to main menu when they lose
'''
def advanced():
wrongGuesses = 0
listOfGuesses = []
print(randomWord)
while(wrongGuesses != 5):
x = input("Enter a letter: ")
if x.lower() in randomWord.lower():
print(x,"is in the word!")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
else:
print(x,"is not in the word.")
wrongGuesses += 1
print(wrongGuesses, "wrong guesses.")
listOfGuesses.append(x)
print("Letters guessed so far: ",listOfGuesses)
print()
print("You lost the game!")
return x
'''
main function, deals with what happens depending on
what the player selected on the menu
'''
def main():
select = menu()
while(select != 4):
if(select == 1):
easyMode()
elif(select == 2):
medium()
elif(select == 3):
advanced()
select = menu()
print("You don't want to play today? :'(")
main()
If you want to try it out yourself, then please don't see the code yet. Like in hangman, we get to see our progress (partially guessed word), you should create another variable that holds such a string. And, with every correct guess, you should update this string accordingly. The string obviously starts out as ##### or ***** according to the length of the word to be guessed.
With several improvements, I present to you, Hangman!
All credits go to you of course!
import random
#list of words for game
hangmanWords = ("Halloween","Hockey","Minnesota","Vikings","Twins","Timberwolves","Wild","Playstation","Achievement","Minecraft","Metallica","Portal","Xbox","Guitar")
#assigns radomized word to variable
randomWord = random.choice(hangmanWords)
'''
menu function, provides user with choices for game, user chooses via imput
'''
def menu():
print("""
Welcome to Hangman!
Select a difficulty:
1. Easy (9 Misses)
2. Medium (7 Misses)
3. Advanced (5 Misses)
4. Exit Game
""")
selection = int(input("What difficulty do you pick (1-4)?: "))
return selection
def game(mode):
'''
the game function, prints the word chosen by randomizer
asks the player to enter a letter that they guess is in the word
player gets guesses according to value passed as per mode,
to figure out the word, correct guesses don't count,
returns player to main menu when they lose
'''
modes = {1:9, 2:7, 3:5} # Matches mode to guesses
guesses = modes[mode]
wrongGuesses = 0
listOfGuesses = []
# print(randomWord) Dont't print the solution!!
# Get a random word which would be guessed by the user
to_guess = random.choice(hangmanWords)
to_guess = to_guess.lower()
# The correctly guessed part of the word that we print after every guess
guessed = "#"*len(to_guess) # e.g. "Hangman" --> "#######"
while(wrongGuesses != guesses):
x = input("Word - %s . Guess a letter: "%guessed).lower()
if x in to_guess:
print(x,"is in the word!")
listOfGuesses.append(x)
# Now replace the '#' in 'guessed' to 'x' as per our word 'to_guess'
new_guessed = ""
for index, char in enumerate(to_guess):
if char == x:
new_guessed += x
else:
new_guessed += guessed[index]
guessed = new_guessed # Change the guessed word according to new guess
# If user has guessed full word correct, then he has won!
if guessed == to_guess:
print("You have guessed the word! You win!")
print("The word was %s"%to_guess)
return True # return true on winning
else:
print("Letters guessed so far:", listOfGuesses, "\n")
else:
print(x,"is not in the word.")
wrongGuesses += 1
print("Wrong guesses:", wrongGuesses)
listOfGuesses.append(x)
print("Letters guessed so far:", listOfGuesses, "\n")
print("You lost the game!")
print("The word was %s"%to_guess)
return False # return false on loosing
'''
main function, deals with what happens depending on
what the player selected on the menu
'''
def main():
select = menu()
while(select != 4):
game(select)
select = menu()
print("You don't want to play today? :'(")
main()
Wherever you see copy-paste or code repetition, it's not Pythonic! Try to avoid repetition, especially in functions. (like your easy, medium & hard functions)
The other answer implements it for you, but I'll walk you through the methodology so you can improve as a programmer.
You're going to want two lists, one that has the full word, and one that has the list you want to display. You can either make a binary list that is the same length as the word, or you can make a "display list", that is full of underscores, until the correct letter is guessed.
The display list method should look something like this and is easier to impliment:
To initialize displaylist:
for _ in range(len(randomword)):
displaylist.append("_")
Then within the if statement:
for i in range(len(randomword)):
if x == randomword[i]:
displaylist[i] = x
And then to print, you would need something like this:
print(''.join(displaylist))
Another improvement you could make is making a separate function that checks your word so that you can most effectively use modular programming. This would cut down on code complexity, redundancy, and make it easier to implement changes.