有没有办法计算python中while循环的迭代次数?

Is there a way to count the number of iterations in a while loop in python?

我有一个非常简单的 while 循环,可以掷骰子直到掷出 6。我对 python 比较陌生,不确定是否已经存在可以用来计数的方法它需要的卷数。我的代码是:

import random

mace_trans = 0
while mace_trans != 6:
    mace_trans = random.randint(1, 6)
    print(mace_trans)

只需创建一个变量并递增它:

import random

# Initialize it to 0
num_rolls = 0

mace_trans = 0
while mace_trans != 6:
    mace_trans = random.randint(1, 6)
    print(mace_trans)

    # Increment it every loop iteration
    num_rolls += 1

print(num_rolls)

我不知道有任何内置方法,但我确实建议您创建某种计数器变量并在每个循环中递增。

import random
mace_trans = 0
rounds = 0
while mace_trans != 6:
    rounds += 1
    mace_trans = random.randint(1, 6)
    print(mace_trans)
import random

dice_roll = random.randint(1,6)
count = 0

while dice_roll != 6:
    count +=1
    dice_roll = random.randint(1,6)

if count == 0:
    print(f'{dice_roll} on the first roll !')
else:
    print(f'It took {count} dice rolls to get a 6.')