Aug-29-2022, 09:37 AM
(Aug-22-2022, 06:23 PM)Kjaglewicz Wrote: Hi All!
I need to write a function that returns a random id for an employee. Can anybody tell me why it returns... "None"? I'm stuck with it...
import random import string def generate_id(number_of_small_letters=4, number_of_capital_letters=2, number_of_digits=2, number_of_special_chars=2, allowed_special_chars=r"_+-!"): small_letters = string.ascii_lowercase capital_letters = string.ascii_uppercase digits = "0123456789" result_small = ''.join(random.choice(small_letters) for i in range (number_of_small_letters)) result_capital = ''.join(random.choice(capital_letters) for i in range (number_of_capital_letters)) result_digits = ''.join(random.choice(digits) for i in range (number_of_digits)) result_special_characters = ''.join(random.choice(allowed_special_chars) for i in range (number_of_special_chars)) random_characters = result_digits + result_small + result_capital + result_special_characters random_characters_list = list(random_characters.strip(" ")) final_result = random.shuffle(random_characters_list) return str(final_result)
Taking a step back and breaking the problem into smaller pieces is always a good idea when you bump up against something that doesn't work the way you expect it to.
Here's one approach that leverages the Python interactive interpreter:
>>> import random >>> import string >>> >>> number_of_small_letters=4 >>> small_letters = string.ascii_lowercase >>> >>> result_small = ''.join(random.choice(small_letters) for i in range (number_of_small_letters)) >>> result_small 'tjso' >>> >>> random_characters = result_small >>> random_characters_list = list(random_characters.strip(" ")) >>> random_characters_list ['t', 'j', 's', 'o'] >>> >>> r = random.shuffle(random_characters_list) >>> r >>> >>> repr(r) 'None' >>> >>> random_characters_list ['s', 'o', 'j', 't'] >>> >>> help(random.shuffle) Help on method shuffle in module random: shuffle(x, random=None) method of random.Random instance Shuffle list x in place, and return None. Optional argument random is a 0-argument function returning a random float in [0.0, 1.0); if it is the default None, the standard random.random will be used.
Per the output of help(), the shuffle method worked exactly as advertised.
Shuffle list x in place, and return None.Hopefully, the investigative work above would have pointed you towards the solution called out by @Gribouillis and @deanhystad :
return "".join(random_characters_list)