简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM