Hangman - 3 versions




#very simple code - V1

import random
word_list = ["aardvark", "baboon", "camel", "myblog", "abs"]

chosen_word = random.choice(word_list)
guess = input("Guess a letter? >> ").lower()

for letter in chosen_word:
if letter == guess:
print("Right!")
else:
print("Wrong!")

 

#much more advanced code - V2
import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)

#Testing code
print(f'Pssst, the solution is {chosen_word}.')

display = []
word_length = len(chosen_word)
for _ in range(word_length):
display += "_"

guess = input("Guess a letter: ").lower()

for position in range(word_length):
letter = chosen_word[position]
#print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
if letter == guess:
display[position] = letter

print(display)


#much more advanced code - V3

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)

#Testing code
print(f'Pssst, the solution is {chosen_word}.')

#Create blanks
display = []
for _ in range(word_length):
display += "_"

#Useing a while loop to let the user guess again. The loop should only
stop once the user has guessed all the letters in the chosen_word
and 'display' has no more blanks ("_").
end_of_game = False

while not end_of_game:
guess = input("Guess a letter: ").lower()
#Check guessed letter
for position in range(word_length):
letter = chosen_word[position]
#print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
if letter == guess:
display[position] = letter
print(display)
#Check if there are no more "_" left in 'display'.
    #Then all letters have been guessed.
if "_" not in display:
end_of_game = True
print("You win.")







Good to read - For and IN

Comments

Popular posts from this blog

Converting student scores to grades (Dictionaries)