首页 > 代码库 > 现实应用实例

现实应用实例

1、购物车

c=[]
sum=0
a=[
    {"name":"电脑","price":1000},
    {"name":"鼠标","price":2000},
    {"name":"优盘","price":3000},
    {"name":"硬盘","price":4000},
    {"name":"音响","price":5000}
]
for i in a:
    print(i["name"],i["price"])
b=int(input("请输入总资产:"))
while True:
    d=input("请输入需要购买的商品名称(输入y退出):")
    if d=="y":
        break
    for j in a:
        if d==j["name"]:
            c.append([j["name"],j["price"]])
for k in c:
    sum=sum+k[1]
print(c)
print("总价格:",sum)
if sum>b:
    print("余额不足,请充值")
    x = input("y:充值,n:退出")
    if x=="n":
        print("欢迎下次光临")
    if x=="y":
        while True:
            p=int(input("请输入充值金额:"))
            b=b+p
            print("恭喜充值成功    余额:",b,"结算金额:",b-sum)
            s=input("是否结算? 结算:1  继续充值:2    :")
            if s=="1":
                if sum>b:
                    print("金额不足,请继续充值")
                if sum<b:
                    print("购物成功,欢迎下次光临")
                    break
            if s=="2":
                continue
else:
    print("购物成功")

 2、验证码

import random                          #导入random模块
temp=""                                #定义一个空字符串,为后面拼接用
for i in range(4):                    #循环四次,生成四位的验证码
    j=random.randrange(5)             #随机生成一个数
    if j==3 or j==1:                 #如果生成1或3的话就让第一位为数字
        b=random.randrange(0,9)
        temp=temp+str(b)             #生成的整数必须转成字符串类型进行拼接
    else:
        a=random.randrange(65,90)
        temp=temp+chr(a)
print(temp)

 3、三级联动

dict= {
    "东北":{
        "吉林省":{
            "吉林市":[‘吉林市1‘,‘吉林市2‘],
            "长春":[‘长春1‘,‘长春2‘],},
        "辽宁省":{
            "沈阳":[‘沈阳1‘,‘沈阳2‘,‘沈阳3‘],
            "大连":[‘大连1‘,‘大连2‘],
                },
            },
    ‘华北‘:{
        ‘河北省‘:{
            ‘廊坊‘:[‘廊坊1‘,‘廊坊2‘],
            ‘保定‘:[‘保定1‘,‘保定2‘],
                },
        ‘内蒙古‘:{
            ‘呼和浩特‘:[‘呼和浩特1‘,‘呼和浩特2‘,‘呼和浩特3‘],
            ‘包头‘:[‘包头1‘,‘包头2‘]
                },

        },
    }
for i in dict:
    print(i)
a=input("请输入所要进入的地区:")
for o in dict[a]:
    print(o)
b=input("请输入要进入的省:")
for p in dict[a][b]:
    print(p)
c=input("请输入所要进入的市:")
for l in dict[a][b][c]:
    print(l)

 4、账号注册登录

def login(a,b):
    """
    用于用户名和密码的验证
    :param a: 用户名
    :param b: 密码
    :return:Ture  用户验证成功   False  用户验证失败
    """
    c=open("334.txt","r",encoding="utf-8")
    for line in c:
        line=line.strip()          #默认strip无参数用于去除换行符和空格
        new_line=line.split("*")    #有参数,移除两端指定的值
        if new_line[0]==a and new_line[1]==b:
            return True
    return False

def yanzheng(a):
    """
    用于验证用户名是否存在
    :param a: 用户名
    :return: True  用户名存在
    """
    c=open("334.txt","r",encoding="utf-8")
    for line in c:
        line=line.strip()          #默认strip无参数用于去除换行符和空格
        new_line=line.split("*")    #有参数,移除两端指定的值
        if new_line[0] ==a:
            return True

def zhuche(a,b):
    """
    用于用户注册
    :param a: 用户名
    :param b: 密码
    :return: True   注册成功
    """
    c = open("334.txt", "a", encoding="utf-8")
    temp="\n"+ a + "*" + b
    c.write(temp)
    return True

def min():
    print("欢迎登录英雄联盟官网")
    m=input("登录:1;注册:2")
    if m=="1":
        f1=input("请输入用户名:")
        f2=input("请输入密码:")
        f3 = login(f1, f2)
        if f3:
            print("登录成功")
        else:
            print("登录失败")
    elif m=="2":
        f1=input("请输入用户名:")
        f2=input("请输入密码:")
        f4=yanzheng(f1)
        if f4:
            print("用户名已存在")
        else:
            f5=zhuche(f1,f2)
            if f5:
                print("恭喜注册成功")

min()

 计算器

