×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python program to design a coin flip function

An example of random.choice() in Python: Here, we are going to learn how to design a function that can be used as coin flip and the function will return a random value of coin flip? By Anuj Singh Last updated : January 12, 2024

Problem statement

Write a Python program to design a coin flip function.

Solution overview

Here, we are going to build a coin() function using Python. The program is so simple as an introductory program for defining a function. The function is going to use an inbuilt library naming random. This random library helps us to choose a random value of the variable within the range.

Designing a coin flip function

To design a coin flip function, use the random.choice() method and pass the list of the values for HEAD and TAIL as ['H', 'T'] as the parameter, when the function is called, it will return a random value from the given list that will be either HEAD ('H') or TAIL ('T').

Consider the below statement:

random.choice(['H','T'])

The above function will choose a random value with a probability of 0.5 each i.e. all are independent to each other which will work as dice.

Python program to design a coin flip function

import random

# function to return the random value of
# coin flip
def coin():
    return random.choice(["H", "T"])

# main code i.e. calling the function
print("COIN FLIP: ", coin())
print("COIN FLIP: ", coin())
print("COIN FLIP: ", coin())
print("COIN FLIP: ", coin())
print("COIN FLIP: ", coin())

Output

The output of the above program is:

RUN 1:
COIN FLIP:  H
COIN FLIP:  T
COIN FLIP:  T
COIN FLIP:  H
COIN FLIP:  T

RUN 2:
COIN FLIP:  H
COIN FLIP:  T
COIN FLIP:  T
COIN FLIP:  T
COIN FLIP:  T

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »

Advertisement
Advertisement

Related Programs

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.