博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
练习题
阅读量:7231 次
发布时间:2019-06-29

本文共 9130 字,大约阅读时间需要 30 分钟。

1.用户输入用户名和密码还有验证码. 

用户可以有三次登录的机会. 但是验证码如果输入错误. 不计算在内.

from random import randintuser = 'chenweixian'pwd = '123'count = 1while count <= 3:    Verify_code = ''    for i in range(4):        Verify_code += chr(randint(65, 90))    In_UserName = input('please input you username:')    In_PassWord = input('please input you password:')    In_Verify_Code = input('input verify_code__%s__:'%Verify_code).upper()    if In_Verify_Code != Verify_code:        print('Verify_Code is fail !!!')        continue    if  In_UserName == user and In_PassWord == pwd:        print('Login Successful !!! ')        break    else:        print('Username or PassWord is fail,Please input again')        count += 1    print('You Only have %s change to login' % (4 - count))
View Code

 

简版购物车

count1 = 1while count1 <= 3:    Name_Input = input('请输入用户名:')    Pwd_Input = input('请输入密码:')    if Name_Input == 'alex' and Pwd_Input == '123':        Money_Input = int(input('请输入你的工资:'))        while 1 :            print('******商品菜单********')            for i in enumerate(goods,1):                print(i[0],i[1]['name'],i[1]['price'])            num  = input('请输入你想要购买的商品的编号:')            if num.upper() == 'Q':                print(dd)                print('购物车')                print('商品名称''\t','价格''\t','购买数量''\t','总价')                for  el in dd:                    print(el['name'],el['price'],el['count'],el['price']*el['count'])                break            num = int(num)            if num < 1 or num > len(goods):                print("您输入的商品不存在")                continue            if goods[num-1]['price'] < Money_Input:                print(goods[num-1])                Money_Input -= goods[num-1]['price']                for  i in dd:                   if i['name'] == goods[num-1]['name']:                        i['count'] = i['count']+1                        break                else:                    dd.append({
'name':goods[num-1]['name'],'price':goods[num-1]['price'],'count':1}) else: while 1 : if goods[num - 1]['price'] > Money_Input: hh = input('余额不足,请充值:Y/N') if hh.lower() == 'y': Money_Input += int(input('请输入你要充值的金额:')) else: print('余额不足,重新选择商品') break else: Money_Input -= goods[num - 1]['price'] for i in dd: if i['name'] == goods[num - 1]['name']: i['count'] += 1 else: dd.append({
'name': goods[num - 1]['name'], 'price': goods[num - 1]['price'], 'count': 1}) print(dd) break print('%s购买成功,你的余额为%s' %(goods[num-1]['name'],Money_Input)) else: if count1 == 3: print('你已经三次输入错误,退出系统') else: print('用户名或密码错误,请重新输入') count1 += 1
View Code

 

Hr

