标签:odi random模块 else png pytho code 分享 字符串 循环
Random模块生成随机数
>>> print random.random() #随机生成0-1的小数
0.772367387029
>>> print random.randint(1,200) #随机生成整数小于或者等于
107
>>> print random.randrange(1,200) #随机生成整数小于最大的数
152
假如想随机生成字母可以使用python里面的chr方法结合random生成字母
chr(random.randint(65,121))
使用以上方法生成一个带大写字母和数字的随机数
#!/usr/bin/python
# -*- coding:utf-8 -*-
import random
checkcode = ‘‘ #定义一个空的字符串
for i in range(4): #循环4次
current = random.randrange(0,4) #随机生成0,1,2,3
if current != i: #如果生成的随机数刚刚好等于i则随机生成一个大写字母赋值给temp
temp = chr(random.randint(65,90))
else: #否则随机生成0,1,2,3,4,5,6,7,8,9数字赋值给temp
temp = random.randint(0,9)
checkcode += str(temp) #一次循环生成的一个数字或者大写字符赋值给字符串
print checkcode #四次循环以后打印字符串
执行

标签:odi random模块 else png pytho code 分享 字符串 循环
原文地址:http://www.cnblogs.com/minseo/p/6897935.html