Python, list empties upon exiting while loop

Question:

I’m writing up a D&D 5e character generator. Using a while loop I’m defining the ability score generation. Rolling 4 6 sided dice and dropping the lowest as below.

import random
abset=list()
def abrl():             #define ability score roll
    abnum=0
    abset=list()
    rollfnl=set()
    while abnum<6:
        rollstat=random.sample(range(1,7),4)
        rollstat.sort(reverse=True)
        tempab=(sum(rollstat[:3]))
        abset.append(tempab)
        print(abset)
        abnum+=1

print('Welcome to this chargen!')
print("let's roll ability scores first!")
abrl()
print(abset)

The print within the while is to troubleshoot abset coming out as []. Thus the following output.

Welcome to this chargen!
let's roll ability scores first!
[13]
[13, 15]
[13, 15, 13]
[13, 15, 13, 13]
[13, 15, 13, 13, 12]
[13, 15, 13, 13, 12, 13]
[]

How come the list gets emptied after, I assume, it exits the while loop or abrl function?
Thank you for any help and patience!

Asked By: jomake

||

Answers:

Global variables are read-only in function bodies, unless using the global keyword.

Here, you define another abset list inside the function, not the same as the global one.

Do this instead :

import random
abset=list()
def abrl():             #define ability score roll
    abnum=0
    global abset
    rollfnl=set()
    while abnum<6:
        rollstat=random.sample(range(1,7),4)
        rollstat.sort(reverse=True)
        tempab=(sum(rollstat[:3]))
        abset.append(tempab)
        print(abset)
        abnum+=1

print('Welcome to this chargen!')
print("let's roll ability scores first!")
abrl()
print(abset)
Answered By: 0xRyN

Variables defined inside a method only exist inside that method. You can think of methods as black boxes – nothing goes in or out, except what you explicitly allow in or out.

To return the abset, add the following line to the end of the method: return abset.

Then, when you call the method, resave the variable to the global scope by calling abset = abrl() rather than just abrl()

Answered By: David_Leber
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.