current code -
string = input("Enter word")
guessed= False
alphabet = 'abcdefghijklmnopqrstuvwxyz'
guesses=[]
while guessed== False:
char = input("Enter one letter :").lower()
if len(char) == 1:
if char not in alphabet:
print("Error you have not entered a letter")
elif char in guesses:
print("Letter has been guessed before")
elif char not in string:
print("Sorry this letter is not part of the word")
guesses.append(char)
elif char in string:
print("Well done")
guesses.append(char)
else:
print("Error")
else:
print("Only 1 character should be entered")
status= ''
if guessed == False:
for letter in string:
if letter in guesses:
status+=letter
if status==string:
print("Congratulations you have won")
guessed=True
else:
status+='_'
print(status)
If the word is "hello world" and the user guessed the words correctly the output below is displayed:
Well done
hello_world
Enter one letter :
The user is asked again to enter another letter even though the word is found. Im not sure on how to fix this.
I would add an extra condition for spaces like this
for letter in string:
if letter in guesses:
status+=letter
if status==string:
print("Congratulations you have won")
guessed=True
elif letter == ' ':
status += ' '
else:
status+='_'
This way the user sees that there are actually two words but does not have to enter a space explicitly.
Output
Enter one letter :h
Well done
h____ _____
Enter one letter :e
Well done
he___ _____
...
Enter one letter :d
Well done
Congratulations you have won
hello world
hello world contains a space, and yet space is not allowed as a guessed letter, so even if the user guesses all the right letters, the status will at best become hello_world, which is not equal to hello world, leaving the game unfinished.
Related
I am creating a guess a letter game in python. the program chooses a random word from a file and the user has the amount of letters to guess the letters to the word. There is one part I am having trouble coding. I need to display the word as dashes and after every guess change the dashed word to include the correctly guessed letters in their corresponding position. So the output looks something like this.
Welcome to Guess a Letter!
Your word has 10 letters
You have 10 incorrect guesses.
Here is the word:
Enter a letter: e
Awe, shucks. You missed with that letter
Enter a letter: a
You got a hit! Here's what the word looks like now:
-------a-a
Enter a letter: o
Awe, shucks. You missed with that letter
Enter a letter: u
Awe, shucks. You missed with that letter
Enter a letter: i
You got a hit! Here's what the word looks like now:
---i---a-a
Enter a letter: y
You got a hit! Here's what the word looks like now:
-y-i---a-a
Enter a letter: t
You got a hit! Here's what the word looks like now:
-y-i-t-ata
Enter a letter: l
You got a hit! Here's what the word looks like now:
ly-i-t-ata
Enter a letter: s
You got a hit! Here's what the word looks like now:
lysist-ata
Enter a letter: r
You got a hit! Here's what the word looks like now:
lysistrata
You won!
Great job!
so here is what i have so far
import random
def pick_word_from_file():
'''Read a file of words and return one word at random'''
file = open("wordlist.txt", 'r')
words = file.readlines()
file.close()
global word #globalizes the variable "word"
word = random.choice(words).strip("\n")
global guesses
guesses = len(word) #number of guesses user has according to number of letters
print(word)
def dashed_word(): #this function turns the word into dashes
global hidden_word #globalizes the variable "hidden_word"
hidden_word = ""
for letter in word: #this for loop changes all the letters of the word to dashes
if letter != " ":
hidden_word = hidden_word + "-"
print(hidden_word)
list(hidden_word)
def game_intro(): #introduces word game rules
print("Welcome to Guess a Word!\n")
print("Your word has",len(word),"letters")
print("You have",len(word),"incorrect guesses.")
print("Only guess with lower case letters please!")
def game(): #this is the main games function
global guess
for letter in range(len(word)):
guess = input("Please enter a lowercase letter as your guess: ") #asks user for lowercase letter as their guess
new_hidden_word = ''
random_int = 0
int(random_int)
for i in range(len(word)):
if guess == word[i:i+1]:
print("Lucky guess!")
print(guess, "is in position", i+1)
hidden_word[i] = guess
hidden_word.join(' ')
print(hidden_word)
random_int = 1
if random_int == 0:
print("Unlucky")
def main(): #this runs all the functions in order
pick_word_from_file()
game_intro()
dashed_word()
game()
main()
Just need help with what is in the game() function
Since strings a immutable, I would use a list to keep track of the guesses and then transfer that to a string in order to print it out. Here is your code modified to reflect those changes :
import random
def pick_word_from_file():
'''Read a file of words and return one word at random'''
file = open("wordlist.txt", 'r')
words = file.readlines()
file.close()
global word #globalizes the variable "word"
word = random.choice(words).strip("\n")
global guesses
guesses = len(word) #number of guesses user has according to number of letters
print(word)
def dashed_word(): #this function turns the word into dashes
global hidden_word #globalizes the variable "hidden_word"
hidden_word = []
for letter in word: #this for loop changes all the letters of the word to dashes
if letter != " ":
hidden_word.append ("-")
print_out = ''
print(print_out.join (hidden_word))
def game_intro(): #introduces word game rules
print("Welcome to Guess a Word!\n")
print("Your word has",len(word),"letters")
print("You have",len(word),"incorrect guesses.")
print("Only guess with lower case letters please!")
def game(): #this is the main games function
global guess
for letter in range(len(word)):
guess = input("Please enter a lowercase letter as your guess: ") #asks user for lowercase letter as their guess
new_hidden_word = ''
random_int = 0
int(random_int)
for i in range(len(word)):
if guess == word[i:i+1]:
print("Lucky guess!")
print(guess, "is in position", i+1)
hidden_word[i] = guess
print_out = ''
print(print_out.join (hidden_word))
random_int = 1
if random_int == 0:
print("Unlucky")
def main(): #this runs all the functions in order
pick_word_from_file()
game_intro()
dashed_word()
game()
main()
I group all functions into one so we don't need to declare global variables. I also add something:
use .lower() to accept uppercase input
a statement telling user how many guesses left
win and lose condition
import random
def game():
# pick_word_from_file()
# using with to close the file automatically
with open("wordlist.txt") as f:
wordlist = f.readlines()
word = random.choice(wordlist).strip("\n")
# game_intro()
print("Welcome to Guess a Word!\n")
print("Your word has", len(word), "letters")
# why we need to say incorrect guesses from the start?
# print("You have", len(word), "incorrect guesses.")
# dashed_word()
# use a list to save letters because string is immutable
hidden_word = ["-" for w in word]
print("".join(hidden_word))
# number of guesses equal to length of word
for guesses in range(len(word)):
# tell user how many guesses left
print(f"You have {len(word) - guesses} guesses left.")
# use .lower() so user can also input uppercase letter
guess = input("Please enter a letter as your guess: ").lower()
change = False
for i in range(len(word)):
if word[i] == guess:
hidden_word[i] = guess
change = True
if change:
print("You got a hit! Here's what the word looks like now:")
print("".join(hidden_word))
else:
print("Awe, shucks. You missed with that letter.")
if "".join(hidden_word) == word:
print("You won! Great job!")
break
# you lose when you are out of guesses
else:
print("You lose.")
game()
Output:
"""
Welcome to Guess a Word!
Your word has 10 letters
----------
You have 10 guesses left.
Please enter a letter as your guess: E
Awe, shucks. You missed with that letter.
You have 9 guesses left.
Please enter a letter as your guess: A
You got a hit! Here's what the word looks like now:
-------a-a
You have 8 guesses left.
Please enter a letter as your guess: O
Awe, shucks. You missed with that letter.
You have 7 guesses left.
Please enter a letter as your guess: U
Awe, shucks. You missed with that letter.
You have 6 guesses left.
Please enter a letter as your guess: I
You got a hit! Here's what the word looks like now:
---i---a-a
You have 5 guesses left.
Please enter a letter as your guess: Y
You got a hit! Here's what the word looks like now:
-y-i---a-a
You have 4 guesses left.
Please enter a letter as your guess: T
You got a hit! Here's what the word looks like now:
-y-i-t-ata
You have 3 guesses left.
Please enter a letter as your guess: L
You got a hit! Here's what the word looks like now:
ly-i-t-ata
You have 2 guesses left.
Please enter a letter as your guess: S
You got a hit! Here's what the word looks like now:
lysist-ata
You have 1 guesses left.
Please enter a letter as your guess: R
You got a hit! Here's what the word looks like now:
lysistrata
You won! Great job!
"""
i would like to know how to put limit on how many character can player put
thinking to limit it by one letter per answer.
it's a guessing game but the computer can only answer yes or no.
five chances to guess a letter.
then need to guess the right word after 5 tries.
import random
words = dict(
helium = "type of element",
korea="a country in asia",
peugeot="brand of a car",
bournemouth="a good place for holiday")
word=list(words)
choice=random.choice(word)
x=list(choice)
score=0
chance=5
print("\n\n\t\t\t WELCOME TO GUESSING GAME")
print("\t\t\tYOU HAVE 5 CHANCES TO GUESS THE WORD")
print("\nit has a", len(choice),"letters word")
print("and this is a clue", (words[choice]))
while word:
guess = input("is there a letter :")
if guess in choice:
print("yes")
else:
print("no")
score +=1
if score == chance:
print("time to guess the right word")
guess = input("and the word is :")
if guess == choice:
print("well done you guess the right word which is ", choice.upper())
break
else:
print("better luck next time the right word is ", choice.upper())
break
Hope this is what you want:
First you should make a new function:
def own_input(text=""):
user_input = ""
# While the length of the input string is not 1
while len(user_input) != 1:
# Ask user for input with message
user_input = input(text)
Now you can use it like this:
a = own_input("Character: ")
This is my first time on this site and am new to programming. I need the user to be able to input another word if they say "y". As of now the program sends them back to the while statements. Any advice would be appreciated.
print('Welcome to Word Madness!!')
vowels = list('aeioyu')
consonants = list('bcdfghjklmnpqrstvwxz')
wordCount = 0
complete = False
while not complete:
mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()
print('You chose to enter: ',str(mode))
#When user chooses to quit program will system exit
if mode == 'quit':
print('Sorry to see you go! Come back to Word Madness soon!')
import sys
sys.exit(0)
#If vowels are selected then they will be counted
if mode == 'vowels':
word = input('Please enter your word!')
number_of_vowels = sum(word.count(i) for i in vowels)
print('Your word was : ',word,'Your Vowel count was: ',number_of_vowels)
wordCount = wordCount + 1
choice = input('Do you have another word? Y/N: ').lower().strip()
if choice == 'n':
averageV = int(number_of_vowels // wordCount)
print('Your average number of Vowels was: ',averageV)
print('Thank you for using Word Madness!')
complete = True
else:
mode = 'vowels'
#If consonants are selected then they will be counted
elif mode == 'consonants':
word = input('Please enter your word!')
number_of_consonants = sum(word.count(i) for i in consonants)
print('Your word was : ',word,'Your Consonant count was: ',number_of_consonants)
wordCount = wordCount + 1
choice = input('Do you have another word? Y/N: ').lower().strip()
if choice =='n':
averageC = int(number_of_consonants // wordCount)
print('Your average number of Consonants was: ',averageC)
print('Thank you for using Word Madness!')
complete = True
#If user has no more words to enter then they are given an average
else:
mode == 'consonants'
else:
print('ERROR! INVALID INPUT DETECTED!')
From your question and the comment, I assume that you want to ask
mode = input('Would you like to type Vowels, Consonants, or Quit?: ').lower().strip()
only once. If that is the case, you can move that statement just above the while loop.
Or also, you can give an option whether user really wants to specify the mode again.
Ok,for what I understood you don't know how to go back in the code. For this you should learn how to use functions in Python.
What is a function?
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. (Definition taken from internet)
So I would suggest you to find more about functions, because it's very useful.
After learning functions you should add that:
After every
if choice =='n':
averageC = int(number_of_consonants // wordCount)
print('Your average number of Consonants was: ',averageC)
print('Thank you for using Word Madness!')
complete = True
Add
elif choice == 'n':
function()
Function() --> Calling the main function.
Question:
The hand is displayed.
The user may input a word or a single period (the string ".")
to indicate they're done playing
Invalid words are rejected, and a message is displayed asking
the user to choose another word until they enter a valid word or "."
When a valid word is entered, it uses up letters from the hand.
After every valid word: the score for that word is displayed,
the remaining letters in the hand are displayed, and the user
is asked to input another word.
The sum of the word scores is displayed when the hand finishes.
The hand finishes when there are no more unused letters or the user inputs a "."
hand: dictionary (string -> int)
wordList: list of lowercase strings
I am trying to write a code for my Python programming online course. However, I am getting an error :
ERROR: Failed to display hand correctly - be sure 'Current Hand' and the display of the hand are on the same line!
Here is my code :
def playHand(hand, wordList, n):
total = 0
while True:
print("\nCurrent Hand:",)
displayHand(hand)
entered = input('Enter word, or a "." to indicate that you are finished: ')
if entered == '.':
print ("Goodbye! Total score: " + str(total) +" points.")
break
if isValidWord(entered, hand, wordList) == False:
print ("Invalid word, please try again.")
else:
total += getWordScore(entered, n)
print (str(entered), "earned", getWordScore(entered,n), "points. Total:", str(total))
hand = updateHand(hand, entered)
if calculateHandlen(hand) == 0:
print ("\nRun out of letters. Total score: " + str(total) +" points.")
break
The answer is in your code already:
def displayHand(hand):
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print() # print an empty line
Use end=" " in your print statement!!
the second "else" statement gives a syntax error. I don't understand why. what is wrong with the code?
Pardon me, still a beginner
while True:
guess = input("Guess a letter or the whole word: ")
if guess == word:
print("Yaye, you've won and have saved my neck!")
break
else:
for letter in letters:
if letter in letters:
continue
else:
guesses -= 1
word_guess(guesses)
if guesses == 0:
break
You can see in the Python 3 flow control documentation an example of an if statement. It can only have one else statement because that is what is run when all other cases (if and elif) didn't match. When are you expecting the second else to run?
As was pointed out in another answer, indentation in python matters.
Is this perhaps the indentation you are looking for?
while True:
guess = input("Guess a letter or the whole word: ")
if guess == word:
print("Yaye, you've won and have saved my neck!")
break
else:
for letter in letters:
if letter in letters:
continue
else:
guesses -= 1
word_guess(guesses)
if guesses == 0:
break