Can somebody help me with this Hangman game?
I created a word guessing game in python and would like some help. I would like the code to make it so that when the person guesses the word correctly it cuts off all the other guesses instead of showing well done then asking for another guess. I’m not actually sure how to do this so can someone help me?
so. you can use a while loop instead, which makes the code much more readable
while True: guess=input() if guess==secret: print() break else: print()
this will do the same thing but much shorter but how does it work?
creates an infinite loop, that is only exited by the "break"
now, this doesnt have a limit so if you add
count=0 while count<5: #do code count+=1
then every iteration (pass through) of the loop, count will increment by 1, and it will then automatically exit
however there is also the for loop
for x in range(5): #do code
this will run the code 5 times before exiting
range(5) is essentially the list [1,2,3,4,5] which is then iterated through, this means that you can take the value of x at any point and execute different code based on it
if 2<x<5: print()
currently you have essentially the same code copied like 5 times, this means that if you made a modificaton to the code you would have to copy and paste it
print("hi") print("hi") print("hi") print("hi")
is more annoying to change than
for x in range(4): print("hi")
the while loop makes it easier to code the logic
it isnt the answer
you have already made the logic with
print("The letter appers",SecretWord.count(Guess3),"times")
you just need to copy one of the repeating sections and put it in the loop
import random import time from termcolor import cprint Default=["ice","book","table"] Fruits=["apple","banana","pear"] Planets=["Mars","Uranus","Venus"] Animals=["rabbit","cat","fish"] name=input("What is your name?") PlayingGame=True print("Hello,welcome to hangman,",name) time.sleep(1) print("The rules are simple,the computer chooses a random word and you have to guess it") time.sleep(1) print("You can only guess one letter at a time.Remember to press enter after each answer ") time.sleep(1) print("Let the fun begin!!!") time.sleep(1) SecretWord=random.choice(Default) Category=input("What category would you like the word to be in?") if Category=="Fruits": SecretWord=random.choice(Fruits) if Category=="Planets": SecretWord=random.choice(Planets) if Category=="Animals": SecretWord=random.choice(Animals) print("The length of your word is:") print(len(SecretWord)) won=False for x in range(6): Guess=input("Make your guess: ") print("The letter appers",SecretWord.count(Guess),"times") GuessWord=input("Can you guess the word yet?") if GuessWord==SecretWord: print("WELL DONE,YOU GOT IT : )") won=True break else: if x==6: break else: print("OOPS,YOU'LL HAVE TO KEEP GUESSING LETTERS") if not won: print("OOPS,YOU LOST")
also dont copy and paste this, mainly because i havent tested it, and wrote it from my head