Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Help Me Understand Hangman Game Breakdown in Python

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 117
    Answer it
    My question is with regards to the below code its a hangman game. I got this code online and trying to reverse engineer it so i can understand it better. My question is specifically regarding two lines , i need to understand the individual line and also i think the two lines are linked and need to know how there are there linked
    the first line in question is..........guessed[letter] = 1.....i understand this assign the a value to key but what benefit does it give my assiging 1 to the key.
    The second line......print(" ".join([ch if guessed[ch] else "_" for ch in word])).... i dont under what this line does and what does "ch" mean and what does it do please clarify
    
    import random
    WORDS= ("variable", "python", "turtle", "string", "loop")
    
    word = random.choice(WORDS)#chooses randomly from the choice of words
    print  ("The word is", len(word), "letters long.")# used to show how many letters are in the random word
    
    ln = len(word)
    guessed = dict.fromkeys(word, 0)
    print("_ "*ln)
    correct = 0
    for i in range(1, 9):#gives the amount of guesses allocated
        letter = input("Guess a letter ")
    
        if letter in word:
            print ("Correct! {} is in the word".format(letter))#if guesses letter is correct print correct
            guessed[letter] = 1
            correct += 1
            if correct == ln:
                print("Congratulations! you win.\n The word was {}".format(word))
                break
        else:
            print ("Incorrect! {} is not in the word".format(letter))
            #if its wrong print incorecct
        print(" ".join([ch if guessed[ch] else "_" for ch in word]))
    else:
        print("You lose!\nThe word was {}".format(word))

 0 Answer(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: