[Tutor] dont understand part of a code

Minhaj Ahmed min786a at googlemail.com
Sat Jul 2 06:46:07 EDT 2016


Hi, below is code for a hangman game which I copied from a book I am
studying,Python programming for the absolute beginners by Michael Dawson. I
have underlined the part of code I do not understand and why it is there.

import random

HANGMAN = (
    """
    ------|
    |
    |
    |
    |
    -----
    """,
    """

     ------|
    |      0
    |
    |
    |
    -----
    """,
    """
     ------|
    |      0
    |     -+-
    |
    |
    -----
    """,
    """
    ------|
    |     0
    |    -+-
    |
    |
    -----
    """,
    """
    ------|
    |     0
    |   /-+-
    |
    |
    -----
    """,
    """
    ------|
    |     0
    |   /-+-\
    |
    |
    -----
    """,
    """
    ------|
    |     0
    |   /-+-\
    |     |
    |
    -----
    """,
    """
    ------|
    |     0
    |   /-+-\
    |     |
    |    |
    -----
    """,
    """
    ------|
    |     0
    |   /-+-\
    |     |
    |    |
    -----
    """,
    """
    ------|
    |     0
    |   /-+-\
    |     |
    |    | |
    -----
    """)

MAX_WRONG = len(HANGMAN )-1
WORDS = ("PYTHON","RUBY","VISUAL BASIC","PHP","JAVA","UNIX","LINUX","PERL")
word = random.choice(WORDS)
so_far = "-" * len(word)
wrong = 0
used = []
print("Welcome to hangman.Good luck!")

while wrong < MAX_WRONG and so_far != word:
    print(HANGMAN[wrong])
    print("\nYou've used the following letterss:\n",used)
    print("\nSo far,the word is:\n", so_far)
    guess = input("\nEnter your guess: ")
    guess = guess.upper()

    while guess in used:
        print("You've already guessed the letter",guess)
        guess = input("Enter your guess: ")
        guess = guess.upper()

    used.append(guess)

    if guess in word:
        print("\nYes",guess,"is in the word!")

        new = ""
        for i in range(len(word)):
            if guess == word[i]:
                new += guess
          *  else:*
*                new += so_far[i]  # why is there a else code here?*
        so_far = new
    else:
        print("\nSorry",guess,"isnt in the word")
        wrong += 1
if wrong == MAX_WRONG:
    print(HANGMAN[wrog])
    print("\nYou have been hanged!!")
else:
    print("\nYou have guessed correct")

print("\nThe word was", word)

input("\nPress enter to exit")


More information about the Tutor mailing list