import random
from Words import words
import string
def get_valid_word(words):
word = random.choice(words)
while '-' or ' ' in word:
word = random.choice(words)
return word.upper()
def hangman() -> object:
word = get_valid_word(words)
word_letter = set(word)
alphabet = set(string.ascii_uppercase)
used_letter = set()
while len(word) > 0:
print("You have used these letter", ' '.join(used_letter))
word_list = [letter if letter in used_letter else '-' for letter in word]
print("Current word: ", ' '.join(word_list))
user_letter = input("Guess a letter: ")
if user_letter in alphabet - used_letter:
used_letter.add(user_letter)
if user_letter in word_letter:
word_letter.remove(user_letter)
elif user_letter in used_letter:
print("You have already used this letter: ")
else:
print("Invalid input")
if __name__ == '__main__':
hangman()
I can't bring code to execute function hangman(). Terminal only shows the following output:
/Users/nighttwinkle/PycharmProjects/pythonProject/venv/bin/python
/Users/nighttwinkle/PycharmProjects/pythonProject/main.py
The issue appears to be with the line
while '-' or ' ' in word:
your syntax is slightly off meaning that this will always evaluate to True and thus the code enters an infinite loop at this point
python interprets the above as
while ('-') or (' ' in word):
an thus the string - is one half of the or statement and any non empty string will always evaluate to True
leaving the while condition as:
while True or ' ' in words:
try this intead:
while '-' in word or ' ' in word:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With