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

    We respect your privacy. Unsubscribe at anytime.

    Python Project: Heads or Tails (5 Things You Will Learn)

    Implement Heads or Tails in Python

    While heads-or-tails is a simple problem to solve in Python you can learn from it.

    • Simplify. How to structure your code in a simple way in functions. This is one of the skills you need a lot of practice in, while it seems simple and easy, there is a lot more to it.
    • Randomness. You need to flip a coin and for that, you need randomness.
    • User prompt. When you program user input can be in the wrong format. How do you deal with that?
    • Loops. To make a user prompt require correct input, you need to understand loops and how to use them in this case.
    • Conditional. You need to validate the guess from the user with the random coin. To do that you need conditionals.

    Are you ready?

    Project Description

    This is a simple project to create a heads-or-tails game in Python, we need to learn to work with functions.

    You should build a guessing game of heads or tails.

    Game description.

    1. The user is asked to guess head or tails
    2. The game will “flip” a coin to either heads or tails.
    3. The game will write if the user guessed correctly or not.

    Your goal is not to write the code, it is to use functions to create it.

    Note: An advantage of writing functions is that it enables you to test it isolated.

    Step 1 Understanding how to break it down

    Why bother breaking the problem down into isolated blocks?

    To simplify the code.

    Instead of “just starting to write the code” it is always a good idea if you can break the problem down in smaller pieces that can be treated isolated.

    The power is it will make it easier to implement isolated pieces and the best part is, you can test pieces of code isolated.

    Let’s try to do it for this project.

    One way to simplify is to think about what is happening in the game.

    1. The user is asked to guess heads or tails
    2. The game will “flip” a coin to either heads or tails.
    3. The game will write if the user guessed correctly or not.

    That could actually be one simple way to break it down into the above 3 pieces.

    Now your job is to implement them isolated and test that they work as expected.

    Step 2 Prompt the user

    A great way to organize code is to implement it in functions.

    This organizes the code in blocks of code that you can use with a call to a function. But more importantly, you can test it isolated.

    One way to prompt the user could be as follows.

    def input_from_user():
        while True:
            guess = input('head or tails? ')
            
            if guess in ['head', 'tails']:
                return guess
            
            print('Not valid input!')
    

    This uses the infinite loop (while True) to prompt the user (input()), until the input is valid (if guess in…).

    Now you can test that function isolated to see if it does what is expected.

    Step 3 Flip a coin

    The next piece we need to implement is a flip of a coin.

    To do that we need randomness. Luckily, Python has a standard library random that can assist you.

    We will use randrange as it is a standard go-to function to use to get a random integer.

    One way to implement it could be as follows.

    from random import randrange
    def flips_a_coin():
        coin = randrange(2)
        if coin == 0:
            return 'tails'
        else:
            return 'head'
    

    The call randrange(2) will either return 0 or 1.

    If it returns 0 we return tails otherwise head.

    Again, you can test this function isolated to see if it does as expected.

    Step 4 Print the result

    Finally, we need to validate if the user’s guess is correct.

    This is where the power of functions is great.

    def print_result(user_guess, coin):
        if user_guess == coin:
            print('You guessed it! You won!')
        else:
            print('No! You guessed wrong!')
    

    You might wonder why I am excited about this function.

    Well, this is where you actually combine the output of the previous two functions.

    But here is the great part.

    You can test it isolated.

    You can try all possibilities manually with your function.

    print_result('tails', 'tails')
    print_result('head', 'tails')
    print_result('tails', 'head')
    print_result('head', 'head')
    

    Now you know that all the pieces work isolated.

    It is time to combine it all.

    Step 5 Combining it all

    We know that all functions work isolated.

    Now it is time to combine it all.

    user_guess = input_from_user()
    coin = flips_a_coin()
    print_result(user_guess, coin)
    

    I must admit. This is beautiful, it is simple.

    Why is this powerful?

    Because it is simple to understand. If you notice something is wrong, say, if it only flips tails, it is easy to identify where in the code you should look, and on top of that, you can test that piece of code isolated.

    Want more Python projects?

    This is part of 19 Python Projects and you can create this project of a basic calculator that will teach you modular programming.

    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.

    2 thoughts on “Python Project: Heads or Tails (5 Things You Will Learn)”

    Leave a Comment