I am working on making a simple game of Hangman in Python 2. The code I have so far is the ground work I have for it, but it doesn't seem to be working. If I could have a simple wake-up call as to what about what code I made isn't working I would appreciate it.
Code:
secret_word = 'tracy'
secret_word_list = []
for letter in secret_word:
secret_word_list += letter
print secret_word_list
def get_guess(guess = input("Guess: ")):
while len(guess) != 1:
print "Your guess must be exactly one character!"
guess = input("Guess: ")
while guess.isalpha() == False:
print "Your guess must be a lowercase letter!"
guess = input("Guess: ")
while guess.islower == False:
print "Your guess must be a lowercase letter!"
guess = input("Guess: ")
else:
return guess
while True:
if str(get_guess) in secret_word_list:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
get_guess(guess = input("Guess: "))
Output:
Output of the Code
You've got several problems here, but the big one is that you're not calling functions, so you compare the function itself to the secret.
Code with fixes:
secret_word = 'tracy' # Don't make secret_word_list, there's no point; just use the str itself since you only test len 1 strings against it anyway
print secret_word
def get_guess(guess): # Don't make the default call input, that'll prompt once for an input and store it as the permanent default
while True:
# Test each condition and break loop only if all past; original code would never
# recheck length if new value entered after testing isalpha
if len(guess) != 1:
print "Your guess must be exactly one character!"
elif not guess.islower(): # Add missing call parens on islower; use not, never compare to False; islower implicitly verifies isalpha, so avoid testing isalpha
print "Your guess must be a lowercase letter!"
else:
break # Passed all tests, break loop
# Get new guess if any test failed
guess = raw_input("Guess: ") # Use raw_input on Python 2, never input (which eval's the result of raw_input)
# Removed else (loop always ends by breaking, using else nonsensical but harmless in original code too
return guess
while True:
# Move guess getting to if, because having it in else case never actually checked it
if get_guess(raw_input("Guess: ")) in secret_word:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
Try it online!
Note: I kept the kinda odd behavior of having get_guess take an argument, but then reprompt for guesses on failure. A saner solution would be to remove the guess argument entirely, and move the guess = raw_input("Guess: ") to the top of the while loop (removing the else block at the end).
get_guess is a function, you need to put () after it to call the function.
You shouldn't put the call to input() as a default argument. The default value is evaluated once, when the function is defined, not every time the function is called. You should assign guess inside the function.
You should test for all the invalid inputs in a single loop.
def get_guess():
while True:
guess = input("Guess:")
if len(guess) != 1:
print "Your guess must be exactly one character!"
continue
if not guess.isalpha() or not guess.islower():
print "Your guess must be a lowercase letter!"
continue
break
return guess
while True:
guess = get_guess()
if guess in secret_word_list:
print "That letter is in the secret word!"
else:
print "That letter is not in the secret word!"
Related
When I run the code, the 3rd guess gives me an output of High/Low. On the 3rd try, I don't need it to tell me if I'm high or low. How can I fix the problem with out using "while" loops or "range." We haven't covered these two keywords yet.
python
print("You have 3 tries to guess the letter.")
letter = "F"
tries = 0
# [ ] create letter_guess() function, call the function to test
def letter_guess(tries):
if not tries == 3:
guess = input("Guess a letter: ")
tries = tries + 1
check = check_guess (guess,letter)
if check == True:
print('Winner')
else:
letter_guess(tries)
else:
print ("GAME OVER!")
pass
# def check_guess(guess,letter)
def check_guess (guess, letter):
#if else to see if correct letter
if letter == guess.upper():
print ("correct")
return True
elif letter < guess.upper():
print ("You are wrong, guess lower.")
return False
elif letter > guess.upper():
print ("You are wrong, guess higher.")
return False
else:
print("Invalid response!")
return False
letter_guess(tries)
One way to get result similar to a loop is to use recursion. But if you have not done loops yet, you almost certainly have not done recursion. So just use straightforward code.
The tricky part is that you need to ask for a guess, input the guess, and check for a correct guess three times, once for each guess. However, you need to give feedback on whether the guess is high or low only two times. Therefore, you cannot put those actions in the same function. Just split them into separate functions, and handle each guess in your main routine. No need to count guesses--the position in the main routine makes that clear.
"""Guess-a-letter game."""
def get_guess(letter):
"""Get a guess an note if it is correct. If correct, return None.
Otherwise, return the guess."""
guess = input("Guess a letter: ").upper()
if guess == letter:
print("Correct: You win!")
return None
else:
return guess
def give_feedback(guess, letter):
"""Give feedback on a wrong guess."""
if letter < guess:
print("You are wrong, guess lower.")
else:
print("You are wrong, guess higher.")
def letter_guess():
# Store the letter for the user to guess.
letter = "F"
# Introduce the game.
print("You have 3 tries to guess the letter.")
# Handle the first guess.
guess = get_guess(letter)
if guess is None:
return # Success!
give_feedback(guess, letter)
# Handle the second guess.
guess = get_guess(letter)
if guess is None:
return # Success!
give_feedback(guess, letter)
# Handle the third and last guess.
guess = get_guess(letter)
if guess is None:
return # Success!
print("You were wrong three times. GAME OVER!")
letter_guess()
I'm working on a project for CodeHS's intro to python course, and I cannot figure out why this section of code is producing an error message or not working at all.
I have tried removing the variable dashes, and the program works fine without it. For some reason, this new variable causes issues with the final part of the code.
secret_word = "banana"
x = 0
dashes = ""
wordlist = list(secret_word)
for x in range(len(secret_word)):
dashes = dashes + "-"
def get_guess():
while x < 1:
guess = input("Guess: ")
if len(guess) > 1:
print "Your guess must have exactly one character!"
elif not guess.islower():
print "Your guess must be a lowercase letter"
else:
return guess
while dashes != secret_word:
print dashes
guess = get_guess()
if guess in wordlist:
print "That letter is in the word"
else:
print "That letter is not in the word"
I expect the program to ask for an input to guess a letter inside the word; however, the program either runs forever, or I experience an error message. This program is unfinished; any help to fix this error message or make it run more smoothly would be greatly appreciated!
You defined x here:
secret_word = "banana"
x = 0
dashes = ""
wordlist = list(secret_word)
And reassigned values here:
for x in range(len(secret_word)):
dashes = dashes + "-"
Then the condition of the loop is always False here. So get_guess() does nothing.
def get_guess():
while x < 1:
guess = input("Guess: ")
This is a nice example to show how short variable names and global variables are dangerous.
This question already has an answer here:
Python "if" statement not working
(1 answer)
Closed 4 years ago.
I'm learning Python for fun at the moment, and it went all well until now. I'm trying to extend the "Guess the Word"-Game, for example being able to let the Player choose a Word by himself (when 2 People play, 1 chooses the Word, the other guesses) I bet that my Mistake is obvious to me as soon as you point it out, but I'm gonna ask anyway. Well, here is the Code. I put in the entire Program, even tough only the top part should matter. I just put in the rest because it isn't much and maybe you guys can understand it better then.
print("Do you wish to set the Word yourself, or let the program choose?")
user_input = input("1 for own Input - 0 for Program-Input")
if user_input == 1:
Keyword = input("Type in the Word you want to use!")
else:
Keyword = "castle"
word = list(Keyword)
length = len(word)
right = list ("_" * length)
used_letters = list()
finished = False
while finished == False:
guess = input("Guess a Letter!")
if guess not in Keyword:
print("This letter is not in the word. Sorry...")
for letter in word:
if letter == guess:
index = word.index(guess)
right[index] = guess
word[index] = "_"
if guess in used_letters[0:100]:
print("You already used that letter before!")
else:
used_letters.append(guess)
list.sort(used_letters)
print(right)
print("Used letters:")
print(used_letters)
if list(Keyword) == right:
print("You win!")
finished = True
input('Press ENTER to exit')
My problem is, I wanna add the Function to be able to choose if you want to set a Word yourself, or use the word the Program has, defined as "Keyword". But no matter what I input, it always starts with "Guess a Letter" instead of skipping down to where the program sets the Keyword. Thank you in advance for your answers! :)
There's 2 issues with your code.
You put the entire block of code into the else statement. This means that if the if user_input == 1: block ever executed, you would only ask your user for a word and then the program would end because the else statement would be skipped.
You are using if user_input == 1: as your check and this will never be true because user inputs are always read in as strings. A string 1 will never equal the integer 1. This is why your program always skips to the else statement. You need to do if int(user_input) == 1:
Whenever you collect a user's input using the input function, it is a string, not int. this means you will have to either parse the value into an int or evaluate it with a string.
option 1: parsing to int:
user_input = int(input("1 for own Input - 0 for Program-Input"))
option 2: evaluating with string:
if user_input == "1":
input returns a string not a integer so it can never be equal to 1 instead it will be equal to "1".
Plus the code for the user guessing only runs when the program chooses the word so it needs to be unindented.
As a side note your code currently registered capital letters as being different from lower case, you can fix this by putting a .lower() after each input which will turn all capital letters into lowercase.
print("Do you wish to set the Word yourself, or let the program choose?: ")
user_input = input("1 for own Input - 0 for Program-Input")
if user_input == "1":
Keyword = input("Type in the Word you want to use: ").lower()
else:
Keyword = "castle"
word = list(Keyword)
length = len(word)
right = list ("_" * length)
used_letters = list()
finished = False
while finished == False:
guess = input("Guess a Letter: ").lower()
if guess not in Keyword:
print("This letter is not in the word. Sorry...")
for letter in word:
if letter == guess:
index = word.index(guess)
right[index] = guess
word[index] = "_"
if guess in used_letters[0:100]:
print("You already used that letter before!")
else:
used_letters.append(guess)
list.sort(used_letters)
print(right)
print("Used letters:")
print(used_letters)
if list(Keyword) == right:
print("You win!")
finished = True
input('Press ENTER to exit')
The first IF statement is being ignored and I have no idea what could cause this. I checked the indentation and everything seems fine.As you can see in the code it prints numberRolled but when I run it it justs ignores the first IF.`
import random
numberRolled = random.randint(1,6)
print numberRolled
while True:
userGuess = raw_input("Guess a number\n")
if userGuess == numberRolled:
print "You got it right!"
quitYN = raw_input("Would you like to play again?\n").lower()
if quitYN == "yes":
continue
else:
break
elif userGuess != numberRolled:
print "Wrong!"`
raw_input() returns a string, but random.randint() returns an int. This means that when doing userGuess == numberRolled you are comparing a string to an int (which returns False).
To fix this simply convert one of the variables to the correct type:
userGuess == str(numberRolled)
Take a look at this answer for more information about variable types and how to compare them in python.
I'm a newbie writing hangman and have hit a bug in one of my modules. My intent in this module is to check the user input and verify it is a single character that is a letter and not a number. The error checking works in that it won't exit the module until a single letter ( or special, haven't figured a way around that yet) is entered but the return value is always the first user input entered not the last and correct entry. Any suggestions would be appreciated.
def get_guess():
guess = str(raw_input('Please enter your guess letter: '))
if len(guess) == 1:
try:
float(guess)
is_int = True
except ValueError:
is_int = False
if is_int:
print "You have entered a number not a letter."
get_guess()
else:
print "Please enter a single letter."
get_guess()
return guess
You are using recursion to get repeated inputs, but are not returning the recursive call results. You do need to return whatever the recursive call produced to pass it back up the stack:
return get_guess()
You'll need to do this in both locations you are calling get_guess() recursively.
Using recursion to get a response is not a good idea however; never underestimate the determination of idiots to get it wrong and instead hit your recursion limit. Use a loop instead:
def get_guess():
while True:
guess = raw_input('Please enter your guess letter: ')
if len(guess) == 1:
if guess.isdigit():
print "You have entered a number not a letter."
else:
return guess
else:
print "Please enter a single letter."
Here the function keeps looping endlessly until you return the one valid character guess. Note that you probably want to test for str.isalpha() instead if only letters are permitted. Your code and my version allow for anything that is not a digit, so spaces and punctuation are allowed too.
You may also want to study Asking the user for input until they give a valid response