我将如何使用.join和for循环随机hexdigit代码生成器? [英] How would I make a random hexdigit code generator using .join and for loops?

查看:279
本文介绍了我将如何使用.join和for循环随机hexdigit代码生成器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程新手,我必须做的一件事就是创建一个随机的hexdigit颜色代码生成器,使用for循环和.join。
我的程序是否接近你如何做,还是完全关闭?
而且,有没有办法让随机数量和字母出现在6?

  import random 
str =(A,B,C,D,E,F,G,H)

seq = 1,2,3,4,5,6,7,8,9)

print'#',$ b (0,3):

字母= random.choice ),
print letter.join(num)


解决方案

<字符串可以迭代,所以我的代码看起来像这样。

 导入随机

def gen_hex_colour_code():
return''.join([在范围(6)中为x的random.choice('0123456789ABCDEF')])

if __name__ =='__main__':
print gen_hex_colour_code()


$ b



$ p $ 在[8] :9F04A4

在[9]中:C9B520

在[10]中:DAF3E3

In [11]:00A9C5

然后你可以把它放在一个单独的文件中,例如 myutilities.py

  code> import myutilities 

print myutilities.gen_hex_colour_code()

如果直接运行myutilities.py文件,那么 if __name__ =='__main __':部分只会被执行。从另一个文件导入时不会执行。这通常是测试函数的地方。



另外,请注意,这是使用Python 2.7的语法。在Python 3.0中,一个主要的区别是print是一个函数,你将不得不使用print(gen_hex_colour_code())。有关更多信息,请参阅 http://docs.python.org/3.0/whatsnew/3.0.html 如果你感到困惑,情况会有什么不同。

为什么我仍然在使用Python 2.7?许多科学的Python模块仍然使用2.7版本,但对于Python的新手,我建议你坚持使用3.0


I am new to programming and one assignment I have to do is create a random hexdigit colour code generator using for loops and .join. Is my program below even close to how you do it, or is it completely off? And, is there a way to make a random amount of numbers and letters appear within 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)

解决方案

Strings can be iterated over, so my code would 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()

results in

In [8]: 9F04A4

In [9]: C9B520

In [10]: DAF3E3

In [11]: 00A9C5 

You could then put this in a separate file called for example, myutilities.py

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

import myutilities

print myutilities.gen_hex_colour_code()

The if __name__ == '__main__': part will only get executed if you run the myutilities.py file directly. It will not execute when you import it from another file. This is generally where testing functions go.

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

Why would I still be using Python 2.7? Many scientific python modules are still using the 2.7 variant, but for a newbie to Python, I would suggest you stick with 3.0

这篇关于我将如何使用.join和for循环随机hexdigit代码生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