I'm a beginner. I want to use Python while statements in duplicate, but it doesn't work.

Asked 2 years ago, Updated 2 years ago, 26 views

What I want to do with Python,

Out of a certain number of D10 dice, roll back the number of dice that are more than a certain number and roll back the number of dice that are more than a certain number.

Repeat this task until the number of dice is zero, and then repeat the number of times

If the number of dice is 0, the largest value of the list is obtained.

For example, suppose the first number of dice is 10, and a certain number is 9

I want to implement this process in Python. I want to get the number of times I rolled the dice, the value, and the biggest value on the last roll list.

We were able to create a code to roll the dice and find out how many values are higher than a certain number.

import random
def dxdice(num, cri):

    dxresult = []
    dicelist = []

    while num > 0:
        d10roll = random.randrange(1, 10)
        dicelist.append(d10roll)
        num = num - 1

    count = 0
    for critical in dicelist:
        if critical >= cri:
            count += 1

    dxresult.append(dicelist)
    dxresult.append(count)

    return dxresult

print(dxdice(10,9))

The code above is the code that works safely.

But when I put the result value back in the while door and turned it around, it just stopped.

What I expected was to print out the list until the number of dice you rolled again [strong] [[number of dice you rolled first], [number of dice you rolled second], [number of dice you rolled second], ...] [strong] I thought I'd print out the list until a number or more was zero, but it stopped.

The code below is non-returnable.

import random
def dxdice(num, cri):

    dxresult = []
    dicelist = []

    while num > 0:

        while num > 0:
            d10roll = random.randrange(1, 10)
            dicelist.append(d10roll)
            num = num - 1

        count = 0
        for critical in dicelist:
            if critical >= cri:
                count += 1

        dxresult.append(dicelist)
        dxresult.append(count)

        # If you enter a number to roll it again, it stops there.
        num = count

    return dxresult

print(dxdice(10,9))

I'm not sure what the problem is. Please reply.

python

2022-09-19 23:32

1 Answers

The problem appears to be caused by the dicelist variable not being initialized.

dicelist is added in the inner while statement and is not reset after being used to create a count value. If you put the phrase that initializes to dicelist = [] into the outer while statement, it will work normally.


2022-09-19 23:32

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.