Python代码实例

1、四位数字字母验证码的生成实例

import random
if __name__ =="__main__": #四位数字字母验证码的生成
checkcode="" #保存验证码的变量
for i in range(4):
index=random.randrange(0,4) #生成一个0~3中的数
if index!=i and index +1 !=i:
checkcode +=chr(random.randint(97,122)) # 生成a~z中的一个小写字母
elif index +1==i:
checkcode +=chr(random.randint(65,90) ) # 生成A~Z中的一个大写字母
else:
checkcode +=str(random.randint(1,9)) # 数字1-9
print(checkcode)

输出为:m47A、8wQ9、vugS

2、格式化时间函数

def formatTime(longtime):
'''格式化时间的函数'''
import time
return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(longtime))

3、记录显示登录日志实例

import time
def show_info():
print('''输入提示数字,执行相应操作
0:退出
1:查看登录日志
''')
def write_loginfo(username):
"""
将用户名和登录时间写入日志
:param username: 用户名
"""
with open('log.txt','a') as f:
string = "用户名:{} 登录时间:{}\n".format(username ,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
f.write(string)
def read_loginfo():
"""
读取日志
"""
with open('log.txt','r') as f:
while True:
line = f.readline()
if line == '':
break # 跳出循环
print(line) # 输出一行内容
if __name__ == "__main__":
# 输入用户名
username = input('请输入用户名:')
# 检测用户名
while len(username) < 2 :
print('用户名长度应不少于2位')
username = input('请输入用户名:')
# 输入密码
password = input('请输入密码:')
# 检测密码
while len(passw ord) < 6 :
print('密码长度应不少于6位')
password = input('请输入密码:')
print('登录成功')
write_loginfo(username) # 写入日志
show_info() # 提示信息
num = int(input('输入操作数字:')) # 输入数字
while True:
if num == 0:
print('退出成功')
break
elif num == 1:
print('查看登录日志')
read_loginfo()
show_info()
num = int(input('输入操作数字:'))
else:
print('您输入的数字有误')
show_info()
num = int(input('输入操作数字:'))

4、模拟淘宝客服自动回复

# 模拟淘宝客服自动回复
def find_answer(question):
with open('reply.txt','r') as f :
while True:
line=f.readline()
if not line: #也可以为if line==''
break
keyword=line.split('|')[0]
reply=line.split('|')[1]
if keyword in question:
return reply
return '对不起,没有你想要找的问题'
if __name__ =='__main__':
question=input('请输入想要提问的内容:')
while True:
if question=='bye':
break
reply=find_answer(question)
if not reply:
question=input("小蜜不懂您在说什么,您可以问一些与订单、账户和支付相关的内容(退出请输入bye):")
else:
print(reply)
question=input("您可以问一些与订单、账户和支付相关的内容(退出请输入bye):")
print('谢谢,再见!')

5、求最大公约数和最小公倍数 (辗转相除法)

最大公约数:指两个或多个整数共有约数中最大的一个

最小公倍数:两个或多个整数公有的倍数叫做它们的公倍数,其中除0以外最小的一个公倍数就叫做这几个整数的最小公倍数

二者关系:两个数之积=最小公倍数*最大公约数

a=int(input('输入数字1:'))
b=int(input('输入数字2:'))
s=a*b
while a%b!=0:
a,b=b,(a%b)
print(a)
print(b)
else:
print(b,'is the maximum common divisor最大公约数')
print(s//b,'is the least common multiple,最小公倍数')

更相减损法

a=int(input('please enter 1st num:'))
b=int(input('please enter 2nd num:'))
s=a*b
while a!=b:
if a>b:
a-=b
elif a<b:
b-=a
else:
print(a,'is the maximum common divisor')
print(s//a,'is the least common multiple')
#运行结果
please enter 1st num:40
please enter 2nd num:60
20 is the maximum common divisor
120 is the least common multiple

6、判断是否为闰年 (辗转相除法)

# 判断是否为闰年
while True:
try:
num=eval(input("请输入一个年份:"))
except:
print('输入错误年份')
continue
if (num %4==0 and num%100 !=0) or num %400==0:
print(num,"是闰年")
else:
print(num,"不是闰年")
import calendar
year = int(input("请输入年份:"))
check_year=calendar.isleap(year)
if check_year == True:
print ("闰年")
else:
print ("平年")

7、Python统计字符串中数字,字母,汉字的个数

import re
str_test='abcdefgHABC123456中华民族'
#把正则表达式编译成对象,如果经常使用该对象,此种方式可提高一定效率
num_regex = re.compile(r'[0-9]')
zimu_regex = re.compile(r'[a-zA-z]')
hanzi_regex = re.compile(r'[\u4E00-\u9FA5]')
print('输入字符串:',str_test)
#findall获取字符串中所有匹配的字符
num_list = num_regex.findall(str_test)
print('包含的数字:',num_list)
zimu_list = zimu_regex.findall(str_test)
print('包含的字母:',zimu_list)
hanzi_list = hanzi_regex.findall(str_test)
print('包含的汉字:',hanzi_list)

#羊车门问题

import random as r
#总次数
total=1000000 #1000,1W,10W,100W
#换与不换的获胜次数
win1=0
win2=0
for i in range(total):
#模拟选择过程
man=r.randint(1,3)
car=r.randint(1,3)
#结果:一开始为车门,不换+1.
# 否则则一开始为羊门,换+1.
if man==car:
win1+=1
else:
win2+=1
print("在{}次实验中:".format(total))
print("若不更改门,获胜概率为{:.3}%.".format((win1/total)*100))
print("若更改门,获胜概率为{:.3}%.".format((win2/total)*100))
import random
x=random.randint(5000,10000)
print(x)
change=0
nochange=0
for i in range(1,x+1):
a=random.randrange(1,4)
b=random.randrange(1,4)
if a==b:
nochange=nochange+1
else:
change=change+1
print("不更改选择得到汽车的概率为{:.2f}".format(nochange/x))
print("更改选择得到汽车的概率为{:.2f}".format(change/x))

版权所有

Andhui

原文链接:https://www.cnblogs.com/huigebj/p/11295202.html