User Tools

Site Tools


list_example_i

Differences

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

Link to this comparison view

Both sides previous revisionPrevious revision
list_example_i [2023/10/30 01:02] 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> +
-import random +
- +
-def play(self): +
-    # List of words to choose from +
-    words = 'apple', 'banana', 'pig', 'going'+
- +
-    guesses = [+
- +
-    chances = 7 +
-    tries = 0 +
- +
-    # Pick a random word +
-    word = random.choice(common_nouns) +
- +
-    gameword = [ '_' ] * len(word) +
- +
-    # This is our game loop. +
-    while tries < chances: +
-        print(""+
-        print("====="+
- +
-        print(" ".join(gameword)) +
-        print(""+
- +
-        # Ask the player to guess a letter. +
-        print("Guesses: " + "".join(guesses)) +
-        print("Tries left: ", chances-tries) +
-        guess = input("Please guess a letter: ") +
- +
-        # Did we already guess this letter? +
-        if guess not in guesses: +
-            guesses.append(guess) +
-            guesses.sort() +
- +
-            if guess in word: +
-                for i in range(len(word)): +
-                    if word[i== guess: +
-                        gameword[i= guess +
-            else: +
-                tries = tries + 1 +
- +
- +
-        # Check if the word has been completely guessed +
-        if '_' not in gameword: +
-            print("Congratulations! You've guessed the word: " + word) +
-            break +
- +
-        if tries >= chances: +
-            print("You've run out of attempts. The word was: " + word) +
- +
-</Code> +
- +
-Initially, you can just use print(gameword) instead of a more complex way of printing the game word. Later you can introduce .join() and explain what it does. Also, after the testing stage you can add more words.+
list_example_i.1698627729.txt.gz · Last modified: 2023/10/30 01:02 by appledog

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki