What's wrong with this string equality comparison? (Python) - python

My code is for a simple hangman type game where the user is supposed to guess the a random word from a list letter by letter or guess the whole word. The comparison for when the user guesses the whole word doesn't execute. I hardcoded one of the possible random words into my code below as an example:
guess = "----"
letterCount = 8
letter = ""
x = 0
while letterCount > 0:
temp1 = "word"
letter = input("Guess a letter in the word or attempt to guess the whole word: ")
if (len(letter) > 1):
print ("this is the test word: word, this is letter:" + letter)
if letter == "word":
print ("You win!!!")
letterCount = 0
else:
x = temp1.find(letter)
while x != -1:
x = temp1.find(letter)
temp1 = temp1[:(x + 1)].replace(letter, '0') + temp1[(x + 1):]
guess = guess[:(x + 1)].replace('-', letter) + guess[(x + 1):]
print (("Your guess is now: " + guess))
letterCount = letterCount - 1
x = 0
If I guess the "word", it tells me that I guess word, it points out that I guess the word I should, but the if statement that should tell me I won never executes. Am I comparing these strings properly or is the problem something else?

>>> while letterCount > 0:
... temp1 = "word"
... letter = input("Guess a letter in the word or attempt to guess the whole word: ")
... if (len(letter) > 1):
... print ("this is the test word: word, this is letter:" + letter)
... if letter == "word":
... print ("You win!!!")
... letterCount = 0
... else:
... x = temp1.find(letter)
... while x != -1:
... x = temp1.find(letter)
... temp1 = temp1[:(x + 1)].replace(letter, '0') + temp1[(x + 1):]
... guess = guess[:(x + 1)].replace('-', letter) + guess[(x + 1):]
... print (("Your guess is now: " + guess))
... letterCount = letterCount - 1
... x = 0
...
Guess a letter in the word or attempt to guess the whole word: "word"
this is the test word: word, this is letter:word
You win!!!
>>>
You need to cast your input as a String for the String comparison test to work.

Related

How to solve this for loop error?. I tried to add a letter in order, in each cycle

I tried to make a simple version of the hangman game. But when I run it, I can't add the letters in order.
The 'count' variable may be the problem. Any can help me ?
Thank you! :)
word = 'houses'# <--just for testing
word = list(word)
print(word)
p2 = ' __ ' * len(word)
p2 = p2.split()
print(p2)
lives = len(word)
print("lives: ", lives)
count = 0
while word != p2:
letter = input("enter a letter: ")
if letter in word:
for x in word:
if x == letter:
p2[count] = letter
#print("cont: ", count)
else:
continue
count+=1
print("p2: ",p2)
else:
lives -= 1
print("You have {} lives left".format(lives))
if lives == 0:
break
Well i wasn't able to understand your point of view about the Hangman but following code is the optimized form of your code and also the my playing interpretation of this game e.g. how this should be played
word = 'houses'# <--just for testing
word = list(word)
print(word)
p2 = ' __ ' * len(word)
p2 = p2.split()
print(p2)
lives = len(word)
print("lives: ", lives)
while word != p2:
letter = input("enter a letter: ")
if letter in word and letter not in p2:
locations = [i for i, x in enumerate(word) if x == letter ]
for location in locations:
p2[location] = letter
print("p2: ",p2)
else:
lives -= 1
print("You have {} lives left".format(lives))
if lives == 0:
break
print('You LOST' if lives == 0 else 'You WON')
Screenshot of the Both Executions of the game (Win & Loss)

Generating a New Random Word After a Condition is Met

I am trying to create a Lingo game in Python where the user has 2 minutes to guess as many correct 5 letter words as possible. I use the random class and a text file to generate a random 5 letter word. However, after the user correctly guesses the word, I do not know how to generate a new 5 letter word. I am thinking I generate it inside the while loop for the timer, but I am not sure. I am still learning about python and this is my first time writing a "game" program. Any ideas or suggestions?
import random
from collections import Counter
import time
file = "words.txt" #File with 5 letter words
f = open(file, 'r')
lines = f.readlines()
randomword = random.choice(lines) #generate random 5 letter word from file
numletters = Counter(randomword)
word = [randomword[0], '_', '_', '_', '_']#part of word that is being shown to user
score = 0 #user score
print(randomword[0])
#print(randomword)
timer = 120 #amount of time game runs for
start_time = time.time() #remember when game started
while(time.time() - start_time < timer): #2 minutes is given to guess as many 5 letter words as possible
for i in range(1,6): #take 5 guesses at what random word is
guess = input("Guess the word: ")
for j in range(1,5): #check to see if other 4 letters of random word match the letters in the user guess word
numguess = Counter(guess)
if(guess[j] == randomword[j] and word[j] == '_'): #replace empty character with letter of random word if correctly guessed
word[j] = randomword[j]
elif(guess[j] in randomword and word[j] == '_'): #replace empty character with uppercase letter of guessed letter if that letter is in the randomword
word[j] = guess[j].upper()
elif(guess[j] in randomword and numguess[guess[j]] > numletters[guess[j]] and word[j] == '_'): #guessed letter gets replaced with '_' if max number of that letter is already in word
word[j] = '_'
elif(guess[j] == randomword[j] and word[j] != '_'): #replace uppercase letter with correctly guessed letter in word
word[j] = randomword[j]
elif(guess[j] == randomword[j] and guess[j].upper() in word): #upper case letter is guessed in correct spot, but no other letters are correcty guessed
word[word.index(word[j].upper())] = '_'
else: #no correct letters are guessed
word[j] = '_'
answer = word[0] + ' ' + word[1] + ' ' + word[2] + ' ' + word[3] + ' ' + word[4]
print(answer)
if(answer == randomword[0] + ' ' + randomword[1] + ' ' + randomword[2] + ' ' + randomword[3] + ' ' + randomword[4]):
print("You are correct!")
score += 100 #user scores 100 points for each correctly guessed word
break
if(answer != randomword[0] + ' ' + randomword[1] + ' ' + randomword[2] + ' ' + randomword[3] + ' ' + randomword[4]):
print("You are incorrect! You get 0 points for this word")
print("The correct word is: " + randomword.strip())
print("Your final score is " + str(score)) #print final score
enter this code into python. it uses an if statement to re-create the same variable with random.randint
import random
condition = True #saying the condition is true
randomthing = random.randint(1,10) # selecting a random number
print(randomthing, "is the first digit") #printing out the first randomly generated digit
if condition == True:
randomthing = random.randint(1,10)# regenerating the number
print(randomthing, "is the second number. if it is the same re run it") # printing out the second generated number
let me know if i can do more help

