How can I create an arbitrary hexdigit code generator using .join and for loops?

I am new to programming, and one assignment I need to do is to create a random hexdigit color code generator using for loops and .join. Is my program below even close to how you do it, or is it completely disabled? And is there a way to make a random number of numbers and letters over 6?

import random str = ("A","B","C","D","E","F","G","H") seq = ("1","2","3","4","5","6", "7","8","9") print '#', for i in range(0,3): letter = random.choice(str) num = random.choice(seq) print num.join(letter), print letter.join(num) 
+7
python string join random for-loop
Nov 08 '13 at 1:03
source share
3 answers

Lines can be repeated, so my code will look like this.

 import random def gen_hex_colour_code(): return ''.join([random.choice('0123456789ABCDEF') for x in range(6)]) if __name__ == '__main__': print gen_hex_colour_code() 

leads to

 In [8]: 9F04A4 In [9]: C9B520 In [10]: DAF3E3 In [11]: 00A9C5 

Then you can put this in a separate file, for example, myutilities.py

Then in your main python file you will use it like this:

 import myutilities print myutilities.gen_hex_colour_code() 

The if __name__ == '__main__': will be executed only when the myutilities.py file is run directly. It will not be executed when importing from another file. This usually happens when performing test functions.

Also note that this uses syntax for Python 2.7. In Python 3.0, the main difference is that printing is a function, and you have to use print (gen_hex_colour_code ()). See http://docs.python.org/3.0/whatsnew/3.0.html for more information on how things are different if you are confused.

Why am I still using Python 2.7? Many scientific python modules still use version 2.7, but for newbies in Python, I suggest you stick with 3.0

+16
Nov 08 '13 at 1:22
source share

One compact way to do this is to use a list of concepts (which are a specific type of loop):

 >>> alpha = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F") >>> ''.join([random.choice(alpha) for _ in range(6)]) '4CFDE4' 

You can shorten the alphabet string with range and map :

 >>> alpha = map(str, range(10)) + ["A", "B", "C", "D", "E", "F"] 

Or just just use the line:

 >>> alpha = "ABCDEF0123456789" 

PS. Since colors are hexadecimal, why not just create a random number and translate it into hexadecimal?

 >>> hex(random.randint(0, 16777215))[2:].upper() 'FDFD4C' 
+8
Nov 08 '13 at 1:07
source share
 import random keylist='0123456789ABCDEF' password=[] length=15 while len(password) < length: a_char = random.choice(keylist) password.append(a_char) print(''.join(password)) 
-one
Aug 25 '16 at 17:54 on
source share



All Articles