Reputation: 31
I'm currently creating a Hangman game in Python. In the code, the word to be guessed is written. How can I change that to a list, and have a random word be chosen?
Here is my code:
print("What's your guess?")
word = "word"
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print(char)
else:
print("_")
failed = failed + 1
if failed == 0:
print("You won")
break
guess = input("guess a character:")
guesses = guess + guesses
if guess not in word:
turns = turns - 1
print("Wrong")
print("You have", + turns, "more guesses")
if turns == 0:
print("You lost, sorry")
Upvotes: 3
Views: 114
Reputation: 1612
You can use random.choice. Just replace word = "word"
with the following:
words_to_guess = ["queueing", "strength", "sesquipedalianism"]
word = random.choice(words_to_guess)
It will pick a random word from the provided list.
As a side note, you can also improve your prints setting the end
parameter of the print
function to an empty string. Then your entire word will be printed in one line:
if char in guesses:
print(char, end="")
else:
print("_", end="")
You may want to add an empty line \n
before the "guess your character:" line then:
guess = input("\nguess a character:")
Upvotes: 2
Reputation: 628
import random
wordlist = ['word1', 'word2', 'word3']
i = random.randint(0, len(wordlist)-1)
word = wordlist[i]
Upvotes: 3