技术分享
import re
def f1(a):
    a = re.sub(" ","",a)
    a = a.replace(‘--‘, ‘+‘).replace(‘++‘, ‘+‘).replace(‘-+‘, ‘-‘).replace(‘+-‘, ‘-‘)
    if "*" in a or "/" in a:
        while True:
            b = re.split("([\-]?\d+[.]?\d*[/*][\-]?\d+[.]?\d*)",a,1)
            if len(b) == 3:
                c = re.split("([/*])",b[1])
                if c[1]== "*":
                    d = float(c[0])*float(c[2])
                    a = b[0]+str(d)+b[2]
                else:
                    d = float(c[0])/float(c[2])
                    a = b[0]+str(d)+b[2]
            else:
                e = re.findall("[\-+]?\d+\.?\d*", a)
                sun = 0
                for i in e:
                    sun = sun + float(i)
                return sun
    else:
        e = re.findall("[\-+]?\d+\.?\d*", a)
        sun = 0
        for i in e:
            sun = sun + float(i)
        return sun
def f2(a):
    a = re.sub(" ", "", a)
    if "*" in a or "/" in a:
        while True:
            a = a.replace(‘--‘, ‘+‘).replace(‘++‘, ‘+‘).replace(‘-+‘, ‘-‘).replace(‘+-‘, ‘-‘)
            b = re.split("(\d+[.]?\d*[/*][\-]?\d+[.]?\d*)", a, 1)
            if len(b) == 3:
                c = re.split("([/*])", b[1])
                if c[1] == "*":
                    d = float(c[0]) * float(c[2])
                    a = b[0] + str(d) + b[2]
                else:
                    d = float(c[0]) / float(c[2])
                    a = b[0] + str(d) + b[2]
            else:
                e = re.findall("[\-+]?\d+\.?\d*", a)
                sun = 0
                for i in e:
                    sun = sun + float(i)
                return sun
    else:
        e = re.findall("[\-+]?\d+\.?\d*", a)
        sun = 0
        for i in e:
            sun = sun + float(i)
        return sun
while True:
    r=re.split("\(([^()]+)\)",a,1)
    if len(r)==3:
        m=f1(r[1])
        a=r[0]+str(m)+r[2]
        print(a)
    else:
        r=f2(a)
        print(r)
        break
print(eval(a))
技术分享

 验证码

方法一

import random
li=[]
for i in range(6):
    a=random.randrange(0,9)
    if a==2 or a==6:
        b=random.randrange(0,9)
        li.append(str(b))
    else:
        b=random.randrange(65,90)
        li.append(chr(b))
print("".join(li))

 游戏

import random
import time
import sys
def outer(func):
    def f(n):
        print("* ☆∵▁▂▄▂▁★∵∴☆★∵∴\n∴★◢█████◣ * ☆∴★∵★ * ☆\n☆◢████☆██◣∴    天气冷了,☆\n◢■◤█████◥█◣送你一件毛衣, * ★\n◥◤  █████◥◤∵小心别著凉了\n\t  █████\n\t  █████")
        r = func(n)
        return r
    return f
for i in range(31):
    time.sleep(0.2)
    sys.stdout.write("\r")
    sys.stdout.write("%s %% |%s"%(int((i/30)*100),i*"██"))
    sys.stdout.flush()
print("\n\t\t欢迎来到英雄联盟PK擂台")
print("剑圣\t\t石头\t\t亚索\t\t瑞文\t\t薇恩\t\t老鼠\n卡牌\t\t劫\t\t剑姬\t\t安妮\t\t龙王\t\t女枪\n男枪\t\t螳螂\t\t蛮王\t\tEZ\t\t金克斯")
opp = input("请选择战斗的英雄1:")
odd = input("请选择战斗的英雄2:")
occ = input("确定:Y   重选:N")
class Swordman:
    def __init__(self,name):
        self.blood = 2000
        self.Name = name
    @outer
    def Q(self):
        self.blood = self.blood - 100
        print("霸道的%s使用地震碎片技能,%s受到100点伤害,当前血量:%s"%(opp,odd,self.blood))
    @outer
    def W(self):
        self.blood = self.blood + 200
        print("%s得到200点血量,当前血量:%s"%(odd,self.blood))
    @outer
    def E(self):
        self.blood = self.blood - 150
        print("霸道的%s使用野蛮打击技能,%s受到150点伤害,当前血量:%s"%(opp,odd,self.blood))
    @outer
    def R(self):
        self.blood = self.blood - 300
        print("霸道的%s使用势不可挡技能,%s受到300点攻击,当前血量:%s"%(opp,odd,self.blood))

