DEV Community

Cover image for Build a Heads Or Tails Game With Python
Juwon?πŸ€
Juwon?πŸ€

Posted on • Edited on

Build a Heads Or Tails Game With Python

Python is a programming language that's often used to develop websites, automate tasks, and analyze data. As a general-purpose language, Python can be used to create many different programs, and it is not specialized in any specific field.

In this article, I will implement the Heads or Tails game using the Python programming language. This article aims to provide a deeper and more helpful understanding of Python.

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

  • Simplify: A simple way to structure your code in functions. Despite its simplicity, this is one of the skills you need a lot of practice in.
  • User Prompt: The game requires handling of user's input.
  • Randomness: You need to flip a coin and for that, you need randomness.
  • Control Flow: The game requires conditional statements and loops to control the game flow based on user input and game logic.

Prerequisites

Before we create the Heads or Tails game with python, ensure the following is installed on your system:

  • Operating systems such as Windows, Linux, or MacOS
  • Python installed on your system(updated version)
  • A code editor or IDE(Visual Studio code with Jupyter notebooks extension)

Let's go!!

Project Description

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

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.

This article aims to demonstrate how simple and useful functions are.
Note: An advantage of writing functions is that it enables you to
test it isolated.

Simplifying The Program
I think it is always wise to break down problems into smaller pieces that can be handled separately rather than just starting to write code.

As a result, it will be easier to implement isolated pieces and, the best part is, you can test pieces of code independently.

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

Let’s try to do it for this project.

Step 1 - Prompt User
In this step, I would create a function that prompts the user.

Creating User Input

#Python

def user_input():

    guess = ''

    while guess not in ['Head','Tail']:
        guess = input('Choose Head or Tail: ').capitalize()


    if guess in ['Head','Tail']:
        return guess

    else:
        print('Wrong choice')
print(user_input)

Enter fullscreen mode Exit fullscreen mode

Code Output

#Python
#code output

Choose Head or Tail: fry
Choose Head or Tail: Head
'Head'
Enter fullscreen mode Exit fullscreen mode

A while loop (while True) is used to prompt the user for input, so executing the code won't begin until a valid entry is entered.

Observe that my code didn't execute until I input the correct word 'Head' after I input the wrong word 'fry'.

Step 2 - Flip a coin
The next step is to implement a function that flips a coin randomly.

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

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

Creating a function to flip a coin

#Python

from random import randrange

def flip_coin():

    coin = randrange(2)

    if coin == 0:
        return 'Tail'
    else:
        return 'Head'

print(flip_coin)
Enter fullscreen mode Exit fullscreen mode

Output of the flip a coin function

#Python
#code output

'Tail'
Enter fullscreen mode Exit fullscreen mode

The call randrange(2) will either return 0 or 1. In the case of 0, tail are returned, in the case of 1, head is returned.

This output indicates that the randrange(2) chose 0 randomly, which means 'Tail' was returned.

Step 3 - Print The Result
Finally, we need to validate if the user’s guess is correct.

This is where the power of functions is great.

Creating the result function

#Python

def result(user_guess,coin):

    if user_guess == coin:
        print('Awesome Choice, You Are Correct!!!')
        print(f'User guessed {user_guess}, computer chose {coin}')

    else:
        print('Wrong Choice')
        print(f'User guessed {user_guess}, computer chose {coin}')

Enter fullscreen mode Exit fullscreen mode

Step 4 - Combining All Functions
As we have already established, functions work independently.

Now it is time to combine it all.

#Python

user_guess = user_input()

coin = flip_coin()

print_result = result(user_guess,coin)
Enter fullscreen mode Exit fullscreen mode

Final Output

#Python

Choose Head or Tail: Head
Wrong Choice
User guessed Head, computer chose Tail


Enter fullscreen mode Exit fullscreen mode

In the output above, we can see that 'Head' was input by the user.

Also we can notice the computer randomly chose 0 randomly which returned 'Tail', finally making the user lose the game and end the program.

Conclusion
The article is about Building a Heads-or-Tails game, which I have broken down step by step for easy readability.

I must admit this is beautiful and 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.

I hope it's educational. It would be greatly appreciated if you followed me, read my previous articles, share your honest opinions, and react and comment.

Top comments (2)

Collapse
 
xtofl profile image
xtofl

I like this post for its very simple introduction to functions.

Some remarks, though, if you would like the code to be exemplary.

After exiting a while loop, its condition is false, so there is no need to check if guess in [...] anymore. You can really drip 3 lines there.

And If the reader has to learn one function from the random module, let it be random.choice.

Collapse
 
jayywestty profile image
Juwon?πŸ€

Thank you, would definitely work on that