使用Python while循环计数:统计5次抛硬币的正反面次数
Using Python While Loop to Count Coin Flip Results
Alright, let's build this coin flip counter step by step. The goal is to run exactly 5 flips, track how many times heads and tails come up, then print the totals. Here's a straightforward implementation:
import random # Initialize counters for heads and tails heads = 0 tails = 0 flip_count = 0 # Loop until we've done 5 flips while flip_count < 5: # Simulate a coin flip: randomly choose heads or tails result = random.choice(["heads", "tails"]) # Update the corresponding counter if result == "heads": heads += 1 else: tails += 1 # Increment the flip count to avoid an infinite loop flip_count += 1 # Print the final results print(f"- Heads was {heads} times") print(f"- Tails was {tails} times")
Let me break down what's happening here:
- We start by importing the
randommodule to simulate the randomness of a real coin flip. headsandtailsstart at 0—these will keep track of how many times each outcome occurs.flip_counttracks how many flips we've completed; we keep the loop running as long as this number is less than 5.random.choice(["heads", "tails"])picks one of the two options at random, just like flipping a coin.- After each flip, we check the result and add 1 to the matching counter, then increment
flip_countto make sure we don't loop forever. - Finally, we use formatted strings to print out the totals in the exact format you're looking for.
Example Output:
- Heads was 3 times
- Tails was 2 times
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

