python练手程序_100个python练手小程序
1.生成200個指定長度的隨機碼
import random
import string
def rand_str(num,len=7):
f = open('file.txt','w')
count = 1
for i in range(num):
restr = ''
chars = string.ascii_lowercase+ string.digits
for i in range(len):
restr += random.choice(chars)
f.write( str(count)+ ' ' + restr +'\n')
count += 1
f.close()
if __name__ == '__main__':
rand_str(200,20)
知識點:
1.隨機取值:
random.choice
2.w是寫入,wb就是寫入二進制文件了。
f = open('file.txt','w')
3.int轉(zhuǎn)為str
str(count)
二、把1中生成的隨機碼存到數(shù)據(jù)庫中
#-*- coding:utf-8 -*-
'''
02
'''
import string
import random
import pymysql
#用于生成隨機字符串List的函數(shù)
def geneRandStr(num,len=7):
strList = []
for i in range(num):
restr = ''
chars = string.ascii_lowercase + string.digits
for i in range(len):
restr += random.choice(chars)
strList.append(restr)
return strList
#把字符串List存入數(shù)據(jù)庫
def storeInMysql(codeList):
try:
conn = pymysql.connect(host='127.0.0.1',user = 'root',
password = '123456',db = 'pytest')
cur = conn.cursor()
except BaseException as e:
print(e)
else:
try:
cur.execute('DROP DATABASE pytest ')
cur.execute('CREATE DATABASE IF NOT EXISTS pytest ')
cur.execute('USE pytest')
cur.execute('''CREATE TABLE IF NOT EXISTS code(
id INT NOT NULL AUTO_INCREMENT,
code VARCHAR (32) NOT NULL,
PRIMARY KEY (id)
)''')
for code in codeList:
cur.execute('INSERT INTO code(code) VALUES (%s)',(code))
cur.connection.commit()
except BaseException as e:
print(e)
finally:
cur.close()
conn.close()
if __name__ == '__main__':
storeInMysql(geneRandStr(20,10))
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的python练手程序_100个python练手小程序的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何选释迦果?
- 下一篇: 想把飘窗打造成小茶室,该如何低成本搞定?