3

I just started to learn Python and am trying to code the following question:

Coin Flip Simulation- Write some code that simulates flipping a single coin however many times the user decides. The code should record the outcomes and count the number of tails and heads.

The following is my code:

import random

def num_of_input():
   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(count_head)
     print(count_tail)

The issue I am having right now is: if i give the input as x (x times of flip), then I need to give input X+1 times to be able to see result, something like this:

count_for_sides()
how many times of flips do you want?4
how many times of flips do you want?4
how many times of flips do you want?4
how many times of flips do you want?4
how many times of flips do you want?4

 0
 4

I am really confused about this situation. I think this means my input function is in a while loop, so it keeps on checking the conditions as it it continues to ask for my input.

thumbtackthief
  • 6,093
  • 10
  • 41
  • 87
Danqi Liu
  • 53
  • 1
  • 5
  • 1
    Could you double check the indentation of the code as it appears here? It matters in Python, and it looks like it's not the same as it is in your code. – Patrick Haugh Feb 16 '18 at 21:48
  • 2
    **Suggestion:** There are numerous coin flip written here on SO in Python, you could google them up and read the code. – Anton vBR Feb 16 '18 at 21:48
  • Please read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ to start learning how to debug your code. – Code-Apprentice Feb 16 '18 at 21:49
  • @AntonvBR: I believe we should be able to tell OP what is wrong. – Jongware Feb 16 '18 at 21:49
  • @usr2564301 Assuming he indents everything properly, the program basically works. I am not having the issues he is having. – Sam Craig Feb 16 '18 at 21:50
  • @SamCraig Judging by the name and the profile pic, I'm guessing he's a she. – thumbtackthief Feb 16 '18 at 21:52
  • Fixing indentation and missing colon, it works: https://ideone.com/fHY9FW – 001 Feb 16 '18 at 21:54
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation. [Minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. Your program doesn't run due to indentation problems. When I fix those, it works as you want. The problem you describe doesn't appear. – Prune Feb 16 '18 at 21:54
  • You could start with the [tag:coin-flipping] tag search. – Xantium Feb 16 '18 at 21:58
  • thanks very much for all the quick comments! appreciated it! – Danqi Liu Feb 16 '18 at 22:06

3 Answers3

0

I think you must have messed up your indentation somewhere. I copied your code, fixed the indentation issues from SO, and it worked basically correctly.

This is what I have:

import random

def num_of_input():
  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(count_head)
  print(count_tail)

count_for_sides()

That being said, you are doing some stuff you shouldn't do.

First off, there are places where infinite loops are appropriate, but your uses are not those places. For the first function, I think something like

def num_of_input():
    try:
        time_flip = int(input('how many times of flips do you want?'))
    except ValueError:
        print('That was not a valid integer. Please try again)
        time_flip = num_of_input()
    finally:
        return time_flip

is more readable and safer.

For the count_for_sides() function, something like:

def count_for_sides:
     count_head, count_tail = 0, 0
     for i in range(num_of_input()):
          if random.randint(0, 1) == 0:
               count_head+=1
          else:
               count_tail+=1
      print(counthead)
      print(counttail)

Along with replaces the infinite while loop with a for loop, I got rid of the random_flip function entirely because it does nothing, and just used random.randint(0, 1) directly.

Generally, the break command in python should be used very sparingly because it very rarely an improvement over a while loop with a conditional, a for loop (like the count_for_sides() function) or a recursive function (like num_of_input()). It is also usually less readable than other structures.

Sam Craig
  • 875
  • 5
  • 16
-1

Here's a succinct way of dealing with the problem, perhaps adapt to your code where you'd like to collect n_times from user input?

import random
from collections import Counter


def coin_toss(n_times):
  all_outcomes = []
  for x in range(n_times):
    outcome = random.random()
    if outcome > .50:
      all_outcomes.append('H')
    if outcome <= .50:
      all_outcomes.append('T')
  return Counter(all_outcomes)


print(coin_toss(100))

>> Counter({'H': 56, 'T': 44})

As others have mentioned, your indentation is all over the place, but that's fixable with some trial and error. The way I'm tracking tail and head outcomes is by keeping all results in a list, then using the Counter object from a module called "collections", which easily tallies element frequencies.

jrjames83
  • 901
  • 2
  • 9
  • 22
-1

I bunched two solutions from SO together in one to make a very simple coin toss. It has some similarities with your solution but everything is stripped.

import random

def int_input(text):
    """Makes sure that that user input is an int"""
    # source: https://stackoverflow.com/questions/22047671

    while True:
        try:
            num = int(input(text))
        except ValueError:
            print("You must enter an integer.")
        else:
            return num

def main():
    """Asks for amount of tosses and prints sum(heads) and sum(tails)"""
    # source: https://stackoverflow.com/questions/6486877/

    tosses = int_input("How many times of flips do you want? ")

    heads = sum(random.randint(0, 1) for toss in range(tosses))
    tails = tosses - heads

    print('The {} tosses resulted in:\n{} heads and {} tails.'
          .format(tosses,heads,tails))    

main()
Anton vBR
  • 18,287
  • 5
  • 40
  • 46