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()