This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 1 year ago.
I have coded a game of Hangman. For unknown letters, it prints a _, but because it is in a while loop it prints a different line. Is there a way to put all the dashes on the same line, so it easier to read?
My code is below:
import time
import random
# Welcoming the user
name = input("What is your name? ")
print("Hello, " + name, "Time to play hangman!")
print(" ")
# Wait for 1 second
time.sleep(1)
print("Start guessing letters...")
time.sleep(0.5)
# Here we set the secret
words = ("pyhton","coding","recycle","dawn","vision","talkative","love","difficulty","late","bake","compact","old","employee","be","bubble","guess","home","urgency","buttocks","shop","fluctuation",
"snack","fling","structure","incentive","enemy","fastidious","overcharge","disagreement","consciousness")
word = random.choice(words)
# Creates an variable with an empty value
guesses = ''
# Determine the number of turns
turns = 10
# Create a while loop
# Check if the turns are more than zero
while turns > 0:
# Make a counter that starts with zero
failed = 0
# For every character in secret word
for char in word:
# See if the character is in the players guess
if char in guesses:
# Print then out the character
print(char)
else:
# If not found, print a dash
print("_")
# And increase the failed counter with one
failed += 1
# If failed is equal to zero
# Print "You Won"
if failed == 0:
print("You won, The word was", word)
# Exit the script
break
print
# Ask the user go guess a character
guess = input("guess a character: ")
# Set the players guess to guesses
guesses += guess
# If the guess is not found in the secret word
if guess not in word:
# Turns counter decreases with 1 (now 9)
turns -= 1
# Print "Wrong"
print("Wrong")
# How many turns are left
print("You have", + turns, 'more guesses' )
# If the turns are equal to zero
if turns == 0:
# Print "You Lose"
print("You Lose")
print("The word was",word)"
The print function has an end parameter which means you can say something like this:
print("text", end=" ")
And instead of moving to a new line, your code will print everything on the same line with spaces between every print.
Note you will have to add this to both print statements:
# see if the character is in the players guess
if char in guesses:
# print then out the character
print(char, end=" ")
else:
# if not found, print a dash
print("_", end=" ")
And you will have to add a "\n" to the front of the text that comes right after the word:
guess = input("\nguess a character: ")
This should do the trick:
Replace your print call for printing "_" with this:
print("_", end = "")
Example:
for i in range(10):
print("_", end="")
# Out: __________
If you want to change the default character at the end of print calls, use the end keyword arg. Example:
>>> word = 'python'
>>> for x in word:
... print(x, end = ' ')
...
p y t h o n
Related
it's a guess-the-letter game something like hangman. it generates a random word in the length of 4 or 5 it's the user's choice and after that, it displays it like this ^^^^ for 4 letters for example. each time user can guess a letter if it's not right I display a message and says it but if it's right has to display that it is right and display the word something for example like this ^a^^. the letter has to be exactly in the position of the original word. can someone help me with the part where the letter that is guessed is right? How shoul i code that this format ^^^^ be forexample like ^a^^ if the letter guessed is right?
# Choosing the words
if result2 == 4:
word = choice(word4)
else:
word = choice(word5)
guess_list = [] # List of guess letters
sec_word = [] # the list for formatting the random word
for i in range(len(word)):
sec_word.append("*") # To format the random word into ****
while result1 > 0: # Start of the guessing game on the condition that guess left is greater than 0
print("word is:", "".join(sec_word)) # Displaying the word
# Displaying the remaining guess number
print("Guess remaining:", num_guess)
print("Previous guess:", guess) # Showing the previous guest
guess = input("Please guess a letter: ")
guess_list.append(guess) # Add the guess letters to a list
if guess.lower() == "stop" or guess.lower() == "exit":
print("Game Ends!")
break # Letting user end the game at anytime
if guess not in guess_list:
if guess in word: # if the user guess correct letter
print(guess, "is in the word")
else: # if the user guess wrong letter
print("Sorry! letter entered is not present in the word!")
else:
# If a letter is already in list
print("You have already guessed that letter, Try another letter")
result1 -= 1 # After each guess the remaining guess time drops 1 time
and output of the code is supposed to be something like this
Word is: ****
Guesses remaining: 6
Previous Guesses:
Choose a letter to guess: a
‘a’ is NOT in the word! Try again!
Word is: ****
Guesses remaining: 5
Previous Guesses: a
Choose a letter to guess: b
‘b’ is in the word!
Word is: b***
Guesses remaining: 4
Previous Guesses: a
Choose a letter to guess: l
‘l’ is in the word!
Word is: bl**
Guesses remaining: 3
Previous Guesses: a
Choose a letter to guess: a
‘a’ is NOT in the word and has been guessed before.
Guesses remaining: 3
Choose another letter to guess: e
‘e’ is in the word!
Word is: bl*e
Guesses remaining: 2
Previous Guesses: a
Choose a letter to guess: exit
I think this base code will work for this,
Note: You need to find index of all occurrences if character is present more than twice in word ( ex: pool ) here o is occurring twice, so you can loop over the base method to replace both occurrences
original_word = 'avatar'
masked_word = '*' * len(original_word)
i = 4 # this is index of character
if(i == 0):
masked_word = original_word[0] + masked_word[1:]
elif(i == len(original_word)-1):
masked_word = masked_word[:i] + original_word[i]
else:
masked_word = masked_word[:i] + original_word[i] + masked_word[i+1:]
print(masked_word)
Im new to programming and was trying to program a word guesser. I dont understand why the while loop doesnt go though three times, also the program doesnt remember the previously guessed letters.
import random
words = ["hello", "bye", "petscop"]
GuessWord = random.choice(words)
tries = 3
while tries > 0:
tries = tries - 1
inp = input("\nEnter your guess: ")
for char in GuessWord:
if char in inp:
print(char, sep="",end="")
elif char not in inp:
print("_", sep="",end="")
tries = tries - 1
I'm sorry to say, StackOverflow isn't a forum for debugging. StackOverflow is more about solving general problems that affect multiple people rather than single instances of a problem (like bugs), if that makes sense.
There is probably a better place for you to ask this question but I can't think of one off the top of my head.
In the spirit of being constructive: the following code appears twice and you should remove the second instance.
tries = tries - 1
Also, you are overwriting inp each time you enter the loop causing it to forget its previous value. There are other issues too. But that's a good start.
The main problem you have is that you decrease the number of tries by 2 each round. Therefore, at the beginning of the second round, the number of tries decreases again so it fails. This is how I would do it:
import random
# library that we use in order to choose
# on random words from a list of words
name = input("What is your name? ")
# Here the user is asked to enter the name first
print("Good Luck ! ", name)
words = ['rainbow', 'computer', 'science', 'programming',
'python', 'mathematics', 'player', 'condition',
'reverse', 'water', 'board']
# Function will choose one random
# word from this list of words
word = random.choice(words)
print("Guess the characters")
guesses = ''
# any number of turns can be used here
turns = 3
while turns > 0:
# counts the number of times a user fails
failed = 0
# all characters from the input
# word taking one at a time.
for char in word:
# comparing that character with
# the character in guesses
if char in guesses:
print(char)
else:
print("_")
# for every failure 1 will be
# incremented in failure
failed += 1
if failed == 0:
# user will win the game if failure is 0
# and 'You Win' will be given as output
print("You Win")
# this print the correct word
print("The word is: ", word)
break
# if user has input the wrong alphabet then
# it will ask user to enter another alphabet
guess = input("guess a character:")
# every input character will be stored in guesses
guesses += guess
# check input with the character in word
if guess not in word:
turns -= 1
# if the character doesn’t match the word
# then “Wrong” will be given as output
print("Wrong")
# this will print the number of
# turns left for the user
print("You have", + turns, 'more guesses')
if turns == 0:
print("You Loose")
I'm currently learning Python and trying to build a set of minigames to solidify my basic knowledge, however there are a few things I want to do with my game that others on here haven't (from what I've seen, at least), and that is remove whitespace between words from the answer and the "masked" answer. I assume it would be done as an "if, else" sort of statement? Please correct me if I'm wrong.
for x in range(i): ## where i is the word
if x == " ":
continue ## wouldn't it be pointless to append something that you don't want to change?
else:
word.append('_')
Another question I had was regarding a loop statement I have at the beginning of my game, within this loop I have an if/else stating that if there are more than 1 letter in the guess, it'll return a statement telling the user that's not valid. But the game immediately stops working afterword.
while guesses < 6:
guess = raw_input("Please guess a letter: ")
if len(guess) > 1:
return "One letter at a time!"
else: continue
I'm not quite sure what to add to my code to make it continue asking for input after this.
Here's my full code, it's currently not working for me after asking for input... I took the code it from another user on here and fixed it to my tastes, since their game didn't use more than one word and didn't check to see if there was more than one letter being input when prompted, and I figured it would be good practice to modify existing code to make it do a bit more than it originally does.
def hangman():
guesses = 0
word = []
guessed = []
words = ["bichon frise", "maltese", "dachshund", "pomeranian", "golden retriever", "shih tzu", "rottweiler", "pit bull", "beagle", "poodle", "akita", "basset hound", "border collie", "boston terrier", "boxer", "bulldog", "chow chow", "chihuahua", "chinese crested", "french bulldog", "great dane", "great pyrenees", "greyhound", "icelandic sheepdog", "irish wolfhound", "komondor", "mastiff", "shnauzer", "pekingese", "welsh corgi", "redhound coonhound", "samoyed", "shiba inu", "weimaraner", "whippet", "italian greyhound", "yorkshire terrier"]
print "Welcome to Hangman. The words chosen are the names of various breeds of dogs, try and guess the word before the man is hung!"
answer = random.choice(words)
i = len(answer)
print "The length of the word is", i, "characters long"
for x in range(i):
if x == " ":
continue
else:
word.append('_')
while guesses < 6:
guess = raw_input("Please guess a letter: ")
if len(guess) > 1:
return "One letter at a time!"
else:
continue
if (guess in i):
print "The letter is in the word."
for index, letter in enumerate(i):
if letter == guess:
word[index] = guess
guessed.append(guess)
else:
print "The letter is not in the word"
guesses = guesses + 1
guessed.append(guess)
print "You have guessed these letters so far: %s)" % (''.join(guessed))
print "Letters matched so far %s): %" (''.join(word))
if ''.join(word) == answer:
break
if guesses == 6:
print "You didn't guess the right answer in time! The answer was %s" % answer
else:
print "You guessed the word!"
remove whitespace between words from the answer.
Given i (i as a string?) is the string, you probably should not use range(..) on it since range expects an int. Furthermore why do you build a list instead of a new string? You can however easily use a generator:
word = ''.join(c for c in i if c != ' ')
word is here a string that contains all characters of i that are not ' '. If you want however to generate a sequence of underscores, you can use:
word = ''.join('_' for c in i if c != ' ')
If you want to construct a list (which the remainder of the code expects), you can use list comprehension:
word = ['_' for c in i if c != ' ']
it'll return a statement telling the user that's not valid. But the game immediately stops working afterword (sic.).
That's because you use a return statement: return means you jump out of the function and (optionally) return a value. You probably want to print(..):
guesses = 0
while guesses < 6:
guess = raw_input("Please guess a letter: ")
if len(guess) > 1:
print("One letter at a time!")
else:
#process char
continue
I also noticed you use continue. continue means that you abandon the remainder of the iteration and take the next one, so it means you will not process the query. So you have to remove the continue part:
while guesses < 6:
guess = raw_input("Please guess a letter: ")
if len(guess) > 1:
print("One letter at a time!")
return ends the function right there, use print instead:
print "One letter at a time!"
As for the whitespace, why don't you append the space to the masked word? That way, the player won't have to guess it, can see that there are spaces, and your join-check will work:
for x in range(i):
if x == " ":
word.append(' ')
else:
word.append('_')
I'm a bit stuck on how I would get python to have it pick a random word.
The user will have 5 chances after that it should display the correct word.
I'm getting this as an error
AttributeError: 'builtin_function_or_method' object has no attribute 'choice'
from random import *
word = ['hello','bye','who','what','when','mouse','juice','phone','touch','pen','book','bag','table','pencil','day','paint','screen','floor','house','roof' ]
print("You will have 5 chances to guess the correct word! ")
rounds = 5
word = random.choice(WORDS)
correct = word
length = len(word)
length = str(length)
while tries < 5:
guess = raw_input("The word is " + length + " letters long. Guess a letter!: ")
if guess not in word:
print ("Sorry, try again.")
else:
print ("Good job! Guess another!")
tries += 1
final = raw_input ("Try to guess the word!: ")
if final == correct:
print ("Amazing! My word was ", word, "!")
else:
print("the value to guess was ",word,"\n")
Of course, this depends on how the words are stored in that file, but assuming that the words are separated by whitespace, it's easy:
with open("wordguessing.txt") as infile:
wordlist = infile.read().split()
toguess = choice(wordlist) # random.choice() chooses an item from a given iterable
Try to use random.choice instead random.randint. The second function will return a number between 0 and the len the list and not a word.
I rewrite your code just to show random.choice. There are more things to improve :)
import random
myList =['hello','bye','who','what','when','mouse','juice','phone','touch','pen','book','bag','table','pencil','day','paint','screen','floor','house','roof' ]
print("You will have 5 chances to guess the correct word! ")
rounds = 5
word = random.choice(myList)
toguess = (input("Enter word here: "))
if word == toguess:
print("Amazing! You guessed it!")
else:
print("Try again!")
print("the value to guess was ",word,"\n")
I'm in a basic programming class and I'm a bit stuck working on this game. The idea was to create a simple word-guessing game, where the computer would choose a random word and you would attempt to guess first some letter in the word, then the word itself after 5 tries. I've gone through multiple times and I still get an error of "Invalid Syntax" when I attempt to run the module.
I'm a bit dyslexic when it comes to programming languages, so maybe there's something I'm overlooking?
I would appreciate it if someone out there could offer a bit of help!
#Word Guessing Game
#Computer picks a random word
#Player tries to guess it
#computer only responds with yes or no
import random
tries = 0
print "Welcome to the word game!"
print "\nI'm going to think of a word and you have to guess it!"
print "\nGuess which letters are in the word, then you have to guess the whole thing!"
print "\nGood luck!"
WORDS = ("follow", "waking", "insane", "chilly", "massive",
"ancient", "zebra", "logical", "never", "nice")
word = random.choice(WORDS)
correct = word
length = len(word)
length = str(length)
guess = raw_input("The word is " + length + " letters long. Guess a letter!: ")
while tries < 5:
for guess in word:
if guess not in word:
print "Sorry, try again."
else:
print "Good job! Guess another!"
tries = tries + 1 #*
if tries = 5:
final = raw_input ("Try to guess the word!: ")
if final = correct:
print "Amazing! My word was ", word, "!"
else:
print "Sorry. My word was ", word, ". Better luck next time!"
raw_input("\n\nPress enter to exit")
It should also be noted that the problems occurred after the end of the "while tries" block, when I attempted to specify the limits of the "tries" variable. I've worked with it before in a random number game, but for some reason it didn't work properly here. I would greatly appreciate some help!
It should also be noted that I run on a rather outdated version of Python, some variation of 2.0, I believe.
tries = tries + 1
if tries == 5:
final = raw_input ("Try to guess the word!: ")
if final == correct:
You need == for comparison not =, = is for assignment.
You can also replace tries = tries + 1 with tries += 1
You also want to move raw_input inside the loop and just ask the user to guess the word outside the while when the guesses are all used up:
while tries < 5:
guess = raw_input("The word is " + length + " letters long. Guess a letter!: ")
if guess not in word: # use `in` to check if the guess/letter is in the word
print "Sorry, try again."
else:
print "Good job! Guess another!"
tries += 1
# guesses are all used up when we get here
final = raw_input ("Try to guess the word!: ")
if final == correct:
print "Amazing! My word was ", word, "!"
else:
print "Sorry. My word was ", word, ". Better luck next time!"
please try this one.
import random
index = -1
infi = ("python","jumble","hide","mama")
word = random.choice(infi)
word_len = len(word)
guess = ""
attempt = 0
enter = ""
print(word)
temp = "_" * word_len
print("\t\t The word chosen by computer contain", word_len,"letters.")
print("\t Tap any letter to check if this letter is in computer word.\n")
print("\t You got 5 attempts to check if tapped letter is in computer word.\n")
print("\t\t\t\t GOOD LUCK!!!\n\n\n\n")
for i in range(0, 5):
attempt +=1
guess = input("Attempt no. "+str(attempt)+":")
if guess in word and guess != enter:
for i in range(0, word_len):
if guess == word[i]:
temp = temp[:i] + guess +temp[i+1:]
print("yes\n" + temp)
if guess not in word:
print("no")
if "_" not in temp:
print("\t\t*********** Congratulation!! You guess the word *************")
break
elif attempt == 5:
guess = input("And the word is:")
if guess == word:
print("\t\t*********** Congratulation!! You guess the word *************")
else:
print("\t\t*********** WRONG!! Shame on you *************")