I am trying to get the elif to work, I have tried allsorts and going a bit mad now.
Basically if guessed is not equal to an entry from randomwordslist then it should state it and not reduce guesses and not go to else statement.
error is "NameError: name 'word' is not defined"
Am I going about this all wrong?
while guess > 0:
guessed = input("Guess ({} attempts left):".format(guess))
guess = guess -1
if guessed == answer:
print("+++++ You have won ++++++")
break
elif guessed != word in randomwordslist:
print("Only words from above count as valid entries")
continue
else:
match = 0
for i in range(len(guessed)):
if guessed[i].lower() == answer[i].lower():
match += 1
You are asking Python to test two things:
guessed != word and word in randomwordslist
because Python comparisons are chained. But you don't have word defined which is why you get the exception.
Just test if guessed is not in randomwordslist:
if guessed not in randomwordslist:
if you wanted to verify that the string is not part of the list. not in is the opposite of in, the latter tests if a value is a member of the second operand.
If you don't want the number of guesses affected, move the test up so that you check it first:
while guess > 0:
guessed = input("Guess ({} attempts left):".format(guess))
if guessed not in randomwordslist:
print("Only words from above count as valid entries")
continue
# valid guess, so it counts.
guess = guess - 1
if guessed == answer:
print("+++++ You have won ++++++")
break
Replace your elif block by this one:
elif guessed not in randomwordslist:
print("Only words from above count as valid entries")
continue
Related
Specifically, I'm doing the hangman challenge from the 100 days of coding by UDEMY. I can't seem to figure out how to check if the user has lost by reaching "0" of "6" lives. When I use this code, it subtracts 1 from "lives" during every instance in the for loop that doesn't match the guess:
lives = 6
while not end_of_game:
guess = input("Guess a letter: ").lower()
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
elif letter != guess:
lives -= 1
if lives == 0:
end_of_game = True
print(f"{' '.join(display)}")
I just did some bench checking of your code. After straightening out the indentation, the main problem I spot in your code is that even if a guessed letter is found and you update the display position, your "for" loop keeps checking the guessed letter against the remaining letters in your word. And that then decrements the life count even when there is a good guess.
I would think that you would want your code to more closely resemble the following code snippet:
lives = 6
while not end_of_game:
guess = input("Guess a letter: ").lower()
found_letter = False # Additional test variable
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
found_letter = True
if found_letter == False: # Do the test for good/bad guess here
lives -= 1
if lives == 0:
end_of_game = True
break
print(f"{' '.join(display)}")
The additional true/false variable "found_letter" would dictate whether or not the life count should be decremented and the test would occur once the whole word has been checked for the guessed letter.
Give that a try.
I'm trying to store the guesses so that I can make code for if you have already guessed that letter and also to make code for when they get all of the letters correct. I may be stuck on that part, too, since I don't know how to check if the letters correspond to the letters in the wordname list, especially when it isn't even ordered.
So, I am looking for some code that would store the guesses and also something that can check if all of the correct letters have been guessed. I am thinking it may have something to do with the enumerate() function, but I am not sure since I have never used it before and have only just heard about it.
Also, for your information, the game is hangman if that helps.
wordname = word_choosing()
wordnamelength = len(wordname)
wordnamelist = list(wordname)
def letter_guess1():
sleep(1)
tries = 5
print(f"{oppositeplayer}, the word is {wordnamelength} letters long")
while tries > 0:
guess1 = input("Make your guess: ")
if guess1 in wordnamelist:
print("Congrats, that is correct")
letternum = wordnamelist.index(guess1)
letternum += 1
print(f"This letter is number {letternum}")
elif guess1 not in wordnamelist:
tries -= 1
print(f"You have {tries} left")
if guess1 == "quit".lower():
exit()
return tries
tries = letter_guess1()
I think set is very suitable in this situation. Keep the letters of the word being guessed as a set and add the guess to another set. Then, you can check if the word was guessed correctly by using the intersection of both sets.
Something like that:
wordname = word_choosing()
wordnamelength = len(wordname)
wordnamelist = list(wordname)
def letter_guess1():
sleep(1)
tries = 5
print(f"{oppositeplayer}, the word is {wordnamelength} letters long")
word_set = set(wordname)
guessed_letters = set()
while tries > 0:
guess = input("Make your guess: ")
if guess in guessed_letters:
print("You already guessed this letter")
continue
guessed_letters.add(guess)
if guess in word_set:
print("Congrats, that is correct")
letternum = wordnamelist.index(guess)
letternum += 1
print(f"This letter is number {letternum}")
elif guess not in word_set:
tries -= 1
print(f"You have {tries} left")
if word_set.intersection(guessed_letters) == word_set:
print("You have won!")
if guess == "quit".lower():
exit()
return tries
tries = letter_guess1()
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')
So I have a quick question about the below code. In the program it will display a series of dashes to match the random word selected. When the player guesses, the program goes through a loop that checks the guess. My question is, and what I'm really confused over, is how does the program know to replace the exact dash needed to display an accurate and partially revealed word? and what is new += so_far[i] doing? overall, that section really confuses me and I would greatly appreciate some clarification. Thanks!
MAX_WRONG = len(HANGMAN) - 1
# creating list of random words
WORDS = ("TECHNOLOGY", "PYTHON", "SCRIPT", "PROCESSOR", "RANDOM", "COMPUTING")
# initialize variables
word = random.choice(WORDS)
so_far = "-" * len(word) # one dash for every letter in the word to be guessed
wrong = 0 # number of wrong guesses made
used = [] # letters already guessed
# creating the main loop
print("Welcome to Hangman. Good luck!")
while wrong < MAX_WRONG and so_far != word:
print(HANGMAN[wrong])
print("\nYou've used the following letters:\n", used)
print("\nSo far, the word is:\n", so_far)
# getting the player's guess
guess = input("\n\nEnter your guess: ")
guess = guess.upper()
while guess in used:
print("You've already guessed the letter", guess)
guess = input("\nEnter your guess: ")
guess = guess.upper()
used.append(guess)
# checking the guess
if guess in word:
print("\nYes!", guess, "is in the word!")
# create a new so_far to include guess
new = ""
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new
else:
print("\nSorry,", guess, "isn't in the word.")
wrong += 1
# ending the game
if wrong == MAX_WRONG:
print(HANGMAN[wrong])
print("\nYou lose!")
else:
print("\nYou guessed it!")
print("The word was:", word)
ext()
You are looking out for this section in the code which does that
for i in range(len(word)):
if guess == word[i]:
new += guess
else:
new += so_far[i]
so_far = new
Say if you guess the word 'S' and say if the word to be guessed is 'Super'
Initial state
Sofar : -----
During the iteration process a variable 'new' is assigned the value for each word match. if not matched take that value from so_far[i]
In our case
Length of word = len('Super') = 5
Iter 1: will only go to ig loop since 'S' occurs only once.
This means all other iterations go to else condition and since all so_far[i] has '-' as values.
So after the first loop of iteration your values look like this
new: S----
At the end of loop reassign new to so_far. This means now 'so_far' variable has changed from '-----' to 'S----'.
I suggest you to use a pdb to debug above the for loop and get the details when you get to such doubts in future.
Hope this helps.
My code is:
import random
WORDS = ('python', 'football', 'facebook', 'photo') #list of words that will be riddled
word = random.choice(WORDS)
correct = word
jumble = ''
hint = 'hint'
score = 0
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):] #creating jumble of correct words
print('Welcome to the game "Anagrams"')
print('Here`s your anagram:', jumble) #Welcoming and giving a jumble to a player
guess = input('\nTry to guess the original word: ')
if guess == correct:
score += 5
print('You won! Congratulations!') #end of game in case of right answer
if guess == hint: #situation if player asks a hint
if correct == WORDS[0]:
print('snake')
elif correct == WORDS[1]:
print('sport game')
elif correct == WORDS[2]:
print('social network')
elif correct == WORDS[3]:
print('picture of something')
score += 1
while guess != correct and guess != '': #situation if player is not correct
print('Sorry, you`re wrong :(')
guess = input('Try to guess the original word: ')
print('Thank you for participating in game.')
print('Your score is', score)
input('\nPress Enter to end')
When asking hint string :
'Sorry, you`re wrong :('
repeats.
It looks like:
Try to guess the original word: hint
sport game
Sorry, you`re wrong :(
How to make this string appear only in case of wrong guess?
change you last while to this:
while guess != correct and guess != '':
guess = input("Sorry, you`re wrong:( ")
In your code, when the player types hint the player gets a hint, but then the program tests the 'hint' string against the correct word. Of course, 'hint' isn't the correct answer, so your program tells them that it's wrong.
Just for fun, I've optimized your code a little, and improved the scoring logic. :)
Your letter-jumbling for loop is quite clever, but there's a more efficient way to do this, using the random.shuffle function. This function shuffles a list, in place. So we need to convert the chosen word into a list, shuffle it, and then join the list back into a string.
I've also replaced your hints logic. Rather than having to do a whole bunch of if tests to see which hint goes with the current word it's much simpler just to store each word and its associated hint as a tuple.
import random
#Words that will be riddled, and their hints
all_words = (
('python', 'snake'),
('football', 'sport game'),
('facebook', 'social network'),
('photo', 'picture of something'),
)
#Randomly choose a word
word, hint = random.choice(all_words)
#Jumble up the letters of word
jumble = list(word)
random.shuffle(jumble)
jumble = ''.join(jumble)
print('Welcome to the game "Anagrams"\n')
print('You may ask for a hint by typing hint at the prompt')
print('Wrong guesses cost 2 points, hints cost 1 point\n')
print("Here's your anagram:", jumble)
score = 0
while True:
guess = input('\nTry to guess the original word: ')
if guess == word:
score += 5
print('You won! Congratulations!')
break
if guess == 'hint':
#Deduct a point for asking for a hint
score -= 1
print(hint)
continue
#Deduct 2 points for a wrong word
score -= 2
print('Sorry, you`re wrong :(')
print('Thank you for participating in game.')
print('Your score is', score)
input('\nPress Enter to end')
Your special logic for a correct guess and for the special input "hint" is only run once on the very first guess. Your loop for incorrect values always runs after that. I think you want to move all the logic into the loop:
while True: # loop forever until a break statement is reached
guess = input('\nTry to guess the original word: ')
if guess == correct:
score += 5
print('You won! Congratulations!')
break # stop looping
if guess == hint: # special case, asking for a hint
if correct == WORDS[0]:
print('snake')
elif correct == WORDS[1]:
print('sport game')
elif correct == WORDS[2]:
print('social network')
elif correct == WORDS[3]:
print('picture of something')
score += 1
else: #situation if player is not correct, and not askng for a hint
print('Sorry, you`re wrong :(')
I've left out the situation where your code would exit the loop on an empty input. If you want that, you should add it explicitly as an extra case, with a break statement.
Lets try to fix some problems:
this
if guess == hint: #situation if player asks a hint
should probably be
elif guess == hint: #situation if player asks a hint
And also this seems wrong to me
while guess != correct and guess != '': #situation if player is not correct
print('Sorry, you`re wrong :(')
guess = input('Try to guess the original word: ')
should be probably changed into that (indentation is important):
guess = input('Try to guess the original word: ')
if guess != correct and guess != '': #situation if player is not correct
print('Sorry, you`re wrong :(')
I have not tried this corrections in a complete program.