This article is an example of a Python program to calculate the percentage of the occurrences of heads or tails in n flips of a coin.
Things to know
- Inputting values to Python
- Data type conversion
- Random value
- Finding Percentage
Inputting values to Python
The command for getting the value in Python is as follows.
variable = input( msg )
where the variable is the memory that we named for the location stored in memory and msg is the message to be displayed on the display before the prompt to receive data, so if you want to stored data in variable n can be coded like this:
n = input( “number of random?”)
Data type conversion
However, the value received from input() is a string, so it must be converted to An integer or decimal by converting it with int( ) or float( ), though we use the following set of statements:
n = int( input( “number of random?” ))
or
n = float( input( “numbeer of random?” ))
If the data is not number will result in an error so when programming we need to intercept potential errors with try/except like this
try:
n = int( input( "number of random?" ))
except:
print("Please input integer")
Random value
Python randomization uses the random() command from the random library. An example of a random value is
import random
random_value = random.random()
The random value is a decimal number in the range of 0 to 1. Therefore, if you want to randomize a value between 0 or 1, which is an integer value, it can be written as a function like this:
def randCoin():
return int(random.random()*2)
So, to check if n random number of heads or tails occur, you can write a code like this:
import random
numH = 0
numT = 0
n = 4
for counter in range(n):
if (randCoin() == 0):
numH += 1
else:
numT += 1
print("H:{}, T:{}".format(numH, numT))
Finding Percentage
The method for calculating the percentage of m from n is done by dividing the value of m by n and multiplying the result by 100 as follows:
percentage = m/n*100
Therefore, the function of finding percentage can be written as:
sub calcPercentage(m, n):
return (100.0*(m/n))
Example Code
Example code22-1 shows the percentage of heads and tails generated from tossing a coin n times.
#code22-1
import random
def randCoin():
return int(random.random()*2)
def calcPercentage(m, n):
if n == 0:
return 0
return (100.0*(m/n))
numH = 0
numT = 0
try:
n = int(input("number of random?"))
for counter in range(n):
if (randCoin()==0):
numH += 1
else:
numT += 1
print("H={}%, T={}%".format(
calcPercentage(numH),
calcPercentage(numT)))
except:
print("Please input integer")
Conclusion
From this article, we learned how to get information, how to convert string data to numbers, error catching, randomization, randomization in the desired range of values and finding the percentage which is the basis for further use.
Finally, have fun with programming.
(C) 2020, By Jarut Busarathid and Danai Jedsadathitikul
Updated 2021-09-09