174k views
4 votes
Write a Python program that simulates the flipping of a coin. When a coin is flipped, there are two options: heads and tails. Before performing a flip, ask the user to choose between heads and tails (you can assume correct user input. The input you ask the user for can be in whatever format you like, i.e., 1 for heads, 2 for tails, 'h' for heads, 't' for tails, etc...). After the user input, "flip" the coin and tell them which side it showed as well as if they guessed correctly or not. Allow the user to keep flipping coins until they decide to stop. Hint: Flipping a coin is similar in concept to rolling a 2-sided die.

1 Answer

2 votes

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.

User Qrsngky
by
8.9k points