Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python, list empties upon exiting while loop

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading