pythonfor-loopwhile-loopprobabilitydice

Errors writing a dice simulator using randomisation in python


I'm making a dice simulator in python. The program throws four dices 1000 times, then calculates how many times the sum of the four dices is equal to 21 or higher. This is what I've written so far:

    import random

    dice1 = random.randint(1,6)
    dice2 = random.randint(1,6)
    dice3 = random.randint(1,6)
    dice4 = random.randint(1,6)

    sum = dice1 + dice2 + dice3 + dice4

    n = 0    # the amount of times the sum of the score was 21 or higher

    for i in range(1000):
        dice1 = random.randint(1,6)
        dice2 = random.randint(1,6)
        dice3 = random.randint(1,6)
        dice4 = random.randint(1,6)
    
        for sum >= 21:
            n = n + 1

    print("You got 21 or higher", n, "times.")

However, the program's terminal only shows "You got 21 or higher 0 times." or "You got 21 or higher 1000 times." when I attempt to run it. How do I write the code so it calculates the amount of times the sum of the score is 21 or higher out of 1000 throws of the dice, as well as print the amount of times in the terminal? Thank you in advance!


Solution

  • I fixed the problem. Can you try this

    import random
    
    n = 0   
    
    for i in range(1000):
        dice1 = random.randint(1,6)
        dice2 = random.randint(1,6)
        dice3 = random.randint(1,6)
        dice4 = random.randint(1,6)
        sum = dice1 + dice2 + dice3 + dice4
        if sum >= 21:
            n = n + 1
    
    print("You got 21 or higher", n, "times.")