list_example_i
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revision | |||
list_example_i [2023/10/30 01:02] – appledog | list_example_i [2023/11/06 01:06] (current) – appledog | ||
---|---|---|---|
Line 1: | Line 1: | ||
- | = List Example I | + | [[pyhang |
- | * Hangman | + | |
- | + | ||
- | == Hangman Game | + | |
- | The following game illustrates the use of lists. | + | |
- | + | ||
- | < | + | |
- | import random | + | |
- | + | ||
- | def play(self): | + | |
- | # List of words to choose from | + | |
- | words = [ ' | + | |
- | + | ||
- | guesses = [] | + | |
- | + | ||
- | chances = 7 | + | |
- | tries = 0 | + | |
- | + | ||
- | # Pick a random word | + | |
- | word = random.choice(common_nouns) | + | |
- | + | ||
- | gameword = [ ' | + | |
- | + | ||
- | # This is our game loop. | + | |
- | while tries < chances: | + | |
- | print("" | + | |
- | print(" | + | |
- | + | ||
- | print(" | + | |
- | print("" | + | |
- | + | ||
- | # Ask the player to guess a letter. | + | |
- | print(" | + | |
- | print(" | + | |
- | guess = input(" | + | |
- | + | ||
- | # 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 ' | + | |
- | print(" | + | |
- | break | + | |
- | + | ||
- | if tries >= chances: | + | |
- | print(" | + | |
- | + | ||
- | </ | + | |
- | + | ||
- | 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