Implementing a game of guessing words in Python - python

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 ...

Related

How do you insert repeated values with distinct indices into an empty list in python?

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

Editing a String without Python Commands (with "for i in range")

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)

How to count the number of times a specific character appears in a list?

Okay so here is a list:
sentList = ['I am a dog', 'I am a cat', 'I am a house full of cards']
I want to be able to count the total number of times a user inputted letter appears throughout the entire list.
userLetter = input('Enter a letter: ')
Let's say the letter is 'a'
I want the program to go through and count the number of times 'a' appears in the list.
In this case, the total number of 'a' in the list should be 8.
I've tried using the count function through a for loop but I keep getting numbers that I don't know how to explain, and without really knowing how to format the loop, or if I need it at all.
I tried this, but it doesn't work.
count = sentList.count(userLetter)
Any help would be appreciated, I couldn't find any documentation for counting all occurrences of a letter in a list.
Use the sum() builtin to add up the counts for each string in the list:
total = sum(s.count(userLetter) for s in sentList)
Merge all the strings into a single string and then use the count function.
count = ''.join(sentList).count(userLetter)
Have you tried something like this?
userLetter = input('Enter a letter: ')
sentList = ['I am a dog', 'I am a cat', 'I am a house full of cards']
letterCount = 0
for sentence in sentList:
letterCount += sentence.count(userLetter)
print("Letter appears {} times".format(letterCount))
Your approach is halfway correct. The problem is that you need to go through the list.
word_count=0
for l in sentList:
word_count+= l.count(userLetter)
word_list = ["aardvark", "baboon", "camel"]
import random
chosen_word = random.choice(word_list)
guess = input("Guess a letter: ").lower()
for letter in chosen_word:
if letter == guess:
print("Right")
else:
print("Wrong")
example program to check if entered letter is present in random choice of word
word_list = ["aardvark", "baboon", "camel"]
import random
chosen_word = random.choice(word_list)
guess = input("Guess a letter: ").lower()
for letter in chosen_word:
if letter == guess:
print("Right")
else:
print("Wrong")

Hangman Game - Duplicate characters issue in lists

I've been making a hangman game and ran into a problem with the lists. If the user input matches any of the characters in the list, the letter's place in said list is found and then added to that position in a blank list. However, words such as "television" that contain duplicate characters don't work. Instead, it will print "tel_vis_on". Sorry if this is a vague post, I don't know the terminology.
def guess():
letter = input ("Please enter a letter:")
if letter in word:
print ("Correct!")
letterPlace = word.index(letter)
answer[letterPlace] = letter
print (*answer)
else:
print ("Wrong!")
if answer == word :
print ("You guessed it! Well Done!")
#end here
else:
guess()
from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()
In that part:
if letter in word:
print ("Correct!")
letterPlace = word.index(letter)
answer[letterPlace] = letter
word.index(letter) will return the index of the first occurrence of the letter.
So you'll replace only the first underscore by the letter. Do that instead:
if letter in word:
print ("Correct!")
for letterPlace in (idx for idx,l in enumerate(word) if l==letter):
answer[letterPlace] = letter
the code loops and if it finds the letter, the generator expression yields the index, to replace the underscore.
you can try this if you want. pretty easy to understand if you don't want anything too complicated:
def findOccurences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
def guess():
letter = input ("Please enter a letter:")
if letter in word:
print ("Correct!")
letterPlace = findOccurences(word,letter)
for i in letterPlace:
answer[i] = letter
print (*answer)
else:
print ("Wrong!")
if answer == word :
print ("You guessed it! Well Done!")
#end here
else:
guess()
from random import choice
objects = ["computer","television"]
word = choice(objects)
word = (list(word))
wordcount = len(word)
answer = ["_"]*wordcount
print (*answer)
guess()
Nice game by the way.
The issue here is that you are replacing only the first occurrence of the letter. In order to replace all occurances, use the re function like this:
def guess():
letter = input ("Please enter a letter:")
if letter in word:
print ("Correct!")
letterPlace = [m.start() for m in re.finditer(letter, word)]
for index in letterPlace:
answer[index] = letter

Hangman in python 3.x, finding the position of a letter in secret word

