Learn how you can become a Python programmer in just 12 weeks.

    We respect your privacy. Unsubscribe at anytime.

    Master For and While Loops in Python to Create a Hangman Game

    Create your own Hangman Game in Python

    You will learn how to loop over a Python list. Further, you will learn the power of a While loop. Finally, you will create a Hangman Game.

    In this tutorial, you will:

    • Looping Over a Python List: Learn how to iterate over elements in a list using different loop constructs in Python.
    • Unleash the Power of While Loops: Understand the versatility of While loops and their ability to execute code repeatedly until a certain condition is met.
    • Create a Hangman Game: Apply your newfound knowledge of loops to develop a Hangman game, where you guess letters to reveal a hidden word.

    By the end of the tutorial, you will have a strong grasp of iterating over lists, utilizing While loops effectively, and implementing a fun and interactive Hangman game. This hands-on experience will enhance your understanding of loops and equip you with practical programming skills.

    Watch tutorial

    Step 1: Loop over a list or sequence

    Looping over a list can be done as follows (see more about lists here).

    my_list = ['First', 'Second', 'Third']
    for item in my_list:
        print(item)
    

    This can also be done over a string, which is a sequence.

    s = "Rune"
    for c in s:
        print(c)
        print("Inside loop")
    print("Outside the loop")
    

    Where we notice the syntax of how the indentation works. What is inside and outside the loop?

    Step 2: While loops and how they differ

    Notice that for-loops in Python loop over a predetermined length. In the above cases, the length of the list or the length of the string.

    If you want a loop that is dependent on something inside the loop.

    What do I mean? Let’s take an example.

    value = 10
    while value > 0:
        value = int(input("Value? "))
    

    As you see – this loop is dependent on input in the loop. If you type zero or a negative value, it will stop.

    Step 3: Description of the Hangman Game

    A description of the Hangman Game (see wiki for further details)

    • The game is as follows.
    • Computer has a list of words.
    • Computer chooses a random word from the list.
    • The player gets 10 wrong guesses (10 turns).
    • The game follows this loop
      • Computer prints the word character by character replacing with underscore those not guessed yet (initially no characters have been guessed).
      • Player guesses a character.
      • If a character is not in words, a turn is withdrawn
      • If no one turns left, the computer wins.
      • If Player has guessed all characters, Player wins

    Step 4: Implementing the Hangman Game

    Let’s try to implement the Hangman Game

    import random
    words = ['father', 'enterprise', 'science', 'programming', 'resistance', 'fiction', 'condition', 'reverse', 'computer', 'python']
    word = random.choice(words)
    turns = 10
    guesses = ''
    while turns > 0:
        print(f"Turns left: {turns}")
        
        guessed_all = True
        for c in word:
            if c in guesses:
                print(c, end=' ')
            else:
                print('_', end=' ')
                guessed_all = False
        print()
        if guessed_all:
            print("You won")
            break
        
        guess = input("Guess a character: ")
        
        if guess in word:
            guesses += guess
        else:
            turns -= 1
    else:
        print("You lost")
    

    Step 5: Want more?

    In the next lesson you will make a Simple Implementation of Caesar Cipher in Python.

    If this is something you like and you want to get started with Python, then this is part of an 8 hours FREE video course with full explanations, projects on each level, and guided solutions.

    The course is structured with the following resources to improve your learning experience.

    • 17 video lessons teaching you everything you need to know to get started with Python.
    • 34 Jupyter Notebooks with lesson code and projects.
    • A FREE eBook to support your Python learning.

    See the full FREE course page here.

    Python for Finance: Unlock Financial Freedom and Build Your Dream Life

    Discover the key to financial freedom and secure your dream life with Python for Finance!

    Say goodbye to financial anxiety and embrace a future filled with confidence and success. If you’re tired of struggling to pay bills and longing for a life of leisure, it’s time to take action.

    Imagine breaking free from that dead-end job and opening doors to endless opportunities. With Python for Finance, you can acquire the invaluable skill of financial analysis that will revolutionize your life.

    Make informed investment decisions, unlock the secrets of business financial performance, and maximize your money like never before. Gain the knowledge sought after by companies worldwide and become an indispensable asset in today’s competitive market.

    Don’t let your dreams slip away. Master Python for Finance and pave your way to a profitable and fulfilling career. Start building the future you deserve today!

    Python for Finance a 21 hours course that teaches investing with Python.

    Learn pandas, NumPy, Matplotlib for Financial Analysis & learn how to Automate Value Investing.

    “Excellent course for anyone trying to learn coding and investing.” – Lorenzo B.

    Leave a Comment