Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate more characters?

Tags:

python

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())
    
like image 635
MadeBy Alvaropop Avatar asked Dec 06 '25 06:12

MadeBy Alvaropop


2 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))
like image 157
jsmart Avatar answered Dec 07 '25 19:12

jsmart


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

like image 41
Reza Avatar answered Dec 07 '25 20:12

Reza