Search code examples
pythoncoin-flipping

Starting out in Python Development: Coin-Tossing Loops


Afternoon all,

I cross your paths as someone looking to teachimself programming. As such, I've started with Python. As a disclaimer, I have searched the question for some examples of Python coin-tosses but I've not really understood any of the code that previous askers have come up with.

My task My educationanal material has asked me to come up with an application that flips the virtual coin 100 times and then prints the results. My ideas was to use an infinite loop, break out when the coin toss reaches 100 and then print the results.

I've not quite achieved this and I'm not spotting the error in what I've written. It seems to achieve the 100 flips but then only prints out 50 of either Heads / Tails; thus my error is somewhere in the counting logic?

Any explanation (bearing in mind I'm a beginner, not a moron!) would get both my gratitude and my upvote

Thanks for reading

# Exercise 3.2
# Heads and Tails coin flip

#import random
import random

#declare variables
heads = 0
tails = 0
cointoss = 0
coinresult = random.randint(1,2)

#start the loop
while True:
    cointoss +=1

    #end the loop if cointoss is greater than 100
    if cointoss > 100:
        break
    if coinresult == 1:
        heads +=1
        cointoss +=1
    elif coinresult == 2:
        tails +=1
        cointoss +=1

  print("Heads came up", heads, "times")
  print("Tails came up", tails, "times")

Solution

  • Put this line:

    coinresult = random.randint(1,2)
    

    inside the while loop. Otherwise you get value once, and just use it over and over inside the loop and you were adding to cointoss in two places per loop.