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 ?
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 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.
In my program, the user can input a list of words or the letter n. What I want to do is when they input n, it want it to set the value of the variable where the user input is saved to a question mark (?).
Also in my program, the user inputs a different list, if they input n, I want the program to generate a word frequency table.
The problem I'm having is that when I write out the if statements for if the user input is n, I don't think that it's changing the value or creating the frequency table.
I've shifted where the code is in the program. I'm not getting the response from either if statement no matter where I put it in the code. Originally I thought the program was that I had put it near the end of the program and since it was reading it top to bottom, nothing was happening. Now, I'm not sure.
I've included the pieces of the code that would work together so I'm not pasting the entire program.
# Ask user for needed keywords or symbols
user_keywords = input("What keywords or special symbols would you like to search the provided file for?\n"
"Please separate each entry with a comma.\n If you would like to just search for question marks"
"please just type n.")
# Holding list, using comma as a way to separate the given words and symbols
list1 = list(user_keywords.split(','))
# Print list for user to see
print("You have entered the following keywords and/or special symbols: ", list1)
# Ask user for needed repeating words
user_repeating = input("What repeating words would you like to search the provided file for?\n"
"Please separate each entry with a comma. \n If you would like a frequency table for all words"
"two letters or more, please type n.")
# Holding list, using comma as a way to separate the given words and symbols
list2 = list(user_repeating.split(','))
# Print list for user to see
print("You have entered the following words: ", list2)
frequency = {}
# Check to see if list1 has no parameters and sets to ?
if list1 == 'n':
list1 = '?'
print("We will search for any question marks.")
# Check to see if list2 has no parameters and creates a frequency array
if list2 == 'n':
document_text = open (path1, 'r')
text_string = document_text.read().lower()
match_pattern = re.findall(r'\b[a-z]{2-20}\b', text_string)
print("We will look for all word frequencies.")
for word in match_pattern:
count = frequency.get(word,0)
frequency[word] = count + 1
frequency_list = frequency.keys()
for words in frequency_list:
print(words, frequency[words])
I expect list1 to be set to ? when n is entered by the user. I expect list2 to generate a word frequency table when n is entered by the user.
I'm not getting any errors. At this point is just goes straight to the end of the program and returns the final print line I have in it, so I know it isn't calling the if statements.
Surely the way to do this is to replace:
list1 = list(user_keywords.split(','))
with
list1 = '?' if user_input == 'n' else list(user_keywords.split(','))
no?
I have recently started to learn python as I wanna enter a deep learning field in future.
As I'm completely new and only started I apologize in advance if my question is silly.
I am currently doing a course on edx by name introduction to python fundamentals and as I final project of module 1 I need to make a program that asks for user input and give an output of all words that starts from h to z.
task
here is my code:
user_input = input("enter a 1 sentence quote, non-alpha separate words: ")
new_name = ""
for letter in user_input:
if letter.isalpha() == True:
new_name += letter.upper()
elif letter.isalpha() == False:
if new_name[0] > "g":
print(new_name)
new_name = ""
else:
new_name = "\n"
print(new_name)
INPUT = Wheresoever you go, go with all your heart
OUTPUT = WHERESOEVERYOUGOGOWITHALLYOURHEART
By my understanding of code I have wrote:
- user enters input
- code check for each character
- if letter is alpha that letter is added into new_name variable
- when encounter first no alpha character in these case space after word Wheresoever code moves to elif since after checking a fist one it was not True and elif turn to mach criteria
- then by using nested if statement it checks if new_name variable[index0] (Wheresoever) is grater then g.
- if it is grater it prints new_name and makes new_name empty and repeat the circle until there is no more characters to check.
- if its not greater then g it starts with new word on the new line
Now as I sad I'm completely new so I have just described my thoughts process of the code and please tell me where am I wrong and how can I corrected and improve my thoughts process and the code mentioned above.
Thank you in advance :)
Try the below, iterate trough the list split of the user_input string, then check if it starts with a G or g, if it does, don't keep it, otherwise keep it, then use regular expressions (re) to get only letters.
Also as you said you need isalpha so then:
user_input = input("enter a 1 sentence quote, non-alpha separate words: ")
print('\n'.join([''.join(x for x in i if x.isalpha()).upper() for i in user_input.split() if not i.lower().startswith('g')]))
Example output:
enter a 1 sentence quote, non-alpha separate words: Wheresoever you go, go with your heart
WHERESOEVER
YOU
WITH
YOUR
HEART
Update form #KillPinguin:
do:
user_input = input("enter a 1 sentence quote, non-alpha separate words: ")
print('\n'.join([''.join(x for x in i if x.isalpha()).upper() for i in user_input.split() if ord(i[0])>ord('g')]))
I have been trying to make a Python code "program that reads in a word specified by the user and prints that word out x number of times where x is the number of characters in the word. Your solution must use a loop"
For example, if the user enters “John”, the computer will print
“John” four times since there are four characters in “John”.
I have done my other task for today though it took me a while it was to make a code that does the same but for the amount of words in a paragraph then prints them as many times as there were words in the paragraph.
loop = 0
print ("please enter a paragraph")
word = str (input())
words = word.split()
number_of_words = len(words)
while (loop < number_of_words):
print(words)
loop = loop + 1
I feel i'm not far off the same principle for the task I am asking help for, as my other does the same but with words not letters. May someone show me the most basic way to count all the letters in a paragraph then print them as many times as there is letters in the paragraph . I found one post on here that is almost the same but refers to files and looks a tad too complex for me "being in my first year at college"
assuming that your variable name is your input:
for _ in name: print(name)
for loops iterate through the letters of a string but since you want to print out the word each time, you dont need to use the values.
python makes this extremely easy:
print(word*len(word))
# or with newlines inbetween
print((word+"\n")*len(word))
Edit: since you really need a loop just use the already suggested answer from R Nar:
for _ in word: print(word)
for i in range(0, len(words)):
print words
I think this should be fine.