Python - Dictionary help, checking if a char is in a dictionary object - python

I have a dictionary object;
secret = {"word" : secretWord}
secretWord being an argument for a string with a single word inside. I also have a string generating an asterisk (*) for every character in the secretWord. In my code I have input from the user which gives a letter.
What I wish to accomplish is to check within the dictionary object secretWord, and if so, replace any asterisk with the input where relevant. However I am not sure how to then save this as a new argument, and then use the next input on the new argument.
Sorry if my question/problem isn't clear, as I am struggling how to word it.
What I want to happen:
for example the secretWord could be 'PRECEDENCE'
>>>
WORD : **********
Guess a letter: e
**E*E*E**E
Guess a letter: p
P*E*E*E**E
etc
What happens:
>>>
WORD : **********
Guess a letter: e
**E*E*E**E
Guess a letter: p
P*********
etc
My current Code:
import random
import sys
def diction(secretWord, lives):
global guess
global secret
secret = {"word" : secretWord, "lives" : lives}
guess = len(secret["word"]) * "*"
print (secret["word"])
print ("WORD: ", guess)
fileName = input("Please insert file name: ")
def wordGuessed(guess, secret):
if guess == secret["word"]:
print ("word is guessed")
if guess != secret["word"]:
print ("word is not guessed")
def livesLeft(inpu):
if inpu not in secret["word"]:
secret["lives"] = secret["lives"] - 1
print("Lives left: ", secret["lives"])
if inpu in secret["word"]:
print("Correct guess")
print(secret["lives"])
def guessCheck(inpu):
for char in secret["word"].lstrip():
if char == inpu:
print (char, end= "")
elif char != secret["word"]:
print ("*", end="")
try:
f = open(fileName)
content = f.readlines()
except IOError as e :
f = None
print("Failed to open", fileName, "- program aborted")
sys.exit()
Run = True
while Run == True:
levelIn = input("Enter difficulty (easy, intermediate or hard): ").lower()
if levelIn == ("easy"):
lives = 10
elif levelIn == ("intermediate"):
lives = 8
elif levelIn == ("hard"):
lives = 5
else:
print("Please input a valid difficulty.")
break
secretWord = (random.choice(content))
secretWord = secretWord.replace("\n", "")
diction(secretWord, lives)
wordGuessed(guess, secret)
while secret["lives"] > 0:
inpu = input("Guess a letter: ").upper()
livesLeft(inpu)
guessCheck(inpu)
if secret["lives"] == 0:
print ("You have no lives left – you have been hung!")
print ("The word was,", secret["word"])

You need to track the guesses made so far, and use those to display the word. Use a set to track what the player already guessed at:
guessed = set()
So that you can do:
if inpu in guessed:
print('You already tried that letter!')
else:
guessed.add(inpu)
whenever a user makes a guess.
You can then use that set to display the word revealed so far:
for char in secret["word"].lstrip():
if char in guessed:
print (char, end="")
else:
print ("*", end="")

Related

Infinite loop not checking for string size and belonging to alphabet

I've been trying to make a check for if the input (guesses) belongs to the alphabet and if it's a single character for my simple hangman game, but when I try to run the program it just ignores the entire if sentence. It's been working everywhere else and I just can't find the source of the problem.
Here is my code:
def eng():
letter_list = []
global word
global letter
g = 0
lives = 10
while True:
word = input("Insert The Word: ")
if not word.isalpha():
print("Only letters of the English alphabet are allowed")
else:
print(letter)
break
cls = lambda: print('\n' * 256)
cls()
ready_letters = list(set(word.lower()))
while True:
q = len(ready_letters)
print(q)
while True:
letter = input("Your guess: ")
if not letter.isalpha() and len(letter) != 1:
print("You can make a guess with only one letter of the English alphabet")
else:
break
print(letter_list)
if letter in ready_letters and letter not in letter_list:
letter_list += letter
print("Nice")
g += 1
if g == q:
print(f"The word was: {word}")
print("GG, 🎉🎊")
print("\n")
return
print(f"{g}/{q} letters guessed correctly!")
elif letter in letter_list:
print("You already wrote this letter, try again")
else:
letter_list += letter
print("Oh noie")
lives -= 1
print(f"You have {lives} lives left")
if lives == 0:
print("GG, 웃💀")
return
(read comment)
General tips not related to the issue would also be appreciated.
Thanks for your time!
Simple mistake, instead of using and you should be using or. You want to print our your error message if they type a non-alpha character OR they type more than one letter.

