I am a beginner in Python and I am stuck on an exercise. In the book there is a game called Word Jumple. Here is what I need to do:
Improve “Word Jumble” so that each word is paired with a hint.
The player should be able to see the hint if he or she is stuck.
Add a scoring system that rewards players who solve a jumble without asking for the hint.
And here is what I did:
# Word Jumble
#
# The computer picks a random word and then "jumbles" it
# The player has to guess the original word
import random
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pick one word randomly from the sequence
word = random.choice(WORDS)
# create a variable to use later to see if the guess is correct
correct = word
# create a jumbled version of the word
jumble =""
hint = "False"
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
# start the game
print(
"""
Welcome to Word Jumble!
Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
print("The jumble is:", jumble)
guess = input("\nYour guess: ")
while guess != correct and guess != "":
if guess == "hint" and word == "python":
hint = "True"
print("It's a snake")
guess = input("Your guess: ")
elif guess == "hint" and word == "jumble":
hint = "True"
print("It's a game")
guess = input("Your guess: ")
elif guess == "hint" and word == "easy":
hint = "True"
print("It's type of difficulty")
guess = input("Your guess: ")
elif guess == "hint" and word == "difficulty":
hint = "True"
print("It's type of difficulty")
guess = input("Your guess: ")
elif guess == "hint" and word == "answer":
hint = "True"
print("It's the opposite of question")
guess = input("Your guess: ")
elif guess == "hint" and word == "xylophone":
hint = "True"
print("Don't know WTF is that")
guess = input("Your guess: ")
else:
print("Sorry, that's not it.")
guess = input("Your guess: ")
if guess == correct:
print("That's it! You guessed it!\n")
if hint == "False":
print("Great! You did it without a hint")
else:
print("Dat hint, man")
print("Thanks for playing.")
input("\n\nPress the enter key to exit.")
As a result I have this:
Welcome to Word Jumble!
Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
The jumble is: jbelum
Your guess: hint
Sorry, that's not it.
Your guess: jumble
That's it! You guessed it!
Great! You did it without a hint
Thanks for playing.
Press the enter key to exit.
Why the while loop is missing all when the input is "hint" and goes directly to the else clause?
Thanks in advance for your time and help.
The problem is that by the time you get to the while guess != correct and guess != "": loop, word has been completely jumbled. So in all the if and elif statements in that loop, you'll never have word equal to one of the six words in your list.
To fix this, substitute correct for word in those statements:
if guess == "hint" and correct == "python":
hint = "True"
print("It's a snake")
guess = input("Your guess: ")
elif guess == "hint" and correct == "jumble":
hint = "True"
print("It's a game")
guess = input("Your guess: ")
elif guess == "hint" and correct == "easy":
hint = "True"
print("It's type of difficulty")
guess = input("Your guess: ")
elif guess == "hint" and correct == "difficulty":
hint = "True"
print("It's type of difficulty")
guess = input("Your guess: ")
elif guess == "hint" and correct == "answer":
hint = "True"
print("It's the opposite of question")
guess = input("Your guess: ")
elif guess == "hint" and correct == "xylophone":
hint = "True"
print("Don't know WTF is that")
guess = input("Your guess: ")
else:
print("Sorry, that's not it.")
guess = input("Your guess: ")
musical_coder is right and solved your problem. Couple of more things you should change in your code to make it nicer:
Don't use strings for hint variable, use boolean:
instead:
hint = "False"
hint = "True"
use:
hint = False
hint = True
Also you can rewrite while loop a little bit to have
guess = input("Your guess: ")
only once and not in every if.
Also, change result printing a bit cause this way it's gonna print hint information even if you input empty string and quit game.
So it could look something like this:
print("The jumble is:", jumble)
guess = "dummy"
while guess != correct and guess != "":
guess = raw_input("Your guess: ")
if guess == "hint" and correct == "python":
hint = True
print("It's a snake")
elif guess == "hint" and correct == "jumble":
hint = True
print("It's a game")
elif guess == "hint" and correct == "easy":
hint = True
print("It's type of difficulty")
elif guess == "hint" and correct == "difficulty":
hint = True
print("It's type of difficulty")
elif guess == "hint" and correct == "answer":
hint = True
print("It's the opposite of question")
elif guess == "hint" and correct == "xylophone":
hint = True
print("Don't know WTF is that")
else:
print("Sorry, that's not it.")
if guess == correct:
print("That's it! You guessed it!\n")
if not hint:
print("Great! You did it without a hint")
else:
print("Dat hint, man")
print("Thanks for playing.")
input("\n\nPress the enter key to exit.")
Here is one way to make your program simpler:
jumble = ''.join(random.sample(word, len(word)))
Related
I am new to coding and want to train and do my own thing with user inputs. The User Input code does not work. It is a number guessing game. When I guess the right number, it says "Incorrect".
import random
while True:
intro = input("Hello! Want to play a game?(Y or N)")
if intro.lower() == "y" or intro.lower() == "yes":
time.sleep(0.1)
print("Let's play a number-guessing game!")
max_num_in = input("Pick a big number")
max_num = int(max_num_in)
time.sleep(0.1)
min_num_in = input("Now pick a smaller number")
min_num = int(min_num_in)
rndm_num = int(random.randrange(min_num,max_num,1))
print(rndm_num)
rndm_in = input("Guess a number between the maximum and minumum numbers!")
if rndm_num == rndm_in:
print("Whoo hoo! You did it! You guessed the number! The number was" + str(rndm_num))
elif rndm_in != rndm_num:
print("Whoops, wrong number. Please try again.(Trials left = 2)")
rndm_in1 = input("Guess again!")
if rndm_in1 == rndm_num:
print("Whoo hoo! You did it! You guessed the number! The number was" + str(rndm_num))
elif rndm_in1 != rndm_num:
print("You didn't get it right. Please try again (Trials left = 1)")
rndm_in2 = input("Guess again!")
if rndm_in2 == rndm_num:
print("Whoo Hoo! You finally did it! The number was" + str(rndm_num))
elif rndm_in2 != rndm_num:
print("Incorrect. The number was " + str(rndm_num))
elif intro.lower() == "n" or intro.lower() == "no":
print("Alright. Bye")
Your inputs are strings convert them to int by using int() function
"5"!=5
This one looks suspicious:
if rndm_num == rndm_in:
It looks like you getting a str as rndm_in but your rndm_num is an int.
Try:
if rndm_num == int(rndm_in):
I am creating a hangman game.Here are the conditions
User will be given six chances for wrong choices
If the letter was already entered, user will be notified that letter already exists (user will not be penalised for double wrong entry)
Now my question is :
I want to display the message that "user lost the game" if the number of wrong guessed letters goes to 7 and exists the loop but it is not happening
here is my code:
print("Welcome to Hangman"
"__________________")
word = "Python"
wordlist=list(word)
wordlist.sort()
print(wordlist)
print("Word's length is", len(word))
letter=" "
used_letter=[]
bad_letter=[]
guess=[]
tries=0
while len(bad_letter)<7:
while guess != wordlist or letter !="exit":
letter = input("Guess your letter:")
if letter in word and letter not in used_letter:
guess.append(letter)
print("good guess")
elif letter in used_letter:
print("letter already used")
else:
bad_letter.append(letter)
print("bad guess")
used_letter.append(letter)
tries+=1
print("You have ",6 - len(bad_letter), " tries remaining")
print(guess)
print("You have made ",tries," tries so far")
guess.sort()
print("Thank you for playing the game, you guessed in ",tries," tries.")
print("Your guessed word is", word)
print("you lost the game")
I am very new to python so i would appreciate help in basic concepts
It seems like your while len(bad_letter) < loop is never exiting because of the while loop below it which is checking for the right answer or exit entry runs forever.
What you should do is only have one master while loop which takes in a new input each time and then check to see if that input matches any of the conditions you are looking for.
You could structure it something like this:
bad_letter = []
tries = 0
found_word = False
while len(bad_letter) < 7:
letter = input("Guess your letter:")
if letter == 'exit':
break # Exit game loop
if letter in word and letter not in used_letter:
guess.append(letter)
print("good guess")
elif letter in used_letter:
print("letter already used")
else:
bad_letter.append(letter)
print("bad guess")
used_letter.append(letter)
tries+=1
print("You have ", 6 - len(bad_letter), " tries remaining")
print(guess)
print("You have made ",tries," tries so far")
guess.sort()
if guess == wordlist:
found_word = True
break # Exits the while loop
print("Thankyou for playing tha game, you guessed in ",tries," tries.")
print("Your guessed word is", word)
if found_word:
print("You won")
else:
print("you lost the game")
Solution
word = 'Zam'
guesses = []
guesses_string = ''
bad_guesses = []
chances = 6
def one_letter(message=""):
user_input = 'more than one letter'
while len(user_input) > 1 or user_input == '':
user_input = input(message)
return user_input
while chances > 0:
if sorted(word.lower()) == sorted(guesses_string.lower()):
print("\nYou guessed every letter! (" + guesses_string + ")")
break
guess = one_letter("\nGuess a letter: ")
if guess in guesses or guess in bad_guesses:
print("You already guessed the letter " + guess + ".")
continue
elif guess.lower() in word.lower():
print("Good guess " + guess + " is in the word!.")
guesses.append(guess)
guesses_string = ''.join(guesses)
print("Letters guessed: " + guesses_string)
else:
print("Sorry, " + guess + " is not in the word.")
bad_guesses.append(guess)
chances -= 1
print(str(chances) + " chances remaning.")
if chances == 0:
print("\nGame Over, You Lose.")
else:
word_guess = ''
while word_guess.lower() != word.lower():
word_guess = input("Guess the word: ('quit' to give up) ")
if word_guess.lower() == 'quit':
print("You gave up, the word was " + word.title() + "!")
break
if word_guess.lower() == word.lower():
print("\nCongratulations YOU WON! The word was "
+ word.title() + "!")
Hey there! I'm new to programming (week 2) and keep seeing these 'hangman' games popup, since today is my break from learning, I the goals you were trying to achieve and ran with it.
Added some extra features in here such as breaking the loop if the all letters are guessed, and then asking the user to guess the final word.
Notes
There is a ton of Refactoring you could do with this(almost breaks my heart to post this raw form) but I just blurted it on on the go.
Also note that my original goal was to stick to your problem of not allowing the same letter to be entered twice. So this solution only works for words that contain no duplicate letters.
Hope this helps! When I get some time I'll Refactor it and update, best of luck!
Updates
Added bad_guesses = [] allows to stop from entering bad guess twice.
I'm trying to write an if statement where if the user enters "yes" a game runs but when I cannot figure out how to do this, I can't find it online.
userName = input("Hello, my name is Logan. What is yours? ")
userFeel = input("Hello " + userName + ", how are you? ")
if userFeel == "good":
print ("That's good to hear")
elif userFeel == "bad":
print ("Well I hope I can help with that")
q1 = input("Do you want to play a game? ")
if q1 == "yes":
print ("Alright, lets begin")
import random
print ("This is a guessing game")
randomNumber = random.randint(1, 100)
found = False
yes = "yes"
while not found:
userGuess = input('Your Guess: ') ; userGuess = int(userGuess)
if userGuess == randomNumber:
print ("You got it!")
found = True
elif userGuess>randomNumber:
print ("Guess Lower")
else:
print ("Guess Higher")
elif game == "no":
print ("No? Okay")
q2 = input("What do you want to do next? ")
This is because you have named both your variable for your input "game" and your function call "game". rename one or the other and your code should work as intended.
If you are using Python2.*, You should use raw_input instead of input.
And no matter what version of Python you are using, you should not use the same name for both the function and your variable.
How do i check for a repeating input(letter) for a hangman game?
Example:
word is apple
input is Guess a letter: a
output is Well Done!
then guess next word
input is Guess a letter: a
output should be you already guess that letter.
my codes:
def checkValidGuess():
word = getHiddenWord()
lives = 10
num = ["1","2","3","4","5","6","7","8","9",]
#guessed = ''
while lives != 0 and word:
print("\nYou have", lives,"guesses left")
letter = input("Guess a letter or enter '0' to guess the word: ")
if letter.lower() in word:
print("Well done!", letter, "is in my word!")
lives -= 1
elif len(letter)>1:
print("You can only guess one letter at a time!")
print("Try again!")
elif letter in num:
print("You can only input letter a - z!")
print("Try again!")
#elif letter in guessed:
#print("repeat")
elif letter == "0":
wword = input("What is the word?").lower()
if wword == word:
print("Well done! You got the word correct!")
break
else:
print("Uh oh! That is not the word!")
lives -= 1
#elif letter == "":
#print("Uh oh! the letter you entered is not in my word.")
#print("Try again!")
else:
print("Uh oh! the letter you entered is not in my word.")
print("Try again!")
lives -= 1
Thanks.
You could store the inputs in a list, let's call it temp.
Then you could check to see if the input exists in the list when the user goes to input a new letter.
guess = input()
if guess in temp:
print "You've already guessed {}".format(guess)
else:
#do whatever you want
Here's an easy way. Start by initializing a list:
guesses = []
Then in your loop:
letter = input("Guess a letter or enter '0' to guess the word: ")
if letter in guesses:
print("Already guessed!")
continue
guesses.append(letter)
So you probably want to invert the order of your checks in your program so that you deal with the try again stuff first. Following that change, add another condition that determines if the letter matches those already guessed. This results in something like:
already_guessed = set() # I made this a set to only keep unique values
while lives > 0 and word: # I changed this to test > 0
print(f"\nYou have {lives} guesses left") # I also added an f-string for print formatting
letter = input("Guess a letter or enter '0' to guess the word: ")
if len(letter) > 1:
print("You can only guess one letter at a time!")
print("Try again!")
continue # If you reach this point, start the loop again!
elif letter in already_guessed:
print("You already guessed that!")
print("Try again")
continue
elif letter in num:
print("You can only input letter a - z!")
print("Try again!")
continue
elif letter.lower() in word:
print("Well done!", letter, "is in my word!")
lives -= 1
else:
already_guessed.update(letter)
# It wasn't a bad character, etc. and it wasn't in the word\
# so add the good character not in the word to your already guessed
# and go again!
You would need to add your other conditional branches, but this should get you there. Good luck.
How can i run a loop within a loop in python to make points in a simple word game
import random
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone", "truck", "doom", "mayonase", "flying", "magic", "mine", "bugle")
play = "Yes"
points = 0
ask = ('Yes')
word = random.choice(WORDS)
while play == "Yes":
hint = word
correct = word
jumble = ""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
print(
"""
Welcome to Word Jumble!
Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
print("The jumble is:", jumble)
guess = input("\nYour guess: ")
while guess != correct and guess != "":
print("Sorry, that's not it.")
guess = input("Your guess: ")
print("Do you want a hint")
if ask == "yes":
print(word)
points - 10
print(points)
if guess == correct:
print("That's it! You guessed it!\n")
play = input("Do you want to play again")
points + 100
print(points)
print("Thanks for playing.")
input("\n\nPress the enter key to exit.")
is all the code i have im trying to add a point system into it. The problem im trying to do is "Improve “Word Jumble” so that each word is paired with a hint. The player should be able to see the hint if he or she is stuck. Add a scoring system that rewards players who solve a jumble without asking for the hint."
Came up with something like this... needs a lot of work, but it will set you on the right track (I hope so!!)
Here's the modified code:
import random
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone", "truck", "doom", "mayonase", "flying", "magic", "mine", "bugle")
play = "Yes"
points = 0
ask = ('Yes')
word = random.choice(WORDS)
while play == "Yes":
next_hint = 4
hint = "{}...".format(word[0:next_hint])
correct = word
jumble = ""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
print(
"""
Welcome to Word Jumble!
Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
print("The jumble is:", jumble)
guess = input("\nYour guess: ")
while guess != correct and guess != "":
print("Sorry, that's not it.")
if hint != word:
ask = input("Do you want a hint? yes / no: ")
if ask in ("yes", "y", "yeah"):
print(hint)
next_hint += 1
hint = "{}...".format(correct[0:next_hint])
points -= 10
print("You lose 10 points!")
guess = input("Your guess: ")
if guess == correct:
print("That's it! You guessed it!\n")
play = input("Do you want to play again? yes/no: ")
points += 100
print("You earn {} points!".format(points))
print("Thanks for playing.")
input("\n\nPress the enter key to exit.")
I added hints that will gradually show the word and fixed the point system (Or at least it takes into account how many hints you used).
The problem is, I always show at least 4 characters of the string and some words are that short (you'll have to fix that)
Hope it helps!!!