class Rock:
    def __init__(self,name):
        self.blood = 3000
        self.Name = name
    @outer
    def Q(self):
        self.blood = self.blood - 150
        print("%s受到150点攻击,当前血量:%s" %(odd,self.blood))
    @outer
    def W(self):
        self.blood = self.blood - 120
        print("%s受到120点攻击,当前血量:%s" %(odd,self.blood))
    @outer
    def E(self):
        self.blood = self.blood - 110
        print("石头受到110点攻击,当前血量:%s" % self.blood)
    @outer
    def R(self):
        self.blood = self.blood - 250
        print("%s受到250点攻击,当前血量:%s" %(odd,self.blood))

obj1 = Swordman(opp)
obj2 = Rock(odd)
print(" %s\n     血量:%s\n     Q攻击:%s\n     W攻击:%s\n     E攻击:%s\n     R攻击:%s\n"%(opp,obj1.blood,150,120,110,250))
print(" %s\n     血量:%s\n     Q攻击:%s\n     W攻击:%s\n     E攻击:%s\n     R攻击:%s\n"%(odd,obj2.blood,100,200,150,300))
while True:
    time.sleep(0.5)
    ret=random.randrange(9)
    if ret == 1 or ret == 3 or ret == 5 or ret == 7:
        tump = random.randrange(9)
        if tump == 1 or tump == 2:
            obj1.Q()
        elif tump == 3 or tump == 4:
            obj1.W()
        elif tump == 5 or tump == 6:
            obj1.E()
        else:
            obj1.R()
    else:
        att = random.randrange(9)
        if att == 1 or att == 2:
            obj2.Q()
        elif att == 3 or att == 4:
            obj2.W()
        elif att == 5 or att == 6:
            obj2.E()
        else:
            obj2.R()
    if obj1.blood < 0:
        print("%sKO%s"%(opp,odd))
        break
    elif obj2.blood < 0:
        print("%sKO%s"%(odd,opp))
        break

 轮播图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="http://www.mamicode.com/jquery-1.9.1.min.js"></script>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            position: relative;
            width: 730px;
            height: 454px;
            border: dashed 5px gold;
            margin: 0 auto;
        }
        img{
            position: absolute;
        }
         .num{
            position: absolute;
            font-size: 0;   /*使li之间的间距为0*/
            width: 100%;    /*使文本内容居中*/
            text-align: center;
            bottom: 10px;
        }
        .num li{
            width: 20px;
            height: 20px;
            
            border-radius: 60%;
            line-height: 20px;
            text-align: center;
            list-style: none;
            display: inline-block;
            font-size: 16px;
            margin: 5px;
            cursor: pointer;
        }
        .r,.l{
            display: inline-block;
            width: 30px;
            height: 60px;
            background-color: #9f9f9f;
            font-size: 25px;
            line-height: 60px;
            text-align: center;
            position: absolute;
            top: 50%;
            right:0;
            margin-top: -30px;
            cursor: pointer;
        }
        .l{
            left: 0;
        }
        .rl{
            display: none;
        }
        .box:hover .rl{
            display: block;
        }
        .num ul li.color{
            background-color: red;
            color: white;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="tu">
            <img src="http://www.mamicode.com/1.jpg" >
            <img src="http://www.mamicode.com/2.jpg" >
            <img src="http://www.mamicode.com/3.jpg" >
            <img src="http://www.mamicode.com/4.jpg" >
            <img src="http://www.mamicode.com/5.jpg" >
        </div>
        <div class="num">
            <ul>
                <li>1</li>
                <li>2</li>
                <li>3</li>
                <li>4</li>
                <li>5</li>
            </ul>
        </div>
        <div class="rl hide" >
            <span class="l"><</span>
            <span class="r">></span>
        </div>
    </div>
    <script>
        $(".num li").first().addClass("color");
        $(".num li").mouseover(function () {
            $(this).addClass("color").siblings().removeClass("color");
            var index = $(this).index();
            i=index;/*表示鼠标放上去再离开后,能够走他后面的那个图,而不是跟定时器的节奏走*/
            $("img").eq(index).fadeIn(1000).siblings().fadeOut(1000);
        });
        var time = setInterval(move,2000);
        i = 0;
        function move() {
            i++;
            if(i==5){i=0}
            $(".num li").eq(i).addClass("color").siblings().removeClass("color");
            $("img").eq(i).fadeIn(1000).siblings().fadeOut(1000);
        }
        $(".box").hover(function () {     /*hover里面的第一个函数表示鼠标放上去以后执行,后一个表示鼠标移除后执行*/
            clearInterval(time)
        },function () {
            var time = setInterval(move,2000);
                }
        );
        $(".r").click(function () {
            move()
        });
        $(".l").click(function () {
            i=i-2;
            if(i==-2){i=3}
            move()
        })
    </script>
</body>
</html>

 

现实应用实例