Coin flip

Posted on Mon, Jul 21 2025 | Tags: python

This is a simple coin flipping game that requires absolutely no third-party packages. Everything we need already ships with a standard installation of Python 3.x. The program takes input from the user, chooses between two random states, and tells the user if they won.

Section 1: Importing the required libraries

Python's standard library includes a lot of pre-written code in the form of modules. In the realm of Python, the words "library" and "module" are often used interchangeably. Here are the only modules we need:

# Make the coin
import random
import sys

The random module contains functions that allow Python to pick random values from arrays and ranges of numbers. The sys module contains a bunch of functions and read-only variables related to the Python interpreter itself and its surrounding environment. Think command line arguments, low-level details about numerical precision, where Python's files are located, etc. For this program, we call sys.exit() to immediately kill Python when a problem occurs.

Section 2: Coin flipping and user input

The next step is to declare an array to hold the two possible coin states: heads and tails. A boolean could be used here instead, but I think an array of two strings is easier to work with for this particular program.

coin = ["heads", "tails"]

After that, we declare a function that flips the coin by randomly picking one of the two possible states.

def flipCoin(coin):
    return random.choice(coin)

Next up is user input. To get input from the user, we use the aptly named input() function, which allows us to write a prompt for the user. The .strip() part is required to remove all leading and trailing white space characters (tabs, spaces, newlines, etc) from the user's input.

def getUserInput():
    choice = input("Choose heads or tails: ").strip()

Then we check whether the user's input was valid. This is very important because the wrong input will cause the program to crash or malfunction. In this case, if the user's input is not valid, the function returns false.

    if choice == "heads" or choice == "tails":
        return choice
    else:
        print("You have to choose heads or tails!")
        return False

Section 3: The main function

Finally we have the main() function. This function calls getUserInput() to get the user's choice. If the user's choice is false, sys.exit(1) is called, which immediately exits Python and returns an exit code of 1 to the operating system.

def main():
    userChoice = getUserInput()

    # If the user's choice was invalid, die.
    if not userChoice:
        sys.exit(1)

Quick note on exit codes:

On Linux and Unix-like systems (including Mac OS), all programs return a final numeric value to the OS when they exit. This value is often called the return code or the exit code. In general, an exit code of 0 means the program terminated normally and nothing went wrong. Anything other than 0 usually means that an error occurred.

If the user's choice was valid, the flipCoin() function is used to get the computer's choice. Then it prints what the computer and the user chose, sees if they match, and tells the user whether they won the coin toss.


    toss = flipCoin(coin)

    print(f"You called '{userChoice}'")
    print(f"Result: {toss}")

    if toss == userChoice:
        print("YOU WIN!")
    else:
        print("You lose...")

Quick note on f-strings:

The lines with f"{var_name}" stuff show off Python's format string syntax (f-string), which allows us to inject variables into strings. Such strings can be assigned to other variables, or sent directly to functions like print().

The final line of the program is a call to the main() function we just defined. And that's it! A simple coin toss game using only what Python provides by default.

main()

And that's it! Here's the complete program for your copypasta enjoyment.

# Make the coin
import random
import sys
coin = ["heads", "tails"]

def flipCoin(coin):
    return random.choice(coin)

def getUserInput():
    choice = input("Choose heads or tails: ").strip()

    if choice == "heads" or choice == "tails":
        return choice
    else:
        print("You have to choose heads or tails!")
        return False


def main():
    userChoice = getUserInput()

    # If the user's choice was invalid, die.
    if not userChoice:
        sys.exit(1)

    toss = flipCoin(coin)

    print(f"You called '{userChoice}'")
    print(f"Result: {toss}")

    if toss == userChoice:
        print("YOU WIN!")
    else:
        print("You lose...")


main()

As you can see, it's pretty short. Try copying the code and playing with it. Maybe make a 3-sided coin or turn it into a number guessing game.