Python hangman without lists - python

I need a simple Python Hangman program without using Lists - It is just one word
HAPPY - this program works - BUT...
This is what I did, with Lists - but teacher said Lists are not allowed
We do not have to draw hangman - we just prompt for the letters - print the "-" for each letter to show length of word.
def main():
secretword = "HAPPY"
displayword=[]
displayword.extend(secretword)
for I in range (len(displayword)):
displayword[I]="_"
print ('current word
')
print (' '.join(displayword))
count = 0
while count < len(secretword):
guess = input('Please guess a etter: ')
for I in range(len(secretword)):
if secretword[I] == guess:
displayword[I] = guess
countr - count + 1
print (' '.join(displayword))
print (congratulations you guess the word')
main()
If you don't like the code - that's fine. This is how our teacher is requiring us to do this. I can see it is not like others do it. I only left out the comments - that are also required on every line of code

One solution to your problem would be to use two strings, secretword, which is the word you're looking for and displayword which is what the user sees so far, the combination of letters and -. Every time you enter a letter, the program checks if the secretword contains that letter and if it does, it updates the character of the specific index in displayword:
def main():
secretword = "HAPPY"
length = len(secretword)
displayword = '-' * length
count = 0
while count < length:
guess = input("Please guess a letter: ")
for i in range(length):
if secretword[i] == guess:
displayword[i] = guess
count += 1
print(displayword)
print("Congratulations, you guessed the word.")
main()

Related

Looping over characters (and their indices) in Python [duplicate]

So I'm making a hanging man game and I have run into a problem regarding indexes. Basically, I want to find the index of a letter inside a secret word, the problem is that if the secret word includes two letters that are the same, for instance, "guacamole", where the letter a has the index of 2 and 4 but when I want to find the index of a, it only prints "2" and not "4". Is there a way around this? Thanks in advance!
Part of code where problem occurs:
for letter in secret_word:
if user_guess == letter:
current_word_index = secret_word.find(letter)
print(current_word_index) #Not in full program, only to test errors.
Full code:
#Hanging man
import string
space = "\v"
dbl_space = "\n"
secret_word = str(input("Enter a secret word: "))
guess_low = list(string.ascii_lowercase)
used_letters = []
user_errors = 0
user_errors_max = 1
secret_word_index = int(len(secret_word))
secret_word_placeholder = list(range(secret_word_index))
while user_errors != user_errors_max:
user_guess = str(input("Enter a letter: "))
if len(user_guess) != 1:
print("You have to pick one letter")
if user_guess in guess_low:
guess_low.remove(user_guess)
used_letters.extend(user_guess)
print(used_letters)
for letter in secret_word:
if user_guess == letter:
current_word_index = secret_word.find(letter)
if user_errors == user_errors_max:
print("You lost the game, the secret word was: " + secret_word)
This is an example of what you are trying to achieve. use list comprehension.
string='hello'
letter='l'
[idx for idx,ch in enumerate(string) if ch==letter]
Python's string find accepts a start parameter that tells it where to start searching:
>>> "guacamole".find('a')
2
>>> "guacamole".find('a', 3)
4
Use a loop, and use the index of the last hit you found + 1 as the start parameter for the next call.
Another more verbose solution might be:
str1 = "ooottat"
def find_all_indices(text, letter):
indices_of_letter = []
for i, ch in enumerate(text):
if ch == letter:
indices_of_letter.append(i)
return indices_of_letter
print(find_all_indices(str1, 'o'))
Side note:
Indexes is the nontechnical plural of index. the right technical plural for index is indices
Yes, if you instantiate a new_variable to be the secret_word variable before the for loop, the in the line current_word_index = secret_word.find(letter) change secret_word.find(letter) to new_variable .find(letter) then below the if statement write new_variable = new_variable [1:] which will remove the letter just found.
so your code would look something like:
new_variable = secret_word
for i in secret_word
if user_guess == letter:
current_word_index = new_variable.find(letter)
#I would do print(current_word_index) this will show the index
#Or current_word_index = current_word_index + ',' + new_variable.find(letter)
new_variable= new_variable[1:] #this will take away your letter.

Hangman Game - Unable to match input letters to word if the inputted letter sequence is jumbled

Below is an outline of what I am trying to built:
getting input from user about word length
sourcing word from text file according to user input word length
getting number of attempts from user input
display the word as *
Get hint letter input from
user
Run the game
start by displaying the word in *
display the number of attempts remaining
prompt to input next letter
if input matches to the word
print "you guessed correct letter"
replace * from the word in the letter at appropriate space and print
print number of attempts remaining
print guessed letter
prompt to input next letter
*this goes on until all the correct letter of the owrd has been guessed
print "You Won"
if input does not match to the word
print " you guessed wrong letter"
print the word in *
print number of attempts remaining
print guessed letter
prompt to input next letter
*this goes on until remaining attepmt is 0
print "you lose"
if number of attempts is 0
print "no attempt left"
Print the correct word
The code is working only if the inputted letters are constant.
Let's say if the game word is "Rain", the code will work only if user inputs: "R", "A", "I", "N".
Code will not work if the inputted letters are jumbled, like, "A", R", "I", "N".
I believe it can be achieved through iteration using enumerate, but I am not sure how.
Here is my code:
import random
WORDS = "wordlist.txt"
"""Getting Length input from user and selecting random word from textfile"""
def get_word_length_attempt():
max_word_length = int(input("Provide max length of word [4-16]: "))
current_word = 0
word_processed = 0
with open(WORDS, 'r') as f:
for word in f:
if '(' in word or ')' in word:
continue
word = word.strip().lower()
if len(word) > max_word_length:
continue
if len(word) < 4:
continue
word_processed += 1
if random.randint(1, word_processed) == 1:
current_word = word
return current_word
"""Getting input of number of attempts player wants to have"""
def get_num_attepmts():
num_attempt = int(input("Provide number of attempts you want: "))
return num_attempt
"""Displaying word in *"""
def display_word_as_secret():
display_word = '*' * len(get_word_length_attempt())
print(display_word)
"""Getting hint letter from user input"""
def get_user_letter():
user_letter = input("Enter letter: ").lower()
if len(user_letter) != 1:
print("Please Enter single letter")
else:
return user_letter
"""Starting Game"""
def start_game():
game_word = get_word_length_attempt()
attempts_remaining = get_num_attepmts()
print('Your Game Word: ' + game_word)
print('Your Game Word: ' + '*'*len(game_word))
print('Attempts Remaining: ' + str(attempts_remaining))
guessed_word = []
while attempts_remaining > 0:
next_letter = get_user_letter()
if next_letter in game_word:
print('You guessed correct')
guessed_word.append(next_letter)
print('Your Game Word: ' + game_word)
print('Your Game Word: ' + '*' * len(game_word))
print('Attempts Remaining: ' + str(attempts_remaining))
correct_word = "".join(guessed_word)
print(guessed_word)
if correct_word == game_word:
print('you won')
break
else:
print('The letter in not in the game word')
attempts_remaining -= 1
print('Your Game Word: ' + game_word)
print('Your Game Word: ' + '*' * len(game_word))
print('Attempts Remaining: ' + str(attempts_remaining))
else:
print('no attempts left')
print('You Lost')
print('The Word is: ' + game_word)
start_game()
You're constructing correct_word from the guessed letters in the order they were entered by the user. A guessed string 'ARIN' is not equal to 'RAIN'.
Instead, you need to do a comparison that doesn't care about the order. The simplest fix would be to change
if correct_word == game_word:
to
if set(correct_word) == set(game_word):
because sets will be compared for their content regardless of the order. It will also cope better with repeated letters, for example 'letterbox' will just be treated as the collection of letters {'b', 'e', 'l', 'o', 'r', 't', 'x'}.
You might as well store the guessed letters as a set in the first place because it doesn't make sense to guess the same letter more than once anyway.
The problem you describe is in line guessed_word.append(next_letter)
In effect you append letters in the order they are given by the player. Which is fine if you just compare the set of letters and number of occurrences, for example by using counter from collections. Or you can figure out where each supplied letter stands in the subject word and reconstruct that from user input

Updating missing letters in hangman game

I'm making a hangman game and have found a problem with my methodology for updating the answer. I have a variable that adds underscores equal to the amount of letters in the word the player needs to guess. However I can't figure out how to effectively update that when the player guesses a correct letter.
Here is my code
import random
'''
HANGMAN IMAGE
print(" _________ ")
print("| | ")
print("| 0 ")
print("| /|\\ ")
print("| / \\ ")
print("| ")
print("| ")
'''
def game():
print('''Welcome to hangman, you must guess letters to fill in the word.
Incorrect guesses will use up a turn, you have 7 turns before you lose.''')
lines = open("wordBank.txt").read()
line = lines[0:]
words = line.split()
myword = random.choice(words).lower()
letters = len(myword)
print("Your word has " + str(letters) + " letters.")
underscores = ""
for x in range(0, letters):
underscores += "_ "
print(underscores)
print(myword)
l = set(myword)
turn = 0
guesses = []
def guess():
thisGuess = input("Type a letter and press Enter(Return) to guess: ")
if thisGuess.lower() in l:
else:
print("Boo")
guess()
game()
You probably need to reword your question as it's not clear what you are asking. But you should look into string splicing. If they guessed the letter "a" and it goes in the third slot then you could do something like
underscores[:2] + 'a' + underscores[3:]
adapt for your code but that would replace the 3rd underscore with an "a".
UPDATE:
don't use a set, look up the index as you go. Try something like this
for index, letter in enumerate(my_word):
if letter == guessed_letter:
if not index == len(my_word) -1
underscores = underscores[:index] + letter + underscores[index+1:]
else:
underscores = undescores[:-1] + letter
Another possible approach (in Python 2.7, see below for 3):
trueword = "shipping"
guesses = ""
def progress():
for i in range(len(trueword)):
if trueword[i] in guesses:
print trueword[i],
else:
print "-",
print ""
This works by checking for each letter if it's been guessed in guesses, and printing that letter. If it hasn't been guessed, it prints -. When you put a comma at the end of a print (as in print "-",) it won't automatically print a newline, so you can continue printing on the same line. print "" prints a null string with a newline, finishing the line.
Then guessing becomes:
guesses += guess
Output is:
guesses = ''
- - - - - - - -
guesses = 'sip'
s - i p p i - -
In Python 3:
trueword = "shipping"
guesses = ""
def progress():
for i in range(len(trueword)):
if trueword[i] in guesses:
print(trueword[i], end='')
else:
print("-", end='')
print('')
you add the end='' parameter to remove the newline, instead of the comma. If you want the spaces between them, you can add sep=' ' as well to specify the separator.
Also, because list comprehensions are awesome (and this works in 2.7 & 3):
def progress():
ans = [word[x] if word[x] in guesses else '-' for x in range(len(word))]
print(' '.join(ans))
Does the same thing via list comprehensions... which are a very strong feature in python.

Replacing every instance of a character in Python string

I have a game where the user guesses letters. They are shown a blank version of the mystery work (_____ for example, the _'s are equal to number of characters in the word). The program knows the word, and needs to replace every index in the blanked out version of the word if the letter they guess is present in the mystery word.
For example, if the player guesses "p" and the word is "hippo" they will be shown __pp_. But, my code will only replace the first instance of "p", giving __p__ instead.
Would this be easier to tackle as a list problem?
mistakes = 0
complete = False
t = False
words = ['cow','horse','deer','elephant','lion','tiger','baboon','donkey','fox','giraffe']
print("\nWelcome to Hangman! Guess the mystery word with less than 6 mistakes!")
# Process to select word
word_num = valid_number()
word = words[word_num]
#print(word)
print("\nThe length of the word is: ", str(len(word)))
attempt = len(word)*"_"
# Guesses
while not (mistakes == 6):
guess = valid_guess()
for letter in word:
if guess == letter:
print("The letter is in the word.")
position = word.index(guess)
attempt = attempt [0:position] + guess + attempt [position + 1:]
print("Letters matched so far: ", attempt)
t = True
while (t == False):
print("The letter is not in the word.")
print("Letters matched so far: ", attempt)
mistakes = mistakes + 1
hangMan = ["------------", "| |", "| O", "| / |", "| |", "| / |\n|\n|"]
hang_man()
t = True
t = False
answer = 'hippo'
fake = '_'*len(answer) #This appears as _____, which is the place to guess
fake = list(fake) #This will convert fake to a list, so that we can access and change it.
guess = raw_input('What is your guess? ') #Takes input
for k in range(0, len(answer)): #For statement to loop over the answer (not really over the answer, but the numerical index of the answer)
if guess == answer[k] #If the guess is in the answer,
fake[k] = guess #change the fake to represent that, EACH TIME IT OCCURS
print ''.join(fake) #converts from list to string
This runs as:
>>> What is your guess?
p
>>> __pp_
To loop over everything, I did not use index, because index only returns the first instance:
>>> var = 'puppy'
>>> var.index('p')
0
So to do that, I analyzed it not by the letter, but by its placement, using a for that does not put k as each letter, but rather as a number so that we can effectively loop over the entire string without it returning only one variable.
One could also use re, but for a beginning programmer, it is better to understand how something works rather than calling a bunch of functions from a module (except in the case of random numbers, nobody wants to make their own pseudo-random equation :D)
Based on Find all occurrences of a substring in Python:
import re
guess = valid_guess()
matches = [m.start() for m in re.finditer(guess, word)]
if matches:
for match in matches:
attempt = attempt[0:match] + guess + attempt[match+1:]
print("Letters matched so far: ", attempt)
else:
.
.
.

How do i find out how many individual letters there are in a word in python?

I'm using pyscripter to create a hangman game. I have managed to get everything to work except one thing. This is that once i have found the correct word the script needs to match this to the secret word. This would usually be easy but the way i have done it leaves gaps in the string.
What i want to do is using the number of letters in the secret word; when i enter a letter it looks for that letter and adds how many times the letter appears in the secret word. i.e. the letter "P" in APPLE appears 2 times, therefore adding 2 to a separate string. if the word was "APPLE" the program would be looking for 5 correct letters.
This way i can make an "if" statement and end the game once the numbers of correct letters guessed matches the length of the secret word.
This is the program i am using : http://i1.ytimg.com/vi/1HZ38RzykuE/maxresdefault.jpg
Does this make sense, I've been pondering on it for a while so it may be jumbled.
Thank you if your able to help.
This is the code i am using:
(blanktotal is the length of the secret word)
else:
if letter in secretword:
letterscorrect = letterscorrect + 1
os.system("cls")
if letter not in guessedletters:
os.system("cls")
for x in range(0, len(secretword)):
if letter == secretword[x]:
for x in range(len(secretword)):
if secretword[x] in letter:
hiddenletter = hiddenletter[:x] + secretword[x] + hiddenletter[x+1:]
guessedletters.append(letter)
else:
print("")
else:
print("")
for letter in hiddenletter:
print(letter, end=' ')
print("")
if letterscorrect == blanktotal:
os.system("cls")
print("")
print("congratulations you have won!!!!")
print("You are now the master of HANGMAN!!!!!")
print("")
You can use the count() method to count the number of occurrence of a letter.
secret = "Apple"
secret.count('p')
gives
2
I think you're just looking for the count method:
>>> s = 'APPLE'
>>> s.count('P')
2

Categories

Resources