I am trying to make a hangman project and to do so, I need to be able to replace the word_chosen variable with -. Does anyone know how? Let me put in my code:
import random
import time
word_list = ['that', 'poop', 'situation', 'coding', 'python']
word_chosen = random.choice(word_list)
your_name = input("What is your name?")
time.sleep(1)
print("Hello " + your_name + ", lets play some hangman!")
I understand that you want to replace the word with - according to how many letters the word has, so just add this at the end of the code you have already:
hidden_word = ""
for i in word_chosen:
hidden_word += "-"
print (hidden_word)
This loops through selected word and adds a dash for every letter in it.
I believe #costaparas has the right idea:
import random
import time
word_list = ['that', 'poop', 'situation', 'coding', 'python']
word_chosen = random.choice(word_list)
hidden_word_chosen = '-' * len(word_chosen)
print(hidden_word_chosen)
Output:
------
Start simple and work your way up. Think about what actions you need to perform. These are your program requirements. We need to:
Show a word with the current characters hidden, using a list of already guessed characters.
Ask the user for letter and add it to the list of guessed characters.
If that character was already chosen, go back to step 2.
If the character is in the word, increase their incorrect guess count.
If all the characters are found, tell the user they have won, then exit.
If the user has made too many incorrect guess, tell the user they have lost, then exit.
Otherwise, go back to step 1.
To help get you started, lets see how you would write a method to perform action 1.
def print_hidden_word(word_chosen, characters_guessed):
result = ""
for character in word_chosen:
if character in characters_guessed:
result += character
else:
result += "-"
print("Your word is: " + result)
We can test this function separately to try it out:
>>> print(print_hidden_word("python", ["p", "t", "n"]))
Your word is: p-t--n
A hint for the whole program: you will want to use a while loop and have a counter to keep track of how many incorrect guesses are made.
Related
I am trying to build a complex hangman game in Python for a school assignment (first post on here btw, so sorry if I don't use the correct etiquette). My code so far is operating on a basic, but functional level; I have a generated file filled with random word variation. I import the file, put it into a list, clean the data and use random to randomly select a word. The program repeatedly asks the user to input a letter or word until they guess correctly or run out of lives. I have ran into an issue where if the same letter appears multiple times in a word, it won't register the fact that it needs to scan and append the list twice for each time the word appears. This might be a really simple problem, but I appreciate any help. Thanks in advance!
(P.S. underscores is the list that displays underscores in place of unidentified letters for the output)
elif guess in correctLetters:
print("\nYou got a letter! Here is where it appears in the word:\n")
index = word.index(guess)
underscores[index] = guess
for i in underscores:
print(i, end="")
In terms of an example, I want the code to use the user's input ('guess') and see if it appears in the list 'correctLetters'. If it does, I want the code to append 'guess' into the correct index in the list. E.g. if the unknown word is 'hangman' and ('guess') is 'h', the code will append 'h' into the correct position in the list and then just make the list look more pleasing to the eye. My current problem is (following the example outlined above) if I were to enter 'a' I want the code to return '_ a _ _ _ a ' where as now it will only return ' a _ _ _ _ _'. I need the code to see that the same item appears twice in the list and so it appends it twice as well in the list that will be shown to the user. Hope this makes my issue clearer.
You might think about going through your hidden word letter for letter and construct a display version of it revealing guessed letters or hiding unguessed letters. Maybe like:
guesses = set()
word = "hello"
## each round make a guess...
guess = "l"
guesses.add(guess)
letters_underscored = [
letter if letter in guesses else "_"
for letter in word
]
word_underscored = "".join(letters_underscored)
print(word_underscored)
This will give you:
__ll_
The code in your question:
index = word.index(guess)
underscores[index] = guess
...finds the first occurrence of the letter in the word and replaces the underscore with the guess. A simple way to replace all occurrences would be to loop until word.index(guess) raises an exception, ignoring indices that have already been replaced by using the second argument of the index method, which specifies a starting point for the search. E.g.:
index = -1
done = False
while not done:
try:
index = word.index(guess, index + 1) # find the index of guess in word that occurs after `index + 1`
underscores[index] = guess
except ValueError:
# if all occurrences have been replaced, stop
done = True
I am a beginner in Python. This is a challenge that I've found in a forum.
This program is censoring the words' (which has given by the user) letters with "*" except the first letter.
For example, If the sentence is "Every breath you take every move you make" and the input word is "every", the output should look like this:
2 incidents found.
Censored lyrics:
E**** breath you take e**** move you make
This was my only idea but it did not work.
text=input("Enter your text: ").lower()
word=input("Choose a word from the previously entered text: ").lower()
def censor(text,word):
t=text.split()
n=[]
for i in t:
if(i==word):
n.append("*"*len(word))
else:
n.append(i)
return " ".join(n)
print (censor)
Any help would be appreciated!
There are a few mistakes.
In Python 3 you have to use () while printing e.g. print("Hello world") NOT: print "Hello world"
i.lower()==word because "Every" != "every"
n.append(i[0]+"*"*(len(word)-1)) because you want first letter to stay
Code:
text=input("Enter your text: ").lower()
word=input("Choose a word from the previously entered text: ").lower()
def censor(text,word):
t=text.split()
n=[]
for i in t:
if(i.lower()==word):
n.append(i[0]+"*"*(len(word)-1))
else:
n.append(i)
return " ".join(n)
print(censor(text,word))
The issue here is that when you find the word, you just put * you never add the first letter. To fix that you would need:
n.append(word[0]+"*"*(len(word)-1))
instead of
n.append("*"*len(word))
Now it will add the first letter and the right number of * afterward.
It's not clear how it "doesn't work"; when I run your code this is the output:
***** breath you take ***** move you make
We can tweak your script to leave in the first letter:
if(i==word):
n.append(i[0] + "*"*(len(word)-1))
Giving the output as:
e**** breath you take e**** move you make
Again, it's not actually clear what wasn't working, but that's how you'd show the first letter of each censored word.
I have an approach related to Regex which could suit this purpose, just consider this as something you can expand on thinking to create your final program:
import re
blacklist = ['every']
def replace(match):
word = match.group()
if word.lower() in blacklist:
return word[0]+"*"*(len(word)-1)
else:
return word
text = 'Every breath you take every move you make'
text = re.sub(r'\b\w*\b', replace, text, flags=re.I|re.U)
print(text)
The advantage this has is that it will work with all kinds of word boundaries that regex recognizes.
You can check the output image below:
I'm trying to a hangman game. I already achieved to set the basics of the game (list, interaction with user) but I don't know how to do the lines for the game, keep asking and printing what the user correct answers are and ilustrate the hangman.
I used index in order to search the exact location of the letter in the word, but I dont know to print it, depending on the number and also I don't how to code that the program keeps track of the correct words.
I would be totally glad for your help. Also thanks for your patience.
The first part of the code is well coded but stackoverflow doesn't display it right.
------------------------------------------------------------------------
import random
def hangman():
words = ['house','car','women', 'university','mother', 'school', 'computer','pants'] #list of words
computer = words[random.randint(0,6)] #computerchoice
word = list(computer) #Make a list with each letter of the word.
welcome = (input ('Welcome, type ok to continue: '))
if welcome == 'ok':
length = len(word)
print(f'help? the word has {length} letters')
option = (input('Start guessing, letter by letter'))
count= 0 #count takes the count of how many tries.
chances = length+3 #You are able to make 3 mistakes.
while count<=chances:
if option in word: #if the choice is there
place = word.index(option) #search for the place.
print() #dont know how to print it in 'that' place.
#place the correct letter over that line.
print('_ '*length) #Trying to do the under lines.
count+=1
else:
break
#Dont know to ilustrate the hangman depending on the length of the word.
hangman()
First let's analyse your code:
import random
def hangman():
words = ['house','car','women', 'university','mother', 'school','computer','pants'] #list of words
computer = words[random.randint(0,6)] #computerchoice
word = list(computer) #Make a list with each letter of the word.
Everything is fine up to here , although str can be used the same way as a list , so no need to transform it.
welcome = (input ('Welcome, type ok to continue: '))
if welcome == 'ok':
length = len(word)
print(f'help? the word has {length} letters')
Yes but those are not unique letters. You can use set() to have the number of unique letters.
option = (input('Start guessing, letter by letter'))
If your input starts here, you will only ask once for a letter , you need to include this part in the while loop
count= 0 #count takes the count of how many tries.
chances = length+3 #You are able to make 3 mistakes.
This would then probably be changed to the length of the set.
while count<=chances:
if option in word: #if the choice is there
place = word.index(option) #search for the place.
This will only give you the index of the first occurence.
We should keep in mind to use regex for this type of search : Find all occurrences of a substring in Python
print() #dont know how to print it in 'that' place.
Let's remember to use the print formating f'stufff{value}stuffff'
#place the correct letter over that line.
To do it , you need to create a str only with _and then fill it in with the indexes using list comprehension .
print('_ '*length) #Trying to do the under lines.
count+=1
Maybe we should handle what happens if option is not in words ?
else:
break
#Dont know to ilustrate the hangman depending on the length of the word.
Also there is no need for break : count increments and therefore while will terminate. And if it was for the outer if/else , break doesn't work outside a loop.
hangman()
Question for OP:
What point would you like to sort out yourself ? What do you need help for next ?
Trying to create a guessing game.
I've got a CSV file with 2 columns. The first contains artist names, the second contains song titles
I want to be able to display a random artist name and then the first letter of each word in the song title e.g.
Led Zeppelin - S******* t* H*****
So far I've been able to get it to select a random artist from the file and display both the artist and song title
import random
import time
filesize = 11251
offset = random.randrange(filesize)
words = []
print("Welcome to the music guessing game")
def randomsong():
file = open("musicFile.csv","r")
file.seek(offset)
file.readline()
line =file.readline()
data = line.split(",")
print (data[0], data[1])
song = data[1]
song = str(song)
print(song)
guesses = 2
Score = 0
song = song.lower()
while guesses != 0:
yourguess = input ("Guess the name of the song")
if yourguess == song:
print ("Well Done!")
else:
print ("Incorrect, try again ")
guesses = guesses -1
print("Game Over!!!")
randomsong()
Users should then be able to try and guess the song.
I know the code above is printing the artist and song title and the song title again, I'm just testing it to make sure it's selecting what I want.
Separate issue: the IF statement is always saying "incorrect please try again" even if I put in the correct answer.
I'm not just looking for someone to do this for me; if you could explain where I've gone wrong I'd appreciate it.
With problems like this, start with the smallest bit first and work from the inside out.
How do I take a single word and display the first letter with asterisks for the rest?
>>> word = 'Hello'
# Use indexing to get the first letter at position 0
>>> word[0]
'H'
# Use indexing to get the remaining letters from position 1 onwards
>>> word[1:]
'ello'
# Use len to get the length of the remaining letters
>>> len(word[1:])
4
# Use the result to multiply a string containing a single asterisk
>>> '*' * len(word[1:])
'****'
# put it together
>>> word[0] + '*' * len(word[1:])
'H****'
So now you know you can get the result for a single word with word[0] + '*' * len(word[1:]), turn it into a function:
def hide_word(word):
return word[0] + '*' * len(word[1:])
Now if you have a string of multiple words, you can use .split() to turn it into a list of individual words. Challenge for you: How do you put the results back together into a new title string?
To answer your OP's title:
You can use str.split() and string-slicing in concjunction with a generator expression and str.join():
def starAllButFirstCharacter(words):
# split at whitespaces into seperate words
w = words.split()
# take the first character, fill up with * till length matches for
# each word we just split. glue together with spaces and return
return ' '.join( (word[0]+"*"*(len(word)-1) for word in w) )
print(starAllButFirstCharacter("Some song with a name"))
Output:
S*** s*** w*** a n***
I was trying to make a program that could be used for one-time pad encryption by counting the number of characters and having a random number for each one. I started making a line that would let the program ignore spaces, but then I realized I would also need to ignore other symbols. I had looked at How to count the number of letters in a string without the spaces? for the spaces,
and it proved very helpful. However, the answers only show how to remove one symbol at a time. To do what I would like by using that answer, I would have to have a long line of - how_long.count('character')'s, and symbols that I may not even know of may still be copied in. Thus, I am asking for a way where it will only count all the alphabetic characters I write down in a list. Is this possible, and if so, how would it be done?
My code:
import random
import sys
num = 0
how_long = input("Message (The punctuation will not be counted)\n Message: ")
charNum = len(how_long) - how_long.count(' ')
print("\n")
print("Shift the letters individually by their respective numbers.")
for num in range(0, charNum-1):
sys.stdout.write(str(random.randint(1, 25))+", ")
print(random.randint(1, 25))
If your desired outcome is to clean a string so it only contains a desired subset of characters the following will work but, I'm not sure I totally understand what your question is so you will probably have to modify somewhat.
desired_letters = 'ABCDOSTRY'
test_input = 'an apple a day keeps the doctor away'
cleaned = ''.join(l for l in test_input if l.upper() in desired_letters)
# cleaned == 'aaadaystdoctoraay'
Use Regex to find the number of letters in the input:
import re, sys, random
how_long = input("Message (The punctuation will not be counted)\n Message: ")
regex_for_letters = "[A-Za-z]"
letter_count = 0
for char in how_long:
check_letter = re.match(regex_for_letters, char)
if check_letter:
letter_count += 1
print(letter_count)
for num in range(0, letter_count-1):
sys.stdout.write(str(random.randint(1, 25))+", ")
print(random.randint(1, 25))
Filter the string:
source_string='My String'
allow_chars=['a','e','i','o','u'] #whatever characters you want to accept
source_string_list=list(source_string)
source_string_filtered=list(filter(lambda x: x in allow_chars,source_string_list))
the count would be: len(source_string_filtered)