print("Welcome to Hangman! Guess the mystery word with less than 6 mistakes!")
words= ['utopian','fairy','tree','monday','blue']
i=int(input("Please enter a number (0<=number<10) to choose the word in the list: "))
if(words[i]):
print("The length of the word is: " , len(words[i]))
guesses=0
while guesses<6:
guess=input("Please enter the letter you guess: ")
if(guess in words[i]):
print("The letter is in the word.")
else:
print("The letter is not in the word.")
guesses=guesses+1
if guesses==6:
print("Failure. The word was:" , words[i])
Having problems with finding the position of the guessed letter in mystery word. I want a output that shows the correctly guessed letters in the mystery word.
Ex. Mystery word is blue. User inputs "b". Output is: "The letter is in the word. Letters matched: b___"
There's many ways to write this, how about if you put all guessed letters in the string called guessed and then compute
''.join(c if c in guessed else '_' for c in words[i])
c will be iterating over the characters of words[i], the word to guess.
The c if c in guessed else '_' bit replaces all characters that have not yet been guessed with underscores.
''.join() will glue the characters back together into a string.
I think you're looking for something like this:
word = []
for x in range(len(words[i])):
word.append('_')
if(guess in words[i]):
print("The letter is in the word.")
for index, letter in enumerate(words[i]):
if letter == guess:
word[index] = guess
A full program looking like:
print("Welcome to Hangman! Guess the mystery word with less than 6 mistakes!")
words= ['utopian','fairy','tree','monday','blue']
i=int(input("Please enter a number (0<=number<10) to choose the word in the list: "))
if(words[i]):
print("The length of the word is: " , len(words[i]))
guesses=0
letters_guessed = []
word = []
for x in range(len(words[i])):
word.append('_')
while guesses < 6:
guess=input("Please enter the letter you guess: ")
if(guess in words[i]):
print("The letter is in the word.")
for index, letter in enumerate(words[i]):
if letter == guess:
word[index] = guess
letters_guessed.append(guess)
else:
print("The letter is not in the word.")
guesses=guesses+1
letters_guessed.append(guess)
print("you have guessed these letters: %s"%(''.join(letters_guessed)))
print("Letters matched so far %s"%''.join(word))
print()
if ''.join(word) == words[i]:
break
if guesses==6:
print("Failure. The word was:" , words[i])
else:
print("YOU'VE WON!! Great Job!")
print("You only made %i wrong guesses"%guesses)
which outputs:
> Welcome to Hangman! Guess the mystery word with less than 6 mistakes!
> Please enter a number (0<=number<10) to choose the word in the list: 2
> The length of the word is: 4
> Please enter the letter you guess: e
> The letter is in the word.
> you have guessed these letters: e
> Letters matched so far __ee
The code above works, but having only 5 items in the list of words to choose you can have an error if you input a number higher than 5, so I put some other words in the list, but I also deleted the lines with the input function where the user is asked to digit the number of the item related to the word to discover.
So:
I imported the random module.
I deleted the input code.
I used the random.sample function to store the word to discover (line 12).
I substituted words[i] with samplecode[0] as label for the word to discover.
I added a space after the underscore in word.append('_ ') to make the number of the letters more evident ( _ _ _ _ _ instead of _____ ).
import random
print("Welcome to Hangman! Guess the word in less than 6 try.")
words= ['utopian','fairy','tree','monday','blue',
'winner','chosen','magician','european',
'basilar','fonsaken','butter','butterfly',
'flipper','seaside','meaning','gorgeous',
'thunder','keyboard','pilgrim','housewife'
]
sampleword = random.sample(words,1)
if(sampleword[0]):
print("The length of the word is: " , len(sampleword[0]))
guesses=0
letters_guessed = []
word = []
for x in range(len(sampleword[0])):
word.append('_ ')
while guesses < 6:
guess=input("Please enter the letter you guess: ")
if(guess in sampleword[0]):
print("The letter is in the word.")
for index, letter in enumerate(sampleword[0]):
if letter == guess:
word[index] = guess
letters_guessed.append(guess)
else:
print("The letter is not in the word.")
guesses=guesses+1
letters_guessed.append(guess)
print("you have guessed these letters: %s"%(''.join(letters_guessed)))
print("Letters matched so far %s"%''.join(word))
print()
if ''.join(word) == sampleword[0]:
break
if guesses==6:
print("Failure. The word was:" , sampleword[0])
else:
print("YOU'VE WON!! Great Job!")
print("You only made %i wrong guesses"%guesses)

Categories