Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Coin Flip Simulator

How would I ask the user if they want to play and then start the simulation? And if they don’t the program prints a goodbye message. And print the total number of times the coin was flipped at the end.

import random 
def num_of_input():
  userName = input("Please enter your name: ")
  print("Hello " + userName + "!" + " This program simulates flipping a coin.")
  while True:
    try:
     time_flip= int(input("How many times of flips do you want? "))
    except:
      print("Please try again.")
      continue
    else:
      break
  return time_flip    

def random_flip():
  return random.randint(0, 1)


def count_for_sides():
  count_head=0
  count_tail=0
  times=num_of_input()
  while True:
    if count_head + count_tail == times:
      break

    else:
      if random_flip()==0:
        count_head+=1
      else:
        count_tail+=1

  print()    
  print(str(count_head) + " came up Heads")
  print(str(count_tail) + " came up Tails")

count_for_sides()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can get input from the user before calling the count_for_sides method and call it if they opt in.

import random 
def num_of_input():
  userName = input("Please enter your name: ")
  print("Hello " + userName + "!" + " This program simulates flipping a coin.")
  while True:
    try:
     time_flip = int(input("How many times of flips do you want? "))
    except:
      print("Please try again.")
      continue
    else:
      break
  return time_flip    

def random_flip():
  return random.randint(0, 1)


def count_for_sides():
  count_head=0
  count_tail=0
  times=num_of_input()
  while True:
    if count_head + count_tail == times:
      break

    else:
      if random_flip()==0:
        count_head+=1
      else:
        count_tail+=1

  print()    
  print(str(count_head) + " came up Heads")
  print(str(count_tail) + " came up Tails")

userWantsToPlay = input("Do you want to play this game? (Y/n): ")
if (userWantsToPlay == 'Y'):
  count_for_sides()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading