个人整理Python代码实例

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

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

输出为:m47A、8wQ9、vugS

-------------------------------

2。格式化时间函数

1 def formatTime(longtime):
2 '''格式化时间的函数'''
3 import time
4 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('输入操作数字:'))

------------------------------
3。模拟淘宝客服自动回复
 1 # 任务2:模拟淘宝客服自动回复
 2 
 3 def find_answer(question):
 4     with open('reply.txt','r') as f :
 5         while True:
 6             line=f.readline()
 7             if  not line:   #也可以为if  line==''
 8                 break
 9             keyword=line.split('|')[0]
10             reply=line.split('|')[1]
11             if keyword in question:
12                 return reply
13         return '对不起,没有你想要找的问题'
14          
15 if __name__ =='__main__':
16     question=input('请输入想要提问的内容:')
17     while True:
18         if question=='bye':
19             break
20         reply=find_answer(question)
21         if not reply:
22             question=input("小蜜不懂您在说什么,您可以问一些与订单、账户和支付相关的内容(退出请输入bye):")
23         else:
24             print(reply)
25             question=input("您可以问一些与订单、账户和支付相关的内容(退出请输入bye):")
26     print('谢谢,再见!')
27         

 

 

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

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

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

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

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

更相减损法

 1 a=int(input('please enter 1st num:'))
 2 b=int(input('please enter 2nd num:'))
 3 s=a*b
 4      
 5 while a!=b:
 6     if a>b:
 7         a-=b
 8     elif a<b:
 9         b-=a
10 else:
11     print(a,'is the maximum common divisor')
12     print(s//a,'is the least common multiple')
13  
14 #运行结果
15 please enter 1st num:40
16 please enter 2nd num:60
17 20 is the maximum common divisor
18 120 is the least common multiple
5。判断是否为闰年 (辗转相除法)
 1 # 判断是否为闰年
 2 while True:
 3     try:
 4         num=eval(input("请输入一个年份:"))
 5     except:
 6         print('输入错误年份')
 7         continue
 8     if (num %4==0 and num%100 !=0) or num %400==0:
 9         print(num,"是闰年")
10     else:
11         print(num,"不是闰年")

 

import calendar

year = int(input("请输入年份:"))
check_year=calendar.isleap(year)
if check_year == True:
    print ("闰年")
else:
    print ("平年")
6。Python统计字符串中数字,字母,汉字的个数
 1 import re
 2 str_test='abcdefgHABC123456中华民族'
 3  
 4 #把正则表达式编译成对象,如果经常使用该对象,此种方式可提高一定效率
 5 num_regex = re.compile(r'[0-9]')
 6 zimu_regex = re.compile(r'[a-zA-z]')
 7 hanzi_regex = re.compile(r'[\u4E00-\u9FA5]')
 8 
 9 print('输入字符串:',str_test)
10 #findall获取字符串中所有匹配的字符
11 num_list = num_regex.findall(str_test)
12 print('包含的数字:',num_list)
13 zimu_list = zimu_regex.findall(str_test)
14 print('包含的字母:',zimu_list)
15 hanzi_list = hanzi_regex.findall(str_test)
16 print('包含的汉字:',hanzi_list)

 #羊车门问题

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

 

 
posted @ 2019-08-03 16:13  Andhui  阅读(98853)  评论(1编辑  收藏  举报