Mark.S
Mark.S

Reputation: 165

python append not adding to list

I am trying to learn python and am currently working with a basic dice roll script. 2 die roll until they both hit 6. when it will print the number of rolls it took to hit the defined [6:6].

this repeats 2 more times as seen with

for x in range(3):
        roll_dice()

My problem is that when I try to sum the run list it will only print the last dice roll count. I'm thinking my run.append(count) is not updating but resetting once it goes through the loop again?

I understand the rest of my code is probably really inefficient but still early stages of learning.

import random

def roll_dice():
    dice_one = 0
    dice_two = 0
    count = 0
    run = []
    while True:
        dice_one = random.randrange(1,7)
        dice_two = random.randrange(1,7)
        count += 1
        print(dice_one, " ", dice_two)

        if dice_one +  dice_two == 12:
            print("----", count, "attempts----")
            break
    run.append(count)
    print(sum(run))

for x in range(3):
        roll_dice()

Upvotes: 1

Views: 340

Answers (3)

user14227070
user14227070

Reputation:

Like the others have pointed out, the run.append(count) is being called outside the While loop. Due to this, only the last updated value of count is being added to run. By moving the run.append(count) inside the While loop, it will be updated each time the loop is executed.

Upvotes: 2

Gustave Coste
Gustave Coste

Reputation: 707

Simply put run.append(count) in the while loop:

import random

def roll_dice():
    dice_one = 0
    dice_two = 0
    count = 0
    run = []
    while True:
        dice_one = random.randrange(1,7)
        dice_two = random.randrange(1,7)
        count += 1
        print(dice_one, " ", dice_two)

        if dice_one +  dice_two == 12:
            print("----", count, "attempts----")
            break
        run.append(count)
    print(sum(run))

for x in range(3):
        roll_dice()

Upvotes: 1

Osvald Laurits
Osvald Laurits

Reputation: 1364

print(sum(run)) only prints the last dice roll count because run.append(count) is outside the while loop. It is only called once on every function call. Put it inside the while loop and it will append each time you roll the dies.

Upvotes: 0

Related Questions