You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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 random module to simulate the randomness of a real coin flip.
  • heads and tails start at 0—these will keep track of how many times each outcome occurs.
  • flip_count tracks 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_count to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:30:20