'''HR⼈⼒资源管理.1. 菜单: ("查看员⼯信息","添加员⼯信息", "修改员⼯信息", "删除员⼯信息", "退出")2. 添加员⼯信息: ⽤户输入员⼯的基本信息(id, name, birthday, salary, time), 将员⼯信息写入到⽂件emp.db⽂件内3. 修改员⼯信息: 显⽰所有员⼯信息. 然后让⽤户选择要修改的员⼯的id. 然后让⽤户输入员⼯的⼯资, 将员⼯的⼯资修改为⽤户输入的⼯资. 其余内容不做改动4. 删除员⼯信息: 显⽰所有员⼯信息. 然后⽤户选择要删除的员⼯id, 根据⽤户输入的id删除该员⼯的全部信息5. 查看员⼯信息: 显⽰出所有员⼯的基本信息. 以上操作都需要围绕着emp.db来完成. 扩展(升级题): ⽤户的每⼀次操作成功都要将⽤户执⾏的操作记录在emp.log⽂件中(查看员⼯信息除外). 例如: ⽤户选择"添加员⼯信息". 当添加动作执⾏完毕, 在emp.log中记录⼀句话: 管理员在xxxx-xx-xx hh:mm:ss时间执⾏了添加员⼯信息操作. 添加的员⼯信息为: xxxxxxxxxxxxx 以此类推. 每次操作成功后都要记录信息. (查看员⼯信息除外) emp.db ⽂件中的内容格式⾃⼰定义. 这个没有要求. 但是要符合你⾃⼰的设计需求'''import timeimport os# 负责记录日志def emplog(content):    f = open("emp.log", mode="a", encoding="utf-8")    f.write(content + "\n")    f.close()def chakan():    f = open("emp.db", mode="r", encoding="utf-8")    print("工号\t姓名\t工资\t生日")    for line in f:        d = eval(line.strip())        # print("%s\t%s\t%s\t%s" % (d['empno'], d['name'], d['salary'], d['birthday']))        print(f"{d['empno']}\t{d['name']}\t{d['salary']}\t{d['birthday']}\t")    print("员工信息显示完毕!")def tianjia():    while 1:        # (id, name, birthday, salary, time)        empno = input("请输入员工的empno: ")        f = open("emp.db", mode="r", encoding="utf-8")        for line in f:            d = eval(line.strip())            if d['empno'] == empno:                break        else:            name = input("请输入员工的姓名:")            birthday = input("请输入员工的生日:")            salary = input("请输入员工的工资:")            intime = time.strftime("%Y-%m-%d")            dic = {
"empno":empno, "name":name,"birthday":birthday, "salary":salary, "intime":intime} f = open("emp.db", mode="a", encoding="utf-8") f.write(str(dic)+"\n") f.close() print("添加成功") emplog("管理员在%s添加了一个员工, 该员工信息为%s" % (time.strftime("%Y-%m-%d %H:%M:%S"), str(dic))) return # 添加成功 f.close()def xiugai(): chakan() # 显示所有员工信息 empno = input("请输入你要修改的员工的工号:") f = open("emp.db", mode="r", encoding="utf-8") for line in f: d = eval(line.strip()) if d['empno'] == empno: break else: print("没有此员工") return f.close() salary = input("请输入该员工的工资") with open("emp.db", mode="r", encoding="utf-8") as f1, \ open("emp.db_副本", mode="w", encoding="utf-8") as f2: for line in f1: d = eval(line.strip()) if d['empno'] == empno: d['salary'] = salary emplog("管理员在%s修改了一个员工, 该员工信息为%s" % (time.strftime("%Y-%m-%d %H:%M:%S"), str(d))) f2.write(str(d) + "\n") os.remove("emp.db") os.rename("emp.db_副本", "emp.db")def shanchu(): chakan() # 显示所有员工信息 empno = input("请输入你要删除的员工工号:") with open("emp.db", mode="r", encoding="utf-8") as f1, \ open("emp.db_副本", mode="w", encoding="utf-8") as f2: for line in f1: d = eval(line.strip()) if d['empno'] == empno: emplog("管理员在%s删除了一个员工, 该员工信息为%s" % (time.strftime("%Y-%m-%d %H:%M:%S"), str(d))) continue f2.write(str(d) + "\n") os.remove("emp.db") os.rename("emp.db_副本", "emp.db")menu = ("查看员⼯信息","添加员⼯信息", "修改员⼯信息", "删除员⼯信息", "退出")while 1: for i in range(len(menu)): print(i+1, menu[i]) num = input("请输入你要执行的菜单") if num == '1': chakan() elif num == "2": tianjia() elif num == "3": xiugai() elif num == "4": shanchu() elif num == '5': print("系统退出") exit() else: print("对不起没有此菜单")
View Code

 TCP类型scoket 通信(可以验证粘包现象,包含通信循环,连接循环部分)

