How to run two loops at the same time in python - python

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!!!

Related

break the game when all the every element already filled

im still learning pyhton. and i try to figure out, How can i break the game when the all i(every element) already filled.
example:
d u c k
You Win!
import random
player = input("\nnama player:")
print("Welcome to the GuesOrd game", player.title() + ".")
print("\nKategori: Hewan")
words = ["duck", "chicken", "bird", "platypus"]
word = random.choice(words)
guesses = "
chance = 10
while True:
for i in word:
if i in guesses:
print(i, end=" ")
else:
print("_", end=" ")
guess = input("\nyour guess(only input 1 aplhabet):")[0]
if guess in word:
guesses += guess
elif guess not in word:
chance -= 1
print("wrong guess. Guess again!")
print("you have " + str(chance) + " chance left!")
if chance == 0:
print("\nGame Over!")
print("The Answer Is", word)
break
Many ways to kill a cat. But off the top of my head, I'd say use something like this whenever the user enters a correct letter:
if guess in word:
guesses += guess
if sorted(guesses) == sorted(word):
print("\nYou've won!")
print("Answer is", word)
break

Spelling Game using Python

I have provided a list of words that will randomly be picked for the game. What it does is to prompt the player to enter an alphabet of the selected word. If the letter provided by the users is found in the selected word, they if be asked if they want to attempt spelling the whole word. if they say yes, then they will be able to do so. Else, they will have to try entering another alphabet.how do I get the output/ results of each user input to be printed as (eg: Outcome: a------) And if the users ended up saying yes to spelling the whole word, how should they be prompt to enter the word?
eg: Do you want spell the word now? (y/n): y
Spell the complete word:
You are correct!
The correct word is albumen
Spell another word? (y/n): y
import random
wordList = ('apple', 'albumen', 'toothpaste', 'enthusiastic')
word = random.choice(wordList)
letter_guess = ""
word_guess = ""
store_letter = ""
count = 1
limit = 5
countLetters = len(word)
choice1 = ("Do you want to spell the word now? (y/n):")
choice2 = ("Spell another word? (y/n):")
choiceY = ("y")
choiceN = ("n")
startGame = print("The word ________ has {} letters. Spell it in 5 tries.".format(countLetters))
while count < limit:
letter_guess = input("Try {} - Current: ________. Your guess? ".format(count))
if letter_guess in word:
print ("yes")
print (input(choice1))
else :
print("no")
count += 1
if choice1 == choiceY:
print (input("Spell the complete word: "))
else:
print (letter_guess)
store_letter += letter_guess
count += 1
while count == limit:
spellFinal = input("Spell the complete word: ")
if spellFinal in word:
print ("You are correct!")
print ("Spell another word? (y/n):")
if choice == "y":
print (startGame)
else:
print('Remaining Words are: ', store_letter)
if spellFinal not in word:
print ("You are incorrect")
print ("The correct word is {}.".format(correct))
You are not collecting the information from your print (input(choice1)) line. You should be assigning it to a variable to be able to compare it later with your choiceY (or you could simply compare the new variable to "y" without having a choiceY variable defined, up to you).
For example:
user_choice = ""
complete_word = ""
if letter_guess in word:
print ("yes\n")
user_choice = input(choice1)
if user_choice.lower() is "y":
complete_word = input("Spell the complete word: ")
#here you compare complete_word with your word variable
else:
print (letter_guess)
store_letter += letter_guess
count += 1
else:
print("no\n")
count +=1
The same applies to the other sections of you code that have the print(input(...)).
Nested ifs can get messy. Perhaps you can consider having a verification function and call that instead.
Hope this helps!

Nested While loop in hangman

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.

While loop initiating when I dont want it to

I'm going over the formatting of the while loop and I remain unsure (I'm a beginner- forgive me) of how I can go about fixing this. Any assistance would be greatly appreciated! I do not want the 'Sorry that's not it' message to pop up when the user asks for a hint- and yet it persists in doing just that.
# 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)
hint = ''
if word == 'python':
hint = 'snake'
if word == 'jumble':
hint = 'jumble'
if word == 'easy':
hint = 'opposite of hard'
if word == 'difficult':
hint = 'opposite of easy'
if word == 'answer':
hint = 'question'
if word == 'xylophone':
hint = 'dingding'
# create a variable to use later to see if the guess is correct
correct = word
# create a jumbled version of the word
jumble =""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
count = 0
# 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 != "":
print("Sorry, that's not it.")
count += 1
hint_input = input('would you like a hint')
if hint_input == 'y':
print(hint)
else:
guess = input("Your guess: ")
if guess == correct:
print("That's it! You guessed it!\n")
print("Thanks for playing.")
input("\n\nPress the enter key to exit.")
Remove the else: since you always wish to get a new guess from the user, regardless of if they've received a hint.
if hint_input == 'y':
print(hint)
guess = input("Your guess: ")
Your code works fine - but you are expected to enter a string including the " or ' in the input field. So enter "jumble" and not just jumble or "y" and not just y.
(well, there is some strange logic in there, e.g. after giving a hint it asks once more whether you want a hint - jus remove the else to get rid of this behaviour) but at least it works...)
I've copied your code and ran it.
I changed input to raw_input, which makes input much nicer.
Removed else: after print(hint) , which should fix your problem.
Lastly, I've added extra space after "Would you like a hint? " - makes it a bit easier to read.
# 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)
hint = ''
if word == 'python':
hint = 'snake'
if word == 'jumble':
hint = 'jumble'
if word == 'easy':
hint = 'opposite of hard'
if word == 'difficult':
hint = 'opposite of easy'
if word == 'answer':
hint = 'question'
if word == 'xylophone':
hint = 'dingding'
# create a variable to use later to see if the guess is correct
correct = word
# create a jumbled version of the word
jumble =""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
count = 0
# 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 = raw_input("\nYour guess: ")
while guess != correct and guess != "":
print("Sorry, that's not it.")
count += 1
hint_input = raw_input('would you like a hint? ')
if hint_input == 'y':
print(hint)
guess = raw_input("Your guess: ")
if guess == correct:
print("That's it! You guessed it!\n")
print("Thanks for playing.")
raw_input("\n\nPress the enter key to exit.")

Need explanation on a while loop in Python

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)))

Categories