Data Science Explorer

Personal Project: Hangman 본문

Projects

Personal Project: Hangman

grace21110 2023. 11. 2. 21:19
반응형

Yesterday, I made this fun project named Hangman and wanted to review the codes today. 

Let's dive in!

 

Please refer to the following codes: 

import random
import string
from words import words

def get_valid_word(words):
    word = random.choice(words)
    while '-' in word or ' ' in word:
        word = random.choice(words)
    return word.upper()

def hangman():
    word = get_valid_word(words)
    word_letters = set(word)
    alphabet = set(string.ascii_uppercase)
    used_letters = set()

    while len(word_letters) > 0:
        user_letter = input('Guess a letter: ').upper()
        
        if user_letter in alphabet - used_letters:
            used_letters.add(user_letter)
            if user_letter in word_letters:
                word_letters.remove(user_letter)
        elif user_letter in used_letters:
            print('You have already used that character. Please try again.')
        else:
            print('Invalid character. Please try again.')

    print(f'Congratulations! You guessed the word: {word}')

if __name__ == "__main__":
    hangman()

 

 

I found interesting code from this project. I will give you an example to explain it. 

 

Let's say we have this code. 

# This code will run regardless of whether the script is the main program or imported as a module
print("This will always be executed")

if __name__ == "__main__":
    # This code will only run if the script is the main program
    print("This will only run if the script is the main program")

When you run this script directly (e.g., python script.py), both print statements will execute. However, if you import this script as a module in another script, only the first print statement will execute, and the code inside the if __name__ == "__main__": block will be skipped.

 

Cannot wait to find other interesting codes!