Jamie McClenaghan
Jamie McClenaghan

Reputation: 49

Set variable by running a function

I am new to Python and it's workings. I am wanting to simply create a variable called 'code' and fill this variable with the method i have made.

Here is the code

codeLength = 4
code = GenerateCode()
print(code)

def GenerateCode(code):
    symbols = ['A', 'B', 'C', 'D', 'E', 'F']
    random.shuffle(symbols)
    del symbols[(symbols.count - codeLength)]
    code = symbols
    return code

So the method should pick 4 letters from the array symbols be randomising it then removing 2. I want the letters at the end to be the variable 'code'

Thanks

Upvotes: 0

Views: 82

Answers (1)

Olivier Melançon
Olivier Melançon

Reputation: 22324

There are the main errors with your code.

  • You call a function before defining it;

  • You delete a single character out of your list, but it would be better to slice it;

  • codeLength would be better passed as an argument.

Here is an example fixing those issues.

import random

def gen_code(length, symbols='ABCDEF'):
    code = random.sample(symbols, length)
    return str(code)

code = gen_code(4)

As an improvement, notice how setting symbols as a keyword argument allows to keep a default value but change the character if need be.

Upvotes: 2

Related Questions