以下是一个示例代码,实现了重复投掷骰子直到投掷了N次六点的功能:
import random
def roll_dice():
return random.randint(1, 6)
def throw_until_six(N):
count = 0
while True:
count += 1
result = roll_dice()
print(f'Throw {count}: {result}')
if result == 6:
break
print(f'It took {count} throws to get a six')
throw_until_six(10)
这个示例代码中,roll_dice()
函数用于模拟投掷骰子,返回一个1到6的随机整数。throw_until_six(N)
函数接受一个参数N,表示要投掷的次数。在循环中,每次投掷骰子后,将计数器count加1,并打印投掷的结果。如果投掷结果为6,则跳出循环,并打印投掷了多少次才得到一个六点。调用throw_until_six(10)
表示投掷10次骰子,直到得到一个六点。