Creating a guessing game in Python using while and for loops - python

I am trying to make a guess game. I've used while, if, elif, and else statements but I'm stuck on how to use for and while loops as well as randomizing single hints and single answers from a nested lists.
black_box = ["guam","lakers","flash","buddha","drake","fortnite","annabelle","xmen","mars","dad"]
nested_list = [["island","yigo","cocos","kelaguen"],["kobe","la","magic","lebron"],["scarlet","speedster","dc","ezra"], ["asiangod","meditation","monk","enlightenment"],["rapper","onedance","canadian","raptors"],["game","epic","notminecraft","dances"],["doll","conjuring","soultaker","creation"],["wolverine","mystique","magneto","apocalypse"],["red","fourth","planet","ares"], ["man","american","peter","lionking"]]
i = random.randint(0,9)
word = black_box[i]
hint = nested_list[i]
print("Guess the word with the following hint: ", hint, "you have 4 tries.")
numofguesses = 0
guess = input("What is the word? ")
while numofguesses < 4:
numofguesses = numofguesses + 1
if guess == word:
print("You win!")
option = input("Do you want to try again or quit? ")
if option == "try again":
print("")
elif option == "quit":
break
if guess != word:
print("Try again!")
guess = input("What is the word? ")
if guess != word:
print("Try again!")
guess = input("What is the word? ")
I expected to get a line of code that prints "Try again!" but it skipped and started to print "What is the word? " print("Guess the word with the following hint: ", hint, "you have 4 tries.") Originally, I used hint[i] which printed out only one hint in the nested list but then I tried to run the program again but I got an error saying, "list index is out of range.

Your condition checks and loops where not correct. Try the below code, it should work fine.
black_box = ["guam","lakers","flash","buddha","drake","fortnite","annabelle","xmen","mars","dad"]
nested_list = [["island","yigo","cocos","kelaguen"],["kobe","la","magic","lebron"],["scarlet","speedster","dc","ezra"], ["asiangod","meditation","monk","enlightenment"],["rapper","onedance","canadian","raptors"],["game","epic","notminecraft","dances"],["doll","conjuring","soultaker","creation"],["wolverine","mystique","magneto","apocalypse"],["red","fourth","planet","ares"], ["man","american","peter","lionking"]]
while True:
i = random.randint(0, 9)
word = black_box[i]
numofguesses = 0
while numofguesses < 4:
hint = nested_list[i][numofguesses]
print("Guess the word with the following hint: ", hint, ". You have ", 4 - numofguesses, " tries!")
guess = input("What is the word? ")
numofguesses = numofguesses + 1
if guess == word:
print("You win!")
break
if guess != word:
print("Try again!")
option = input("Do you want to try again or quit? ")
if option == "try again":
print("")
else:
break

Related

I'm trying to create a guessing game but when I run my code, nothing happens

I'm currently new to programming so I'm trying to create a guessing game as practice but I don't know what I did wrong.
secret_word = "Giraffe" or "giraffe"
guess_word = ""
failed = False
guess_count_limit = 3
guess_count = 0
while guess_word != secret_word and not failed:
if 1 < guess_count:
guess = input("Guess the animal I'm thinking of: ")
guess_count += 1
elif 2 < guess_count:
print("Incorrect but here's a hint: ")
print("It's common in Africa. ")
print("Two guesses left.")
guess = input("Now try again: ")
guess_count += 1
elif 3 < guess_count:
print("Incorrect but here's your last hint: ")
print("It's tall. ")
print("One guess left")
guess = input("Now try again: ")
elif guess_count == guess_count_limit:
print("Nope, out of guesses.")
failed = True
if failed:
print("You win")
else:
print("Wow, you really lost huh.")
When I try to run this program, nothing happens.
This version will work:
secret_word = "giraffe"
guess_word = ""
guess_count_limit = 3
guess_count = 0
while guess_word.lower() != secret_word and guess_count < guess_count_limit :
if 1 > guess_count:
guess_word = input("Guess the animal I'm thinking of: ")
guess_count += 1
elif 2 > guess_count:
print("Incorrect but here's a hint: ")
print("It's common in Africa. ")
print("Two guesses left.")
guess_word = input("Now try again: ")
guess_count += 1
elif 3 > guess_count:
print("Incorrect but here's your last hint: ")
print("It's tall. ")
print("One guess left")
guess_word = input("Now try again: ")
elif guess_count == guess_count_limit:
print("Nope, out of guesses.")
print("Wow, you really lost huh.")
if guess_word.lower() == secret_word :
print("You win")
you made 3 mistakes:
secret_word = "Giraffe" or "giraffe"
As far as I know logical operators does not work with strings. However, you do not need 2 words with different letter cases, you need only one and then change the case of the guesses to check.
when you took the input you stored in guess but in the loop you are comparing guess_word with secret_word!!
you had a problem inside the loop in the condition statements, try to figure it out in order to learn and become better.
good luck!