import socketimport subprocessserver = socket.socket()ip_port = ('127.0.0.1',8080)server.bind(ip_port)server.listen(2)con,addr = server.accept()# print(addr)while 1 :    client_cmd = con.recv(1024).decode('utf-8')    # print('*****')    sub = subprocess.Popen(        client_cmd,        shell=True,        stderr=subprocess.PIPE,        stdout=subprocess.PIPE,)    # print('********')    cmd_res = sub.stdout.read()    print(type(cmd_res))    con.sendall(cmd_res)    print('结果长度>>>', len(cmd_res))
服务端配置
import socketclient = socket.socket()ip_port = ('127.0.0.1',8080)client.connect(ip_port)while 1:    client_cmd = client.send(input('请输入系统指令>>>').encode('utf-8'))    cmd_result = client.recv(1024).decode('gbk')    print(cmd_result)
客户端配置

 

 

进程池版的socket 并发聊天

#Pool内的进程数默认是cpu核数,假设为4(查看方法os.cpu_count())#开启6个客户端,会发现2个客户端处于等待状态#在每个进程内查看pid,会发现pid使用为4个,即多个客户端公用4个进程from socket import *from multiprocessing import Poolimport osserver=socket(AF_INET,SOCK_STREAM)server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)server.bind(('127.0.0.1',8080))server.listen(5)def talk(conn):    print('进程pid: %s' %os.getpid())    while True:        try:            msg=conn.recv(1024)            if not msg:break            conn.send(msg.upper())        except Exception:            breakif __name__ == '__main__':    p=Pool(5)    while True:        print('ggggg')        conn,*_=server.accept()        print('bbbbb')        p.apply_async(talk,args=(conn,))        print('hhhhhh')        # p.apply(talk,args=(conn,client_addr)) #同步的话,则同一时间只有一个客户端能访问
服务器端
from socket import *client=socket(AF_INET,SOCK_STREAM)client.connect(('127.0.0.1',8080))while True:    msg=input('>>: ').strip()    if not msg:continue    client.send(msg.encode('utf-8'))    msg=client.recv(1024)    print(msg.decode('utf-8'))
客户端

 

多线程实现socket

import multiprocessingimport threadingimport sockets=socket.socket(socket.AF_INET,socket.SOCK_STREAM)s.bind(('127.0.0.1',8080))s.listen(5)def action(conn):    while True:        data=conn.recv(1024)        print(data)        msg = input('服务端输入:') #在多线程里面可以使用input输入内容,那么就可以实现客户端和服务端的聊天了,多进程不能输入        conn.send(bytes(msg,encoding='utf-8'))if __name__ == '__main__':    while True:        conn,addr=s.accept()        p=threading.Thread(target=action,args=(conn,))        p.start()tcp_server.py
服务端
import sockets=socket.socket(socket.AF_INET,socket.SOCK_STREAM)s.connect(('127.0.0.1',8080))while True:    msg=input('>>: ').strip()    if not msg:continue    s.send(msg.encode('utf-8'))    data=s.recv(1024)    print(data)tcp_client.py
客户端

 

转载于:https://www.cnblogs.com/vivi0403/p/9973973.html

你可能感兴趣的文章
第七周
查看>>
java 字符串与字符数组相互转换
查看>>
遍历js的obj中所有属性得key
查看>>
Validate XML using a XSD (XML Schema)
查看>>
A Tour of Go Exercise: Errors
查看>>
Windows 7 转移用户文件夹
查看>>
Linux shell的环境配置和命令行技巧
查看>>
Objective-C中的SEL、IMP和Class类型(转)
查看>>
20180814 基于51单片机的数码相机实验指导书编写,继续挖坑
查看>>
数据库中的T-sql语句 条件修改 高级查询
查看>>
win7开机密码忘记了
查看>>
阿里前端两年随想
查看>>
day28(ajax之js原生代码实现)
查看>>
用自定义属性attr或prop方法,遍历获取当前点击a的titleid
查看>>
安卓真机测试遇到的检测不到安卓设备的问题
查看>>
我的大学,我的梦
查看>>
洛谷训练P1008(循环+暴力)
查看>>
【挖坟】HDU3205 Factorization
查看>>
reentrantlock用于替代synchronized
查看>>
Android包管理机制(二)PackageInstaller安装APK
查看>>