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
CodePudding user response:
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:
CodePudding user response:
You are probably entering an infinite loop in function get_valid_word(words)
.
Try to debug your code and check line while '-' or ' ' in word:
CodePudding user response:
The other answer are correct. But I wan't to suggest an improvement of your code. There is a redundant because the line word = random.choice(words)
appears two times.
You can prevent this when you prevent the while
loop and replace it with a recursive call of get_valid_word()
.
import random
import string
# from Words import words
words = ['FOOBAR', 'FOO-BAR', 'FOO BAR']
def get_valid_word(words):
word = random.choice(words)
if '-' in word or ' ' in word:
return get_valid_word(words)
return word.upper()