I am currently creating a hangman game for a project. I have managed to code where a user can enter individual letters to guess the secret word. However, I am having trouble adding an additional feature where the user can guess the entire word upfront.
below is my code attempt, may I know what to write to have this new feature in my game?
def game_play():
word = random.choice(WORDS)
# Dashes for each letter in each word
current_guess = "-" * len(word)
# Wrong Guess Counter
wrong_guesses = 0
# Used letters Tracker
used_letters = []
while wrong_guesses < MAX_WRONG and current_guess != word:
print (HANGMAN[wrong_guesses])
print ("You have used the following letters: ", used_letters)
print ("So far, the word is: ", current_guess)
guess = input ("Enter your letter guess:")
guess = guess.upper()
# Check if letter was already used
while guess in used_letters:
print ("You have already guessed that letter", guess)
guess = input ("Enter your letter guess: ")
guess = guess.upper()
# Add new guess letter to list
used_letters.append(guess)
# Check guess
if guess in word:
print ("You have guessed correctly!")
# Update hidden word with mixed letters and dashes
new_current_guess = ""
for letter in range(len(word)):
if guess == word[letter]:
new_current_guess += guess
else:
new_current_guess += current_guess[letter]
current_guess = new_current_guess
else:
print ("Sorry that was incorrect")
# Increase the number of incorrect by 1
wrong_guesses += 1
# End the game
if wrong_guesses == MAX_WRONG:
print (HANGMAN[wrong_guesses])
print ("You have been hanged!")
print ("The correct word is", word)
else:
print ("You have won!!")
game_play()
Rather than prompting the user for a new guess each time, you could overwrite the line where you output their previous guesses so far, so the output may look something like:
Word: _ A N _ _ A N Misses: B C D
This would mean they could just keep typing guess and the line would update. See python overwrite previous line for details on how to overwrite previous line.
The input command will let you enter multiple letters. I don't see anything stopping the user entering the full word there already?
Instead of counting each letter which matches/fails you could maintain a set of correct/failed guesses and check against the number of items in the set. Maybe something like:
import random
WORDS = ['STACK', 'OVERFLOW', 'HELP']
def playgame():
word = random.choice(WORDS)
# valid characters
valid = set((chr(c) for c in range(ord('A'), ord('A') + 26)))
# unique characters in word
unique = set((c for c in word))
hits = set()
misses = set()
allowed_misses = 5
complete = False
while complete == False:
guess = input("Enter your guess: ").upper()
for c in (c for c in guess if c in valid):
if c in unique:
hits.add(c)
else:
misses.add(c)
# break out of for
if len(hits) == len(unique) or len(misses) > allowed_misses:
complete = True
break
if not complete:
# output continuation messages
print(f'Hits: {hits} misses: {misses}')
if len(hits) == len(unique):
# output sucess message
print(f'Success: hits {hits} misses {misses}')
else:
# output fail message
print(f'Fail: hits {hits} misses {misses}')
if __name__ == '__main__':
playgame()
I have included the additional feature to enter the entire word, and also refactored your code. If the user entered the entire word correctly, I'd assign current_guess with the correct word and break the while loop. Please have a look
import random
WORDS = ['apple', 'kiwi', 'banana']
MAX_WRONG = 3
def game_play():
word = random.choice(WORDS).upper()
current_guess = '-' * len(word) #hidden answer
wrong_guesses = 0
used_letters = []
while wrong_guesses < MAX_WRONG and current_guess != word:
print ('\nRemaining tries:', MAX_WRONG - wrong_guesses)
print ('So far, the secret word is: ', current_guess)
print ('You have used the following letters: ', used_letters)
guess = input('Enter your letter guess:').upper()
if guess == word:
current_guess = word
break #exit the while-loop
while guess in used_letters: #check for duplicate input
print ('You have guessed "' + guess + '" already!')
guess = input ('Enter your letter guess: ').upper()
used_letters.append(guess) #append guess to used_letters
if guess in word:
print ('You have guessed correctly!')
new_current_guess = ''
for idx in range(len(word)): #update hidden answer
if guess == word[idx]:
new_current_guess += guess
else:
new_current_guess += current_guess[idx]
current_guess = new_current_guess
else:
print ('Sorry that was incorrect')
wrong_guesses += 1
if wrong_guesses == MAX_WRONG:
print ('\nYou have been hanged!')
print ('The correct word is', word)
elif current_guess == word:
print ('\nYou have won!! The word is:', word)
game_play()
Output:
Remaining tries: 3
So far, the secret word is: ----
You have used the following letters: []
Enter your letter guess: i
You have guessed correctly!
Remaining tries: 3
So far, the secret word is: -I-I
You have used the following letters: ['I']
Enter your letter guess: kiwi
You have won!! The word is: KIWI
I'm trying to build a basic program where the computer selects a word out of a pre-existing list (called "words") and the user must guess the appropriate letters to guess the word. This is what the main function looks like so far:
def game():
word = random.choice(words)
while ' ' or '-' in word:
word = random.choice(words)
if ' ' or '-' not in word:
break
print(f'Hint: The chosen word is {len(word)} letters long')
letters = list(word)
progress = []
while True:
guess = str(input('Guess a letter: '))
if len(guess) > 1:
print('Sorry, guess a single letter: ')
if guess in word:
print(f'The letter {guess} is in the word')
for i, j in enumerate(letters):
if progress.count(guess) >= letters.count(guess):
break
elif j == guess:
progress.insert(i, j)
print('Current progress: ' + '-'.join(progress))
if len(progress) == len(word):
if letters[:] == progress[:]:
print('Congrats! You found the word: ' + str(word))
break
elif guess not in word:
print(f'The letter {guess} is not in the word: Try Again')
continue
My issue is with the for loop where I use enumerate(y) and the respective "elif j == guess" condition. I noticed that when running the function, the code works if the letters that are repeated are successive (ex: in the word "chilly", if I type in "l", the function correctly displays the two l's and the game works as intended). However, if the letters are repeated separately (ex: the word "cologne"), the function doesn't insert the "l" between the two o's, and keeps the two o's together regardless, thus preventing the proper word from ever being guessed. Is there a different method I could use to fix this problem?
You should remember the letters already guessed and simplyfiy the printing to any letter that you remember and use - for any other letter in the word.
Your errror stems from your list and counting method to remember which letters to print or not.
I fixed your incorrect if-condition (see How to test multiple variables against a value? for more on that).
import random
# supply list of words to function to avoid globals
def game(words):
word = random.choice(words)
# fixed your check ... not sure why you do that
while ' ' in word or '-' in word:
word = random.choice(words)
# no break needed, will break if no space/- in
print(f'Hint: The chosen word is {len(word)} letters long')
# remember which letters where guessed already
guesses = set()
while True:
guess = input('Guess a letter: ') # no str needed it is already a str
if len(guess) > 1:
print('Sorry, guess a single letter: ')
continue # back to while loop
# add to guessed letters
guesses.add(guess)
# print message
if guess in word:
print(f'The letter {guess} is in the word')
else:
print(f'The letter {guess} is not in the word: Try Again')
continue # back to while loop
print('Current progress: ', end="")
# assume we have all letters guessed
done = True
for idx, letter in enumerate(word):
if letter in guesses:
# print letter if already guessed
print(letter, end="")
else:
# invalidate assumption and print -
done = False
print("-",end="")
print()
# if assumption not invalidated: done
if done:
print('Congrats! You found the word: ' + str(word))
break
game(["eye", "ear", "egg", "anvil"])
Output:
Hint: The chosen word is 3 letters long
Guess a letter: The letter e is in the word
Current progress: e-e
Guess a letter: The letter r is not in the word: Try Again
Current progress: e-e
Guess a letter: The letter y is in the word
Current progress: eye
Congrats! You found the word: eye
So I am stuck with the part of checking if the letter is present in the word or not. The game needs to let a person guess a letter in the word, and tell if this letter is present in word or not(5 attempts only)
import random
i=0
WORDS= ("notebook","pc", "footprint")
word = random.choice(WORDS)
print(len(word))
while i<5:
inp = input("What's your guess for a letter in the word?\n")
for j in range(0,len(word)):
if inp == word[j]:
print("Yes, we have this letter.")
else:
print("No, we don't have this letter.")
i=i+1
The expected output would be one sentence, either confirming that the letter is present in word, or disproving. However, the actual output is that is prints one sentence per each of letters in the given word, like this:
What's your guess for a letter in the word?
p
Yes, we have this letter.
No, we don't have this letter.
Instead of checking against each letter of the word (and thereby printing it each time), just check whether the letter is in the word:
while i<5:
inp = input("What's your guess for a letter in the word?\n")
if inp in word:
print("Yes, we have this letter.")
You can try regular expression:
import random
import re
i=0
WORDS= ("notebook","pc", "footprint")
word = random.choice(WORDS)
print(len(word))
while i<5:
inp = input("What's your guess for a letter in the word?\n")
res = re.findall(inp, word)
length = len(res)
if length == 0:
print("Your guess is wrong :( ")
else:
print(f"You guess is right :) ")
i +=1
here the output of regular expression is a list so you can do whatever you want with it, e.g. hangman game or ...
For an assignment, I need code that asks the user for a word and a letter. Then, it edits the word to not include the specific letter. It needs in include a "for i in range" statement. The code before works but doesn't use a for loop and uses a python command.
word1 = raw_input ("Give me a word! ")
letter1 = raw_input ("Give me a letter! ")
modify = word1.replace(letter1,"")
check = word1.find(letter1)
if check == -1:
print "There is no letters to replace in", word1
check = 0
if check >= 1:
print modify
How about:
word = raw_input('Give me a word! ')
letter = raw_input('Give me a letter! ')
cleaned = ''
for i in range(len(word)):
if word[i] != letter:
cleaned += word[i]
if cleaned:
print cleaned
else:
print 'There is no letters to replace in', word
You can iterate through a string letter by letter like you would a list or dict
word='someword'
for letter in word:
print(letter)
I am trying to use python to write a function that checks whether the first letter of a given word, for instance "ball" is a vowel in either uppercase or lowercase. So for instance:
#here is a variable containing a word:
my_word = "Acrobat"
#letters in vowel as a list
the_vowel = ["a","e","i","o","u"]
How do a check that the first letter in "Acrobat" is one of the vowels in the list? I also need to take into consideration whether it is upper or lowercase?
try my_word[0].lower() in the_vowel
I don't know if it is better than the answers already posted here, but you could also do:
vowels = ('a','e','i','o','u','A','E','I','O','U')
myWord.startswith(vowels)
Here are some hints to help you figure it out.
To get a single letter from a string subscript the string.
>>> 'abcd'[2]
'c'
Note that the first character is character zero, the second character is character one, and so forth.
The next thing to note is that an upper case letter does not compare equal to a lower case letter:
>>> 'a' == 'A'
False
Luckily, python strings have the methods upper and lower to change the case of a string:
>>> 'abc'.upper()
'ABC'
>>> 'a' == 'A'.lower()
True
To test for membership in a list us in:
>>> 3 in [1, 2, 3]
True
>>> 8 in [1, 2, 3]
False
So in order to solve your problem, tie together subscripting to get a single letter, upper/lower to adjust case, and testing for membership using in.
my_word = "Acrobat"
the_vowel = "aeiou"
if myword[0].lower() in the_vowel:
print('1st letter is a vowel')
else:
print('Not vowel')
My code looks like this.
original = raw_input("Enter a word:")
word = original.lower()
first = word[0]
vowel = "aeiou"
if len(original) > 0 and original.isalpha():
if first in vowel:
print word
print first
print "vowel!"
else:
print word
print first
print "consonant
x = (input ("Enter any word: "))
vowel = "aeiouAEIOU"
if x[0] in vowel:
print ("1st letter is vowel: ",x)
else:
print ("1st letter is consonant: ",x)
Here's how I did it since the inputted word needs to be checked first before storing it as a variable:
original = raw_input('Enter a word:')
if len(original) > 0 and original.isalpha():
word = original.lower()
first = word[0]
if first in ['a','e','i','o','u']:
print "vowel"
else:
print "consonant"
else:
print 'empty'
changes:
if my_word[0] in ('a','e','i','o','u'):
print(' Yes, the first letter is vowel ')
else:
print(' No, the first letter is not vowel ')
So, Here is the simple code for finding out that the first letter is either vowel or not!! If you have any further query in python or js, then comment it down.
import ast,sys
input_str = sys.stdin.read()
if input_str[0] in ['a','e','i','o','u','A','E','I','O','U']:
print('YES')
else:
print('NO')
Here is the solution to the exercise on codecadmy.com:
original = raw_input('Enter a word:')
word = original.lower()
first = word[0]
vowel = "aeiou"
if len(original) > 0 and original.isalpha():
if first in vowel:
print 'vowel'
else:
print 'consonant'
else:
print 'empty'
Will it not be (slightly) faster to define the_vowel as a dictionary than a list?
the_vowel = {"a":1,"e":1,"i":1,"o":1,"u":1}
my_word[0].lower() in the_vowel
anti vowel Function
def anti_vowel(text):
vowel = ["a","e","i","o","u"]
new_text = ''
for char in text:
if char.lower() in vowel:
continue
else:
new_text += char
print new_text
return new_text
x = raw_input("Enter a word: ")
vowels=['a','e','i','o','u']
for vowel in vowels:
if vowel in x:
print "Vowels"
else:
print "No vowels"
This would print out 5 lines, if any of those includes a line that says Vowels then that means there is a vowel. I know this isn't the best way but it works.
Let's do it in more simply way
def check_vowel(s1):
v=['a','e','i','o','u']
for i in v:
if s1[0].lower()==i:
return (f'{s1} start with Vowel word {i}')
else:
return (f" {s1} start with Consonants word {s1[0]}")
print(check_vowel("orange"))
inp = input('Enter a name to check if it starts with vowel : ') *# Here we ask for a word*
vowel = ['A','E','I','O','U', 'a','e','i','o','u'] *# This is the list of all vowels*
if inp[0] in vowel:
print('YES') *# Here with the if statement we check if the first alphabet is a vowel (alphabet from the list vowel)*
else:
print('NO') *# Here we get the response as NO if the first alphabet is not a vowel*
my_word = "Acrobat"
the_vowel = ["a", "e", "i", "o", "u"]
if my_word[0].lower() in the_vowel:
print(my_word + " starts with a vowel")
else:
print(my_word + " doesnt start with a vowel")
input_str="aeroplane"
if input_str[0].lower() in ['a','e','i','o','u']:
print('YES')
else:
print('NO')
Output will be YES as the input string starts with a here.