I created a guessing game and I can't understand why my -= command function doesn't work

I'm a very new programmer(started less than a month ago). I really need some help with this.
Sorry if it's a bit long...
How this works is that my guesses go down every time I get something wrong(pretty obvious). Or it is supposed to, anyway.
This is a program I created as a prototype for a hangman project. Once I get this right, I'll be able to attempt the bigger project. Tell me if the full command above works differently for you or if you have any suggestion as to how to make it shorter or better or it's too early for me to attempt a project as big as this. Thank you!
import random
player_name = input("What is your name? ")
print("Good luck, " + player_name + "!")
words = ["program", "giraffe", "python", "lesson", "rainbows", "unicorns", "keys", "exercise"]
guess = " "
repeat = True
word = random.choice(words)
guesses = int(len(word))
while repeat is True:
print("The word is " + str(len(word)) + " characters long.")
guess = input("Enter your guess: ")
if guess != word:
guesses -= 1
print("Incorrect")
print("Try again")
elif guess == word:
print("Good job!")
print(str.capitalize(word) + " is the right answer!")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
word = random.choice(words)
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
if guesses == 1:
print("You only have one chance left.")
if guesses <= 0:
print("You lose...")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
the issue is with the scope of your conditionals
while repeat is True:
print("The word is " + str(len(word)) + " characters long.")
guess = input("Enter your guess: ")
if guess != word:
guesses -= 1
print("Incorrect")
print("Try again")
elif guess == word:
print("Good job!")
print(str.capitalize(word) + " is the right answer!")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
word = random.choice(words)
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
if guesses == 1:
print("You only have one chance left.")
if guesses <= 0:
print("You lose...")
repeat = input("Do you want to play again? (input Yes/No)")
if repeat == "Yes" or "yes":
repeat = True
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False
this will fix the guesses issue, but you'll need to refactor the play-again logic.
Something like this
repeat = True
gameOver = False
while repeat is True:
print("The word is " + str(len(word)) + " characters long.")
guess = input("Enter your guess: ")
if guess != word:
guesses -= 1
print("Incorrect")
print("Try again")
elif guess == word:
print("Good job!")
print(str.capitalize(word) + " is the right answer!")
gameOver = True
if guesses == 1:
print("You only have one chance left.")
if guesses <= 0:
print("You lose...")
gameOver = True
if gameOver:
playAgain = input("Do you want to play again? (input Yes/No)")
if playAgain == "Yes" or "yes":
word = random.choice(words)
repeat = True
gameOver = False
elif repeat == "No" or "no":
print("Better luck next time!")
repeat = False

Breaking a loop for basic python

