Home » Python » 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?
Submitted by Anuj Singh, on August 01, 2019

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.

    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.

Here is the code

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

COIN FLIP:  H
COIN FLIP:  T
COIN FLIP:  T
COIN FLIP:  H
COIN FLIP:  T





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.