Forum Archive

Coin flip with report problem

craigmrock

Hi,
Having trouble with code for a coin flip simulation program I’m trying to set up for a Stats class. The goal is to ask how many times to flip the coin, then show the results after the simulation. I’m pretty new to Python and programming, so I checked stack overflow and found the code below to try. Problem is, nothing is printing to the console to review. Any thoughts?
```
import random

def coinToss():
number = input("Number of times to flip coin: ")
recordList = []
heads = 0
tails = 0
for amount in range(number):
flip = random.randint(0,1)
if (flip == 0):
print("Heads")
recordList.append("Heads")
else:
print("Tails")
recordList.append("Tails")
print(str(recordList))
print(str(recordList.count("Heads")) + str(recordList.count("Tails")))

```
jerry

My first guess would be that since this is a function, you’ll need to call it. Add the following line to the bottom of your code:

coinToss()

On the command line, at least, that causes the code to ask for a number and then toss the coin that many times.

craigmrock

@jerry thanks!! That worked!

DaveClark

What a great sample program. I too am a beginner programmer. Your code has been fun to play with. I messed around and did some changes you might like. I made it just print out the final result, even runnng it to 100000 coin flips, it fast enough to run big numbers

import random

def coinToss():
    number = int(input("Number of times to flip coin: "))

    recordList = []
    Heads = 0
    Tails = 0
    for amount in range(number):
        flip = random.randint(0,1)
        if (flip == 0):
            #print("Heads")
            recordList.append('Heads')
        else:
            #print("Tails")
            recordList.append("Tails")
        #print(str(recordList))

    s = (str(recordList.count("Heads")) + ' heads  ' + str(recordList.count("Tails")) + ' tails')

    print(s)
    print()

coinToss()
ccc
  • use .input().strip() to gracefully deal with leading or trailing whitespace
  • use random.choice() to avoid the conversion step
  • simplify with list comprehension
  • print with f-string on Python 3.6 and later
import random


def coinToss():
    number = int(input("Number of times to flip coin: ").strip())
    flips = [random.choice(('Heads', 'Tails')) for _ in range(number)]
    print(f'{flips.count("Heads")} heads, {flips.count("Tails")} tails\n')


coinToss()
DaveClark

Wow

The economy of your art is exquisite

ramvee

@ccc
Beauty !

DaniAli17958920

i am here to tell you that now we are able to flip a coin many times at the give website which is best or its activity.click on he link to check it.
https://flip-a-coin-tosser.com/

roberys

Flipping a coin is easy best game to decide something i pplayed on pc https://flip-a-coin-tosser.com/