Home > Net >  Count the number of time a specific number occurs in a for loop
Count the number of time a specific number occurs in a for loop

Time:10-30

So i am trying to make a dice game that rolls the dice 10 times and is you get 2 1's you get extra points

This is my for loop

import random

rolls = 10
total = 0     

for i in range(1, rolls   1):
    n = random.randint(1, 6)
    total  = n
    print(f'Roll {i}: [{n}]')

How to make it tell me if there are 2 1's in the any of the rolls

CodePudding user response:

Two dices means two randomized input. So you'll need do two randints. Then you can check if both are 1.

import random

rolls = 10
total = 0     

for i in range(1, rolls   1):
    n1 = random.randint(1, 6)
    n2 = random.randint(1, 6)
    if n1 == 1 and n2 == 1:
        total  = 1

print(f'rolled {n} times. Got both 1s {total} times')

CodePudding user response:

You can keep track of how many 1's with a variable, let's call in numberOfOnes and increment it every time we roll a 1.

import random

rolls = 10
total = 0
numberOfOnes = 0    

for i in range(1, rolls   1):
    n = random.randint(1, 6)
    total  = n
    if n == 1:
        numberOfOnes  = 1
    print(f'Roll {i}: [{n}]. {numberOfOnes} 1\'s rolled so far!')

#here we'll check if we rolled 1's at least twice
if numberOfOnes >= 2:
    print("You got an extra point!")

If you want to handle two dices (rolled both 10 times), you can check @MSH's answer.

  • Related