I have been working on this for a while now. I have been able to get parts of this to work, but never the whole thing. The end goal is to loop the user back into another game if they so choose. I think the issue is with my break statement, but I am not sure how to route around it. I have included all my code so that any mistakes can be found. Apologies if this has already been answered, I couldn't find a page with this kind of problem.
def game():
import random
from random import randint
n = randint(1, 10)
print('Enter a seed vlaue: ')
the_seed_value = input(' ')
random.seed(the_seed_value)
guessesTaken = 0
print("what is your name?")
myName = input("")
guess = int(input("Enter an integer from 1 to 99: "))
while n != "guess":
if guess < n:
print ("guess is low")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
elif guess > n:
print ("guess is high")
guessesTaken = guessesTaken + 1
guess = int(input("Enter an integer from 1 to 99: "))
else:
print ("Congradulations " + myName + " you guessed it in " + str(guessesTaken) + " guesses!")
break
print('Want to play agian? y/n')
answer = input(" ")
if answer == "n":
print ("Ok, See you next time!")
elif answer == "y":
print("Starting new game!")
game()
def main():
game()
if __name__ == "__main__":
main()
For one, #kerwei notes correctly that your while line has an issue, and needs to be changed from while n != "guess": to while n != guess:.
For two, your while loop is satisfied when the player guesses correctly, bypassing the Congrats line.
Since the game is currently structured to stay in the loop until the player guesses correctly, a simple fix would be to remove the else: line from the loop and place the victory statement afterwards. That is,
def game()
...
while n != guess:
if guess < n:
...
elif guess > n:
...
print('Congrats!')
print('play again?')
...

Converting a list of ints into something compatible with locations in another list While creating a Hangman game

I've been working on hangman project recently, I have used enumerate to get the locations of a letter that's been guessed so i can put it into a list, but when i try and put it into "guess" list, it comes up with:
Edit: I do understand that you cannot simply change an entire list into a series of ints by doing int(list), it's simply a place holder
Here is my code
import random
lines = []
with open('words.txt', 'r') as f:
for line in f:
line = line.strip()
lines.append(line)
choice = random.choice(lines)
#print("it says", choice)
guessed = False
print("Your word is", len(choice), "letters long!")
answer = ["_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"]
wrong = 0
= 1
print(choice)
while not guessed:
guess = input("Guess a letter!")
#location = choice.find(guess)
location = [i for i, a in enumerate(choice) if a == guess]
print(location)
if wrong == 6:
print("Sorry, you have killed yourself.")
guessed = True
elif not location:
wrong += 1
print("Sorry, that was not part of the word!")
print("You have", (6 - wrong), "guesses left")
elif right == len(choice):
answer[int(location)] = guess
print(answer[0:len(choice)])
print("Congratulations! You have won!")
guessed = True
else:
right += 1
answer[location] = guess
print(answer[0:len(choice)])
Your code has other issues beyond this but as your question at hand, it is here:
elif right == len(choice):
answer[int(location)] = guess
print(answer[0:len(choice)])
print("Congratulations! You have won!")
guessed = True
else:
right += 1
answer[location] = guess
print(answer[0:len(choice)])
Your two statements answer[int(location)] = guess and answer[location] = guess if you print location it is a list, for a 4 letter word example vash, location is a list of range [0,3] you are attempting to pass the entire list as an index which will not work regardless if you convert it to int or not.
Please try this modification, this is not a full solution, I do not want to take away from your journey on this project but this will get your moving:
import random
lines = ['hey', 'this', 'that']
choice = random.choice(lines)
#print("it says", choice)
guessed = False
print("Your word is", len(choice), "letters long!")
answer = ["_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_","_"]
wrong = 0
right = 0
print(choice)
while not guessed:
guess = input("Guess a letter!")
#location = choice.find(guess)
if wrong == 6:
print("Sorry, you have killed yourself.")
guessed = True
elif guess not in choice:
wrong += 1
print("Sorry, that was not part of the word!")
print("You have", (6 - wrong), "guesses left")
elif right == len(choice):
print(answer)
print("Congratulations! You have won!")
guessed = True
else:
right += 1
answer[choice.index(guess)] = guess
print(answer[0:len(choice)])

Hangman drawing regardless of correct letters (Python, turtle)

