python计算抛硬币结果

 1、原始代码
import random
endGame = False

while not endGame:
    strResult = ""  #将所有结果保存为一个长字符串
    timeA = 0       #出现正面的次数
    timeB = 0       #出现反面的次数
    userInput = input("输入次数,或者按q退出\n")
    if userInput == "q":       #输入q时退出程序
        endGame = True
        print("程序结束")
    else:
        timeThrow = int(userInput)       #输入抛硬币的次数
        for index in range(timeThrow):
            throwResult = random.randint(1,2)        #随机生成1和2(正面和反面)
            strResult += str(throwResult)                 #将1或2合成字符串
        timeA = strResult.count("1")                      #统计1(正面)的次数
        timeB = strResult.count("2")                      #统计2(反面)的次数
        pctA = timeA/(timeA +  timeB)*100                 #正面占总次数的百分比
        pctB = timeB/(timeA +  timeB)*100                 #反面占总次数的百分比
        print(f"总共投掷了{timeThrow}次,a面出现{timeA}次,占比{pctA}%,b面出现{timeB}次,占比{pctB}%")

2、将硬币改为类的代码
import random
class Coin:
    def __init__(self):
        self.side = 0
        self.front = 1
        self.back = 2
        self.front_time = 0
        self.back_time = 0
        self.total_time = int(input("input a throw number"))
    def throw(self):
        for i in range(self.total_time):
            self.side = random.randint(1, 2)
            match self.side:
                case 1:
                    self.front_time += 1
                case 2:
                    self.back_time += 1
    def show_throw_result(self):
        front_rate = self.front_time/self.total_time
        back_rate = self.back_time/self.total_time
        print(f"u throw {self.total_time} times\n{self.front_time} front, the rate is {front_rate}\n{self.back_time} back, the rate is {back_rate}")
is_over = False
while not is_over:
    coin = Coin()
    coin.throw()
    coin.show_throw_result()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值