Final answer:
The Python program allows the user to choose heads or tails, randomly generates the result of coin flips, and lets the user know if they guessed right. The outcome of each flip has a fair chance, reflecting the 50% theoretical probability of getting heads or tails.
Step-by-step explanation:
Simulating a Coin Flip in Python
To simulate flipping a coin in Python, you can use the built-in random module to generate random outcomes. Here is an example program that accomplishes this:
import random
while True:
user_choice = input("Choose heads or tails (h/t): ").lower()
flip_result = 'heads' if random.choice(['h', 't']) == 'h' else 'tails'
print("The coin landed on {}.".format(flip_result))
if user_choice[0] == flip_result[0]:
print("You guessed correctly!")
else:
print("Sorry, you guessed incorrectly.")
continue_flipping = input("Do you want to flip again? (yes/no): ").lower()
if continue_flipping != 'yes':
break
The program prompts the user to choose between heads or tails, then generates a random outcome for the coin flip. It reports the result and whether the user's guess was correct, offering the option to flip again. By utilizing the randint function from the random module, each flip is equally likely to be heads or tails, simulating a fair coin. In real-world coin flipping, the probability of heads or tails is 50%, which makes this a fair way to make decisions in competitions.
Remember that if you toss a coin a large number of times, like in Karl Pearson's experiment of 24,000 tosses, the results will tend to converge to the theoretical probability of 0.5 for both heads and tails, as per the law of large numbers.