I have a list (display) that I need to update as the user does their input. So, if the user input the letter A, I need the letter A to replace an element in the new list called display. I might not be writing this code correctly, but I'm stuck at the code below. I'm not sure how I can write the code to replace the element in the list called display. Any help or guidance would be much appreciated. TIA
import random
name_list = ["daniel", "babs", "cal"]
chosen_word = random.choice(name_list)
display = []
guess = input("Guess a letter: ").lower()
for numChar in range(len(chosen_word)):
display += "_"
for letter in chosen_word:
if letter == guess:
EXPECTED OUTPUT:
If the user input was "a" and the chosen_word is babs, since it has an "a" in it, I need it to replace the list ('', '', '', '') with the corresponding letter. ('', 'a', '', '_')
You're trying to make hangman, aren't you?
Try this:
import random
name_list = ["daniel", "babs", "cal"]
chosen_word = random.choice(name_list)
display = []
guess = input("Guess a letter: ").lower()
if guess == chosen_word:
display = list(chosen_word)
else
for numChar in range(len(chosen_word)):
if numChar == guess[0]:
display.append(numChar)
else
display.append("_")
import random
name_list = ["daniel", "babs", "cal"]
chosen_word = random.choice(name_list)
display = []
guess = input("Guess a letter: ").lower()
display[:] = [guess if x == guess else "_" for x in chosen_word]
Use enumerate to get each letter as well as its index:
import random
name_list = ["daniel", "babs", "cal"]
chosen_word = list(random.choice(name_list))
display = ["_" for _ in chosen_word]
while display != chosen_word:
print(display)
guess = input("Guess a letter: ").lower()
for i, letter in enumerate(chosen_word):
if letter == guess:
display[i] = letter
Related
import random
#variable will count how many letters are in the word the computer chooses
count = 0
user = input("Guess letter: ")
word = random.choice(["LONDON", "RESPECT", "ABSOLUTE"])
#This seperates each letter and makes a list
letters = list(word)
#Loop counts letters in the word and updates the variable
for i in range(0, len(word)):
if(word[i] != ' '):
count = count + 1;
#This checks if any of the letter that the user guessed is in the list letters
if user == letters[0] or user == letters[1] or user == letters[2] or user == letters[3] or user == letters[4] or user == letters[5] or user == letters[6] or user == letters[7]:
print("well done")
else:
print("nope")
print(letters)
print(" _ " * count)
I expect the error's coming from your long if .. or statement. By replacing it you'll not only shorten your code, but also make it easier to debug:
import random
# computer selects secret word
word = random.choice(["LONDON", "RESPECT", "ABSOLUTE"])
#This seperates each letter and makes a list
letters = list(word) # <-- not actually needed!
#variable will count how many letters are in the word the computer chooses
count = len(letters)
# accept user input & convert to upper case
user = input("Guess letter: ").upper()
#This checks if any of the letter that the user guessed is in the list letters
if user in letters:
print("well done")
else:
print("nope")
print(letters)
print(" _ " * count)
Keep working on your own approach, but if you get stuck, here's how I'd approach the guessing part of the game. You'd still need to figure out how you want to track incorrect guesses and game over:
import random
# computer selects secret word
letters = random.choice(["LONDON", "RESPECT", "ABSOLUTE"])
print(f'Guess the {len(letters)} letter word!')
user_guesses = []
# Keep going until user is correct
while True:
# accept user input & convert to upper case
user = input('\nGuess letter: ').upper()
user_guesses.append(user)
# if user's guess is in the word, display it, otherwise display _
progress = []
for letter in letters:
if letter in user_guesses:
progress.append(letter)
else:
progress.append('_')
print(''.join(progress))
if progress == letters:
print('You win')
break
Good evening everyone..... i wrote a vowel eater program with the code below
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
userWord = userWord.upper()
for letter in userWord:
if letter == 'A':
continue
elif letter == 'E':
continue
elif letter == 'I':
continue
elif letter == 'O':
continue
elif letter == 'U':
continue
else:
print(letter)
It run fine but i want to use concatenation operation to ask python to combine selected letters into a longer string during subsequent loop turns, and assign it to the wordWithoutVowels variable.....
I really appreciate any help or suggestions thanks in advance
is this what you need?
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
userWord = userWord.upper()
for letter in userWord:
if letter == 'A':
word = letter
continue
elif letter == 'E':
continue
elif letter == 'I':
continue
elif letter == 'O':
continue
elif letter == 'U':
continue
else:
wordWithoutVowels+=letter
print(wordWithoutVowels)
Another approach. You can prepare a set of vowels you want to filter-out before-hand and then use str.join() to obtain you string:
userWord = input("Please Enter a word: ")
vowels = set('aeiou')
wordWithoutVowels = ''.join(character for character in userWord if not character.lower() in vowels)
print(wordWithoutVowels)
Prints (for example):
Please Enter a word: Hello World
Hll Wrld
I'm sorry I didn't read the original post (OP) more carefully. Poster clearly asked for a way to do this by concatenation in a loop. So instead of excluding vowels, we want to include the good characters. Or instead of looking for membership, we can look for not in membership.
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
vowels = 'aAeEiIoOuU'
wordWithoutVowels = '' # initialize to empty string
for letter in userWord:
if letter not in vowels:
wordWithoutVowels += letter # equivalent to wordWithoutVowels = wordWithoutVowels + letter
print(wordWithoutVowels)
Please Enter a word: Hello World
Hll Wrld
or you can try this:
wordWithoutVowels = ""
user = input("Enter a word: ")
userWord = user.upper()
for letter in userWord:
if letter == "A":
continue
elif letter == "E":
continue
elif letter == "O":
continue
elif letter == "I":
continue
elif letter == "U":
continue
else:
wordWithoutVowels += letter
print(wordWithoutVowels)
Using str.replace() seems like a natural way to go for a problem like this
Brute Force
Just go through all of the vowels. And if they exist in input string, replace them
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
userWord = userWord.upper()
# make a copy of userWord
output = userWord
# replace vowels
output = output.replace('A', '') # replace A with empty string
output = output.replace('E', '') # replace E with empty string
output = output.replace('I', '') # replace I with empty string
output = output.replace('O', '') # replace O with empty string
output = output.replace('U', '') # replace U with empty string
print(output)
Please Enter a word: Hello World
HLL WRLD
Use a loop
This is a little more elegant. And you won't have to convert the input to uppercase.
wordWithoutVowels = ""
userWord = input("Please Enter a word: ")
# make a copy of userWord
output = userWord
# replace vowels
vowels = 'aAeEiIoOuU'
for letter in vowels:
output = output.replace(letter, '') # replace letter with empty string
print(output)
Please Enter a word: Hello World
Hll Wrld
Try this. I think it's the easiest way:
word_without_vowels = ""
user_word = input("Enter a word")
user_word = user_word.upper()
for letter in user_word:
# Complete the body of the loop.
if letter in ("A","E","I","O","U"):
continue
word_without_vowels+=letter
print(word_without_vowels)
user_word =str(input("Enter a Word"))
# and assign it to the user_word variable.
user_word = user_word.upper()
vowels = ('A','E','E','I','O','U')
for letter in user_word:
if letter in vowels:
continue
elif letter == vowels:
letter = letter - vowels
else:
print(letter)
A one liner that does what you need is:
wordWithoutVowels = ''.join([ x for x in userWord if x not in 'aeiou'])
or the equivalent:
wordWithoutVowels = ''.join(filter(lambda x : x not in 'aeiou', userWord))
The code is creating a list containing the letters in the string that are not vowels and then joining them into a new string.
You just need to figure out how to handle the lower/capital cases. You could do x.lower() not in 'aeiou', check if x is in 'aeiouAEIOU', ... you have plenty of choices.
user_word = input('enter a word:')
user_word = user_word.upper()
for letter in user_word:
if letter in ('A','E','I','O','U'):
continue
print(letter)
word_without_vowels = ""
vowels = 'A', 'E', 'I', 'O', 'U'
user_word = input('enter a word:')
user_word = user_word.upper()
for letter in user_word:
if letter in vowels:
continue
word_without_vowels += letter
print(word_without_vowels)
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)
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")
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.