I'm creating a hangman game in Python 3.5.1 and everything is going well except for when it comes to the guessing part. I print "Hurray" when the letter is guessed correctly and I have it draw an additional body part when it is not guessed correctly. My problem is that even when a letter is guessed correctly it will also draw another body part:
import drawHangman
import turtle
import random
def main():
window = turtle.Screen()
window.setup(400, 400, 200, 200)
HG = turtle.Turtle()
drawHangman.default(HG)
wrongGuess = 0
maxGuesses = 0
lines = open('wordlist.txt').read().splitlines()
myline =random.choice(lines)
print(myline)
name = input("Welcome to hangman! What is your name? \n")
print("Welcome", name + "! \n The rules are as follows: \n 1) No looking at answer list! \n 2) Do not have fun!! \n 3) No hacking my game!")
tos = input("Do you accept the rules provided above? Type Yes or No. \n")
if tos == "no":
print("Who cares! The rules suck anyways!")
elif tos == "yes":
print("HI")
else:
print("You don't listen very well. I guess proceed ugh")
while maxGuesses < 6:
guess = input("Please input your guess!")
maxGuesses += 1
for char in myline:
if char in guess:
print("Hurray")
else:
wrongGuess += 1
print("You have", 6 - maxGuesses, "guesses left!")
if wrongGuess == 1:
drawHangman.drawHead(HG)
elif wrongGuess == 2:
drawHangman.drawBody(HG)
elif wrongGuess == 3:
drawHangman.drawLeftArm(HG)
elif wrongGuess == 4:
drawHangman.drawRightArm(HG)
elif wrongGuess == 5:
drawHangman.drawLeftLeg(HG)
elif wrongGuess == 6:
drawHangman.drawRightLeg(HG)
else:
playAgain = input('Do you want to play again? (yes or no)')
if playAgain == "yes":
drawHangman.reset(HG)
main()
else:
print("Thanks for playing!")
return
main()
I know it has something to do with the part where else tells it there is a wrong letter but I can't figure it out. I've tried indenting it one more space, but that just prints the amount of guesses left. Any help is appreciated.
PS. The drawHangman.* routines come from a file I have in my src folder that contains body parts.
You have indented the else clause (and the following lines) incorrectly - it's in the scope of the for loop instead of the if statement:
for char in myline:
if char in guess:
print("Hurray")
else:
wrongGuess += 1
print("You have", 6 - maxGuesses, "guesses left!")
if wrongGuess == 1:
drawHangman.drawHead(HG)
# etc.
As you wrote it, the else clause and all the drawings are executed only after the entire for loop has finished.
Besides the problem raised in your question, there seem to be other issues with your code: your logic assumes/hardcodes 6 letter words; you're repeat game logic is actually recursive; you don't close the words file after you're finished with it; your yes/no question handling isn't robust; you repeat things, by recalling main(), that need only be done once; you don't display the current correct/unknown letter status.
Below is a rework of your code to address these issues and play an actual game of hangman:
from turtle import Turtle, Screen
import random
import drawHangman
BODY_PARTS = [ \
drawHangman.drawHead, drawHangman.drawBody, drawHangman.drawLeftArm, \
drawHangman.drawRightArm, drawHangman.drawLeftLeg, drawHangman.drawRightLeg, \
]
MAXIMUM_WRONG_GUESSES = len(BODY_PARTS)
def hangman(HG):
drawHangman.default(HG)
with open('wordlist.txt') as file:
lines = file.read().splitlines()
word = random.choice(lines)
letters = set(word)
wrongGuesses = 0
while letters and wrongGuesses < MAXIMUM_WRONG_GUESSES:
for letter in word:
print("*" if letter in letters else letter, end="")
print(".")
letter = input("Please input your guess: ")
if letter in letters:
print("Hurray!")
letters.remove(letter)
else:
BODY_PARTS[wrongGuesses](HG)
wrongGuesses += 1
print("You have", MAXIMUM_WRONG_GUESSES - wrongGuesses, "guesses left!")
def main():
screen = Screen()
screen.setup(400, 400, 200, 200)
turtle = Turtle()
playAgain = True
print("Welcome to hangman!")
name = input("Enter your name: ")
print("Welcome", name + "!")
print("The rules are as follows:")
print(" 1) No looking at answer list!")
print(" 2) Do not have fun!!")
print(" 3) No hacking my game!")
tos = input("Do you accept the rules provided above? (yes or no): ")
if tos.lower().startswith("n"):
print("Who cares! The rules suck anyways!")
elif tos.lower().startswith("y"):
print("Hi")
else:
print("You don't listen very well. I guess proceed ugh")
while playAgain:
hangman(turtle)
answer = input('Do you want to play again? (yes or no): ')
playAgain = answer.lower().startswith("y")
if playAgain:
drawHangman.reset(turtle)
else:
print("Thanks for playing!")
main()

Categories

Resources