Python Hangman not ending when player guesses all letters

My problem is that when I run the program and get all the letters correct, it does not move on from there and I'm in an infinite loop. I expect it to say "Good Job!" and end the program when the player gets the word right. I am very new to coding, and would greatly appreciate any help.
import random
import time
name = input("What is your name? ")
print(name + ", ay?")
time.sleep(1)
start = input("Up for a game of Hangman?(y/n) ")
lis = random.choice(["yet"])
dash = []
while len(dash) != len(lis):
dash.append("_")
guess = []
guesscomb = "".join(guess)
wrongcount=int(0)
alphabet = "abcdefghijklmnopqrstuvwxyz"
if start == "y":
print("One game of Hangman comin' right up,",name)
letter = input("Alright then, Guess a letter: ")
thing = ''.join(dash)
while guesscomb != thing:
if letter == "" or letter == " " or len(letter) != 1:
print("I don't understand. Please only use singular letters.")
letter = input("Guess a letter: ")
elif letter in lis and letter in alphabet:
print("Nice!")
location = lis.find(letter)
dash[location] = letter
guess.append(letter)
alphabet.replace(letter," ")
guesscomb = "".join(guess)
letter = input("Guess a letter: ")
else:
print("Wrong.")
wrongcount = wrongcount + 1
print("Total Mistakes:",wrongcount)
letter = input("Guess a letter: ")
elif start == "n":
input("Shame.")
quit()
print("Good Job!")
time.sleep(10)
The thing variable is equal to ___ while lis is always equal to "yet".
guesscomb cannot be equal to thing as you validate a letter when the guess is equal to a letter in lis
You can use print with the parameter end="" so that the cursor don't go new line.
You can use the method isalpha on string to check if it is all characters instead of comparing it with the alphabets.
And as Ben said, thing is always ___
Modify this part of your code, and it will work
if start == "y":
print("One game of Hangman comin' right up,", name)
print("Alright then, ", end="")
# letter = input("Alright then, Guess a letter: ")
thing = ''.join(dash)
while guesscomb != thing:
letter = input("Guess a letter: ")
if letter == "" or letter == " " or len(letter) != 1:
print("I don't understand. Please only use singular letters.")
elif letter in lis and letter in alphabet:
print("Nice!")
location = lis.find(letter)
dash[location] = letter
guess.append(letter)
alphabet.replace(letter, " ")
guesscomb = "".join(guess)
else:
print("Wrong.")
wrongcount = wrongcount + 1
print("Total Mistakes:", wrongcount)
thing = ''.join(dash)

How to get python to recognize the next occurrence of letter in hangman

