SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
.loops
Exercise:
Programming Excercises
Question:40 | ISBN:978013274719 | Edition: 6

Question

(Simulation: heads or tails) Write a program that simulates flipping a coin one million times and displays the number of heads and tails.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Simulation: heads or tails Program code:

#Header section
import random
#This method is used to Flips a coin and returns the result
def flipCoinSimulation():
 
  return "heads" if random.random() < 0.5 else "tails"

#main method for simulates flipping a coin one million times 
#and displays the number of heads and tails using call the method, flipCoinSimulation 
def main():
  results = []
  for _ in range(1000000):
    results.append(flipCoinSimulation())

  heads = results.count("heads")
  tails = results.count("tails")

  print("Heads: {}\nTails: {}".format(heads, tails))


if __name__ == "__main__":
  main()

Executed Output 1:

Heads: 500048
Tails: 499952

Executed Output 2:

Heads: 499701
Tails: 500299

 

0 0

Discussions

Post the discussion to improve the above solution.