Python 3 hangman for a beginner

print("Welcome to hangman. Are you ready to have some fun?")
def play():
import random
List = ["random", "words", "list"]
word = str(random.choice(List))
mistake = 7
alreadySaid = set()
board = "_" * len(word)
print(" ".join(board))
while mistake > 0:
while True:
guess = input("Please guess a letter: ")
if len(guess) <= 1:
break
else:
print("Too long. Enter only one letter.")
if guess in word:
alreadySaid.add(guess)
print("Correct!",guess, " was in the word!")
board = "".join([guess if guess in word else "_" for str in word])
if board == word:
print("Congratulations! You´re correct!!!")
elif guess not in word:
mistake -= 1
print("Wrong!", mistake," mistakes remaining.")
if mistake <= 0:
print("Game Over")
print(" ".join(board))
play()
I'm trying to make hangman with python 3 but whenever I input a correct letter it comes out as a word of only that letter. For example for random when I input r the output is r r r r r r when I want r _ _ _ _ _. What do you think is wrong? Also do I have any other problems?
Might I suggest you take a step back and try a different, cleaner approach? Besides that, I suggest you keep your hidden word as a list, since strings are immutable and do not support item assignment, which means you cannot reveal the character if the user's guess was correct (you can then join() it when you need it to display it to the user as a string):
import random
word_list = [
'spam',
'eggs',
'foo',
'bar'
]
word = random.choice(word_list)
guess = ['_'] * len(word)
chances = 7
while '_' in guess and chances > 0:
print(' '.join(guess))
char = input('Enter char: ')
if len(char) > 1:
print('Please enter only one char.')
continue
if char not in word:
chances -= 1
if chances == 0:
print('Game over!')
break
else:
print('You have', chances, 'chances left.')
else:
for i, x in enumerate(word):
if x == char:
guess[i] = char
else:
print(''.join(guess))
print('Congratulations!')

Python hangman replacing

So I'm writing a hangman program and I'm having trouble getting the current guesses to display as underscores with the correct letters guessed replacing an underscore. I can get the function to work once (thats the insert_letter function) and I know its just replacing every time it goes through the loop, but I can't return the new current without quitting the loop so if someone could offer another way to get the guesses to keep updating that would be great!
def insert_letter(letter, current, word):
current = "_" * len(word)
for i in range (len(word)):
if letter in word[i]:
current = current[:i] + letter + current[i+1:]
return current
def play_hangman(filename, incorrect):
words = read_words(filename)
secret_word = random.choice(words)
num_guess = 0
letters_guessed = set()
letter = input("Please enter a letter: ")
while num_guess < incorrect:
letter = input()
if letter in secret_word:
current = insert_letter(letter, current, secret_word)
print(current)
else:
num_guess += 1
current = "_" * len(secret_word)
print(current)
letters_guessed.add(letter)
You didn't show the code for your insert_letter() function so I wrote an alternative -- display_remaining(). Give this a try:
import random, sys
def play_hangman(filename, incorrect):
words = read_words(filename)
secret_word = random.choice(words)
num_guess = 0
letters_guessed = set()
while num_guess < incorrect:
letter = input("Please enter a letter: ")
letters_guessed.add(letter)
current = display_remaining(secret_word, letters_guessed)
print(current)
if not letter in secret_word:
print("Incorrect guess.")
num_guess += 1
if not '_' in current:
print("Congratulations! You've won!")
sys.exit(0)
print("Sorry. You've run out of guesses. Game over.")
def display_remaining(word, guessed):
replaced = word[:]
for letter in word:
if (not letter == '_') and letter not in guessed:
replaced = replaced.replace(letter, '_', 1)
return replaced
def read_words(filename):
with open(filename, 'rU') as f:
return [line.strip() for line in f]
if __name__ == '__main__':
play_hangman('words.txt', 6)
NOTE: With this implementation, your words file shouldn't have any words containing the underscore character.

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