My hangman program is fully functioning except there is one problem, let's say the word is mathematics, I guess m, a, t, h, e - but once I guess the other m, it says I guessed it (as opposed to saying "You already guessed this letter") but it doesn't replace the _.
My Code:
def start():
import random
words = ["barbershop", "cuddle", "furious", "demolition", "centaur", "forest", "pineapple", "mathematics", "turkish"]
word = random.choice(words);
hiddenword = len(word) * "-"
used_letters = []
lives = 6
print "Welcome to Hangman! You have 6 guesses, good luck!"
while True:
print word
print "".join(hiddenword)
guess = raw_input("> ")
hiddenword = list(hiddenword)
if len(guess) > 1:
print "Error: 1 Letter Maximum"
elif len(guess) < 1:
guess = raw_input("> ")
else:
if guess.isdigit() == True:
print "Error: Hangman only accepts letters."
else:
if guess in used_letters and word.count(guess) == 1:
print "You already guessed that letter"
else:
if guess.lower() in word:
print "You got the letter " + "'" + guess + "'" + "!"
hiddenword[word.index(guess)] = guess
used_letters.append(guess)
else:
lives -= 1
print "-1 Guesses"
print "Guesses:", lives
used_letters.append(guess)
if lives == 0:
print "GAME OVER: You're out of guesses, try again!"
break
if hiddenword == word:
print "Cangratulations, you got the word!"
break
start()
P.S. - I know I have a lot of excess code e.g. if statements, please do not comment on that.
The problem appears to be with the line:
hiddenword[word.index(guess)] = guess
The string method .index(x) returns the index of the first incidence of x. So this line will persistently fill in the first "m" in mathematics.
Assuming you want the game to reveal all instances of a letter when it is guessed (e.g., show both m's in "mathematics" when you guess "m"), you can substitute this:
for i, x in enumerate(word):
if word[i] == guess:
hiddenword[i] = guess
for your line:
hiddenword[word.index(guess)] = guess
Also, to get the "Congratulations!" message to appear, you will need to change if hiddenword == word to if ''.join(hiddenword) == word, since hiddenword is a list at this point.
Removing multiple occurences of a character in a string in python is easily achieved using:
your_string.replace("m", "");
http://www.tutorialspoint.com/python/string_replace.htm

HANGMAN assignment python

For an assignment I need to write a basic HANGMAN game. It all works except this part of it...
The game is supposed to print one of these an underscore ("_") for every letter that there is in the mystery word; and then as the user guesses (correct) letters, they will be put in.
E.G
Assuming the word was "word"
User guesses "W"
W _ _ _
User guesses "D"
W _ _ D
However, in many cases some underscores will go missing once the user has made a few guesses so it will end up looking like:
W _ D
instead of:
W _ _ D
I can't work out which part of my code is making this happen. Any help would be appreciated! Cheers!
Here is my code:
import random
choice = None
list = ["HANGMAN", "ASSIGNEMENT", "PYTHON", "SCHOOL", "PROGRAMMING", "CODING", "CHALLENGE"]
while choice != "0":
print('''
******************
Welcome to Hangman
******************
Please select a menu option:
0 - Exit
1 - Enter a new list of words
2 - Play Game
''')
choice= input("Enter you choice: ")
if choice == "0":
print("Exiting the program...")
elif choice =="1":
list = []
x = 0
while x != 5:
word = str(input("Enter a new word to put in the list: "))
list.append(word)
word = word.upper()
x += 1
elif choice == "2":
word = random.choice(list)
word = word.upper()
hidden_word = " _ " * len(word)
lives = 6
guessed = []
while lives != 0 and hidden_word != word:
print("\n******************************")
print("The word is")
print(hidden_word)
print("\nThere are", len(word), "letters in this word")
print("So far the letters you have guessed are: ")
print(' '.join(guessed))
print("\n You have", lives,"lives remaining")
guess = input("\n Guess a letter: \n")
guess = guess.upper()
if len(guess) > 1:
guess = input("\n You can only guess one letter at a time!\n Try again: ")
guess = guess.upper()
while guess in guessed:
print("\n You have already guessed that letter!")
guess = input("\n Please take another guess: ")
guess = guess.upper()
guessed.append(guess)
if guess in word:
print("*******************************")
print("Well done!", guess.upper(),"is in the word")
word_so_far = ""
for i in range (len(word)):
if guess == str(word[i]):
word_so_far += guess
else:
word_so_far += hidden_word[i]
hidden_word = word_so_far
else:
print("************************")
print("Sorry, but", guess, "is not in the word")
lives -= 1
if lives == 0:
print("GAME OVER! You ahve no lives left")
else:
print("\n CONGRATULATIONS! You have guessed the word")
print("The word was", word)
print("\nThank you for playing Hangman")
else:
choice = input("\n That is not a valid option! Please try again!\n Choice: ")
You have hidden_word = " _ " * len(word)
This means that at start for a two letter word, you have [space][underscore][space][space][underscore][space].
When you then do word_so_far += hidden_word[i], for i = 0, you will append a space, not an underscore.
The quickest fix would seem to be:
Set hidden_word to just be _'s (hidden_word = " _ " * len(word))
When you print out the word, do
hidden_word.replace("_"," _ ") to add the spaces around the underscores back
#Foon has showed you the problem with your solution.
If you can divide your code up into small functional blocks, it makes it easier to concentrate on that one task and it makes it easier to test. When you are having a problem with a specific task it helps to isolate the problem by making it into a function.
Something like this.
word = '12345'
guesses = ['1', '5', '9', '0']
def hidden_word(word, guesses):
hidden = ''
for character in word:
hidden += character if character in guesses else ' _ '
return hidden
print(hidden_word(word, guesses))
guesses.append('3')
print(hidden_word(word, guesses))
Below code solves the problem.you can do some modifications based on your requirement.If the Guessed letter exists in the word.Then the letter will be added to the display variable.If not you can give a warning .But note that it might tempt you to write ELSE statement inside the for loop(condition:if guess not in word).If you do like that then the object inside the Else statement will be repeated untill the For loop stops.so that's why it's better to use a separete IF statement outside the for loop.
word="banana"
display=[]
for i in word:
display+="_"
print(display)
while True:
Guess=input("Enter the letter:")
for position in range(len(word)):
if Guess==word[position]:
display[position]=word[position]
print(display)
if Guess not in word:
print("letter Doesn't exist")

Python: Hangman game problems

I am brand new to Python but a have a littel Matlab and C++ background. Please Help!!!!
I am having problems with my hangman code. If a word has multiple of the same letter in I cannot figure out how to get it to switch all of them. I have a couple tries with some of them commented out.
import random
import time
import sys
def pickWord():
words = [line.strip() for line in open('word_list.txt')]
word = random.choice(words)
word = word.lower()
return word
def checkLetter(word, input):
if input not in word:
in_letter = 0
else:
in_letter = 1
return in_letter
def check_input(input):
if input.isaplha() == False :
input = raw_input('Your input was not a letter, please enter a letter: ')
elif len(input) > 0:
input = raw_input('Your entry was longer than 1 letter, please enter one letter: ')
else:
input = input
return input
#main function
running = 'y'
print('Lets Play Hangman!\n\n ------------------------ \n\nGenerating a Random word \n\n')
while running == 'y':
word = pickWord()
letters = list(word)
time.sleep(3)
print ('The word has been chosen\n\n')
print '%s' % word
start = raw_input('Are you ready to start?(y/n)')
start = start.lower()
if start == 'n':
print('Well, too damn bad. Here We go!\n\n **************************\n\n')
elif start == 'y':
print('Awesome, lets begin!\n\n*********************************\n\n')
else:
print('You did not enter y or n, sorry you are not allowed to play!')
sys.exit()
i = 0
print ('The word has %d letters in it') % len(word)
input = raw_input('What is your first guess: ')
input = input.lower()
correct = ['_'] * len(word)
print ' '.join(correct)
while correct != letters and i <= 5:
'''if input in letters:
for input in letters:
location = letters.index(input)
correct[location] = input
print('You guessed the correct letter! Your input %s is in the word at the %d spot.') % (input, location)
print ' '.join(correct)
elif input not in letters:
print('You guessed wrong :(')
i = i + 1
guesses = 6 - i
print('You have %d guesses left.') % guesses
guesses = 0
else:
print('You did not enter a valid letter, please try again.')'''
'''for j in letters:
if j == input:
location = letters.index(j)
correct[location] = j
print '%s' % ' '.join(correct)
print '%d' % location
print '%s' % j
if j == input:
location = letters.index(j)
correct[location] = j
print('You guessed the correct letter! Your input %s is in the word at the %d spot.') % (input, location)
print ' '.join(correct)'''
if input not in letters:
i = i + 1
guesses = 6 - i
print("You guessed incorrectly. You have %d guesses left.") % guesses
input = raw_input('What is your next guess: ')
input = input.lower()
if correct == letters:
print('Congrats! You won the game!')
else:
print('You lost. :(')
running = raw_input('Do you want to play again? (y/n)').lower()
In your attempt, the loop is stopping when it finds the first match of input to letters.
the following code will work:
guess = raw_input('What is your first guess: ')
word = "wordword"
letters = list(word)
correct = ['_']* len(word)
for x, y in enumerate(word):
if guess == y:
correct[x] = y
Your mistakes
In your first attempt:
if input in letters:
for input in letters:
you are checking if input is in letters, which is fine, but if this returns True, inputs original value is lost, and is reassigned as you loop through the elements of letters.
eg
>>>input = "w"
>>>word = "word"
>>>if input in word:
... for input in word:
... print(input)
w
o
r
d
your second attempt
for j in letters:
if j == input:
location = letters.index(j)
is a lot closer to being successful, however location = letters.index(j) is always going to equal the index of the first match of j, and thus will not assign all matched values of input.

Categories

Resources