문제

I am making a serial key generator for a school exercise, and I am running into a small problem. When I run the program, and type in I want to make 20 serial keys, the program will make twenty of the same keys. The cause of this is in the for loop making variables every time it passes by. (The v{0} thing)

I can not figure out how to use another method to read all the values in a list, and create variables out of them.

My code:

import random, sys

class Application:

    def __init__(self):
        global i
        i = int(input("How many serial codes do you want to create?\n"))
        print("")
        self.main(i)


    def main(self, i):

        seq = "ABCDFGHJIKLMNOPQRSTUVWXYZ1234567890"
        store = []

        for z in range(0, i):  
            for x in range(0, 5):
                first = random.choice(seq)
                second= random.choice(seq)
                third = random.choice(seq)
                fourth =random.choice(seq)
                fifth = random.choice(seq)
                serial = first + second + third + fourth + fifth
                store.append(serial)

            for y, item in enumerate(store):
                setattr(sys.modules[__name__], 'v{0}'.format(y), item)

            create = v0 + "-" + v1 + "-" + v2 + "-" + v3 + "-" + v4
            print(create)
        print("\nCreated", i, "serial keys!")

if __name__ == '__main__':
    app = Application()
도움이 되었습니까?

해결책

You are doing some very funky stuff there that is totally not necessary.

This loop is your problem:

for y, item in enumerate(store):
    setattr(sys.modules[__name__], 'v{0}'.format(y), item)

You are setting the same 5 global variables over and over again, overwriting the previous version. Your use of setattr(sys.modules[__name__], ..) is totally not needed when you have the globals() function giving you the global namespace as a dictionary. But setting global variables to solve a simple problem is like using a shotgun to catch one gnat.

Your code could be vastly simplified:

def main(self, count):
    seq = "ABCDFGHJIKLMNOPQRSTUVWXYZ1234567890"

    for i in range(count):
        print('-'.join(''.join(random.choice(seq) for _ in range(5)) for _ in range(5)))

    print("\nCreated {} serial keys!".format(count))

Sample printed output for count set to 5:

LWLGX-F6MNR-9YIZC-H23TK-TIGB9
YALYY-4ZARO-8H9BV-YMHVD-HFFGP
JNA5R-65GT1-TZ3BM-PNMZI-56NM3
39VCY-MLZ98-SU1PP-PYMX7-RZJQZ
76LGC-VF5MG-LK7C4-XPUSO-H0B97

다른 팁

You may find it useful to print store at the end for debugging purposes. You continually append to the list, but only ever read the first five elements.

The use of global variables is a bit odd to me, but the underlying problem is the way you're using the list.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top