Search code examples
pythonpython-3.xprobabilitydice

Python program that simulates rolling a 6 sided die and adds up the result of each roll till you roll a 1


so this is the code I wrote that attempts to answer the question in the title :

import random
print("Well, hello there.")
while True:
    a = random.randint(1,6)
    sum = 0
    if(a==1): #If a one is indeed rolled, it just shows rolled a 1 and 'Pigs out' and makes the score equal to 0(player score that is) and is a sort of a GameOver
        print("Pigged out!")
        break #To get out of the loop
    else:
        while(sum<=20): 
            sum += a
            print(sum)

The program should hold the score till it reaches 20(or more) and display it. It essentially represents a single turn of 'Pig'. I am unable to figure out where I am going wrong with this? Any suggestions would be helpful.

An example of a sample output:

-rolled a 6 -rolled a 6 -rolled a 5 -rolled a 6 -Turn score is 23


Solution

  • If I understand rightly then you can simplify this quite a lot, like this:

    import random
    print("Well, hello there.")
    score = 0
    while score < 20:
        a = random.randint(1,6)
        print("A {} was rolled".format(a))
        score += a
        if a == 1:
            print("Pigged out!")
            score = 0
            break
    print("Turn score is {}".format(score))