How to generate more characters?

Viewed 62

I'm making a code generator based on the popular game Among US, which has 4-letter game codes. I built this program to generate one for you, to see if it actually exists, but instead of four letters, only one gets generated four times.

How can I fix this? Thanks in advance!

import random
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
quantity = int(input('How many codes do you want? '))

def create_code():
     for c in range(4):
         code = ''
         code += random.choice(chars)

         return code

for i in range(0, quantity):
    print('Your code is', create_code())
    
4 Answers

Here is another way, which uses .choices() (plural)

import random
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
list_of_chars = random.choices(chars, k=4)
print(''.join(list_of_chars))

Try this

import random
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
quantity = int(input('How many codes do you want? '))

def create_code():
    code = ''
    for c in range(4):
        code += random.choice(chars)
    return code

for i in range(0, quantity):
    print('Your code is', create_code())

You initialize the variable code within your loop so it's reset every time. It should be:

import random
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
quantity = int(input('How many codes do you want? '))

def create_code():
    code = ''
    for c in range(4):
        code += random.choice(chars)
    return code

for i in range(0, quantity):
    print('Your code is', create_code())

A few problems. You are overwriting the code variable each time through the loop with code = ''. You are also returning from within the loop. Try this:

def create_code():
    code = ''
    for c in range(4):
        code += random.choice(chars)
    return code
Related