Game: Guess the Correct Word.


Learn with Hafiza Palwasha




How to design a game 'To Guess a Number' ?

Lecture No. 2

1. Open Python IDLE and open a new file as shown below:


2. Now the new file will open like this:


3. Now you have to write the following code for the game 'To Guess the correct Word':

import random

def choose_word():
    words = ["apple", "banana", "cherry", "grape", "orange", "strawberry", "watermelon"]
    return random.choice(words)

def display_word(word, guessed_letters):
    display = ""
    for letter in word:
        if letter in guessed_letters:
            display += letter
        else:
            display += "_"
    return display

def hangman():
    word_to_guess = choose_word()
    guessed_letters = []
    attempts_left = 6
    
    print("Welcome to Hangman!\n" "Guess the letter from the following list:" "apple\n", "banana\n", "cherry\n", "grape\n", "orange\n", "strawberry\n", "watermelon\n")
    
    while attempts_left > 0:
        print("\n" + display_word(word_to_guess, guessed_letters))
        guess = input("Guess a letter: ").lower()
        
        if len(guess) != 1 or not guess.isalpha():
            print("Please enter a single letter.")
            continue
        
        if guess in guessed_letters:
            print("You've already guessed that letter.")
            continue
        
        guessed_letters.append(guess)
        
        if guess in word_to_guess:
            print("Correct!")
        else:
            attempts_left -= 1
            print(f"Wrong guess! {attempts_left} attempts left.")
        
        if "_" not in display_word(word_to_guess, guessed_letters):
            print("\nCongratulations! You've guessed the word:", word_to_guess)
            break
    
    if attempts_left == 0:
        print("\nSorry, you've run out of attempts. The word was:", word_to_guess)

if __name__ == "__main__":
    hangman()

4. This written code will appear on screen as shown below:


5. Now click on 'run' and then click on 'Run Module' and the output will be as shown below:


6. Now you have to keep entering the letters to guess the correct word as shown below:








7. So luckily, I guessed the correct number and I won the game.

Homework Task

Now you have to do the following tasks to show your skills:
1. Rewrite this code for 20 words.
2. Rewrite this code for all the words starting from vowels.
3. Rewrite the code for 15 number of countries.

Enter your comments if you are facing some difficulty.

Comments