User Tools

Site Tools


clubs:python_club:python_club_ex_hangman
Home | clubs :: cloud club :: python_club :: 3D-Printing | projects :: Proxmox | Kubernetes | scripting | utilities | games

About the Club

Python Club Topics - Exercise: Hangman game

Exercise: Hangman Game

  1. Output: Create the game of Hangman for 2 players
  2. What you learn from the example:
    1. Use loops, conditionals, and functions
    2. Get input from user
    3. Use lists

Solution

[1] code:python show
import random

def hangman():
    words = [“python”, “java”, “javascript”, “ruby”, “csharp”, “swift”, “kotlin”, “go”, “rust”, “php”]
    word = random.choice(words)
    word_letters = set(word)
    alphabet = set(chr(ord('a') + i) for i in range(26))
    used_letters = set()
    lives = 6

    while len(word_letters) > 0 and lives > 0:
        print(“You have”, lives, “lives left and you have used these letters: ”, “ ”.join(used_letters))
        word_list = [letter if letter in used_letters else “_” for letter in word]
        print(“Current word: ”, “ ”.join(word_list))

        user_letter = input(“Guess a letter: ”).lower()
        if user_letter in alphabet - used_letters:
            used_letters.add(user_letter)
            if user_letter in word_letters:
                word_letters.remove(user_letter)
            else:
                lives -= 1
                print(“Letter is not in word.”)
        elif user_letter in used_letters:
            print(“You have already used that character. Please try again.”)
        else:
            print(“Invalid character. Please try again.”)

    if lives == 0:
        print(“You died, sorry. The word was”, word)
    else:
        print(“You guessed the word”, word, “!!”)

hangman()

clubs/python_club/python_club_ex_hangman.txt · Last modified: by 127.0.0.1