User Tools

Site Tools


list_example_i

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
list_example_i [2023/10/27 10:31] – created appledoglist_example_i [2023/11/06 01:06] (current) appledog
Line 1: Line 1:
-= List Example I +[[pyhang game]]
-* Hangman +
- +
-== Hangman Game +
-The following game illustrates the use of lists. +
- +
-<Code:Python> +
-def hangman(): +
-    # List of words to choose from +
-    words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"+
- +
-    # Choose a random word from the list +
-    word = random.choice(words) +
- +
-    # Create a list to store the guessed letters +
-    guessed_letters = [] +
- +
-    # Maximum number of incorrect guesses allowed +
-    max_attempts = 6 +
-    attempts = 0 +
- +
-    # Create a string to store the partially revealed word +
-    current_word = ["_"] * len(word) +
- +
-    while attempts < max_attempts: +
-        # Display the current state of the word +
-        print(" ".join(current_word)) +
- +
-        # Ask the player for a letter guess +
-        guess = input("Guess a letter: ").lower() +
- +
-        # Check if the guess is a single letter +
-        if len(guess) != 1 or not guess.isalpha(): +
-            print("Please enter a single letter."+
-            continue +
- +
-        # Check if the letter has already been guessed +
-        if guess in guessed_letters: +
-            print("You've already guessed that letter."+
-            continue +
- +
-        # Add the guess to the list of guessed letters +
-        guessed_letters.append(guess) +
- +
-        # Check if the guess is in the word +
-        if guess in word: +
-            for i in range(len(word)): +
-                if word[i] == guess: +
-                    current_word[i= guess +
-        else: +
-            attempts += 1 +
-            print(f"Incorrect guess! You have {max_attempts - attempts} attempts left."+
- +
-        # Check if the word has been completely guessed +
-        if "".join(current_word) == word: +
-            print("Congratulations! You've guessed the word: " + word) +
-            break +
- +
-    if attempts >= max_attempts: +
-        print("You've run out of attempts. The word was: " + word) +
- +
-</Code>+
list_example_i.1698402676.txt.gz · Last modified: 2023/10/27 10:31 by appledog

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki