开发基础(练习题)

一、基础语法练习题

 

#1
li = ['jiu','lin','liang']
print ("{0}{1}{2}{3}{4}".format(li[0],'_',li[1],'_',li[2]))
#2
li = ["alec", " aric", "Alex", "Tony", "rain"]
for l in li :
    if  l.strip().startswith("a") == True or l.strip().startswith("A") and   l.strip().endswith("c"):
        print(l.strip())

tu = ("alec", " aric", "Alex", "Tony", "rain")
for l in tu :
    if  l.strip().startswith("a") == True or l.strip().startswith("A") and   l.strip().endswith("c"):
        print(l.strip())

dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"}
for l in dic.values() :
    if  l.strip().startswith("a") == True or l.strip().startswith("A") and   l.strip().endswith("c"):
        print(l.strip())

#3

#3
li = ['alex','eric','rain']
print(len(li))
li.append("seven")
print(li)
li.insert(0,"Tony")
print(li)
li[1] = "Kelly"
print(li)
li.pop(li.index("eric"))
print(li)
li_2 = li[1]
li.pop(1)
print(li_2,li)
print(li)
li.pop(3)
print(li[3:])
li.pop(2,4)
print(li)
print(li[::-1])for k in range(len(li)):
    print(k)
for k,y in enumerate(li):
    print(k+100,y)

#4
li = ["hello", 'seven', ["mon", ["h", "kelly"], 'all'], 123, 446]
print(li[2][1][1])
li[2][2] = 'ALL'
print(li)

#5

#5
tu = ('alex', 'eric', 'rain')
print(len(tu))
print(tu[2])
print(tu[1],tu[2])
for i in tu:
    print(i)
for i in range(len(tu)):
    print(i)
for k,y in enumerate(tu):
    print(k+10,y)

#6
tu = ("alex", [11, 22, {"k1": 'v1', "k2": ["age", "name"], "k3": (11,22,33)}, 44])
#1,只读列表,2,不能修改
#不可以
#k2是 字典,对应的值是列表可以被修改
tu[1][2]["k2"].append("Seven") 
print(tu)
#k3对应的值是元祖不能修改

#7
dic = {'k1': "v1", "k2": "v2", "k3": [11,22,33]}
for k in dic.keys():
    print(k)
for v in dic.values():
    print(v)
for k,y in dic.items():
    print(k,y)
dic["k4"] = "v4"
print(dic)
dic['k1'] = 'alex'
print(dic)
dic['k3'].append(44)
print(dic)
dic["k3"].insert[0,18]print(dic)
#8
s = 'alex'
print(s.split())
print(tuple(s))
li = ['alex','seven']
print(tuple(li))
tu = ('alex','seven')
print(list(tu))
li = ['alex','seven']
dic = {}
for k,y in enumerate(li):
    dic.setdefault((10-k),y )
    print(dic)

#9
s = [11,22,33,44,55,66,77,88,99,90]
len(s)
k1 = []
k2 = []
dic = {'k1':None,'k2':None}
for k in range(len(s)):
    print(s[k])
    if s[k] > 66 :
        k1.append(s[k])
    elif s[k] <66 :
        k2.append(s[k])
dic['k1'] = k1
dic['k2'] = k2
print(dic)

#10
li = ["手机", "电脑", '鼠标垫', '游艇']
shoplist = []
for k,y in enumerate(li):
    print(k,y)
user = int(input("输入序号---"))
print(li[user])
user_1 = (input("添加的商品----"))
(li.append(user_1))
print(li)
#11
city = {"北京":{"朝阳":["大望路","国贸"],
               "昌平":["沙河","昌平"]},
        "河北":{"张家口":["沙城","宣化"],
                "石家庄":["某某路","某某街"]}
        }
go = True
while go:
    cc = []
    dq = []
    print("\33[31;1m一级列表\33[1m".center(40,"="))
    for i,v in enumerate(city,1):
        print(i,v)
        cc.append(v)
    print("\33[35;1m插入数据 i 退出按Q\33[1m")
    u_c1 = str(input(">>>"))
    if u_c1.isdigit():#进二级之前判断
        u_c1 = int(u_c1)
        if u_c1 >0 and u_c1 <=len(cc):
            while go:
                print("\33[32;1m二级列表\33[1m".center(40, "="))
                for i1,v1 in enumerate(city[cc[u_c1-1]],1):
                    print(i1,v1)
                    dq.append(v1)
                print("\33[35;1m退出按Q 返回 B\33[1m")
                u_c2 = input(">>>")
                if u_c2.isdigit():#进三级之前判断
                    u_c2 = int(u_c2)
                    if u_c2 >0 and u_c2<=len(dq):
                        while go:
                            print("\33[32;1m三级列表\33[1m".center(40, "="))
                            for s in city[cc[u_c1-1]][dq[u_c2-1]]:
                                print(s)
                            print("\33[35;1m退出按Q 返回 B\33[1m")
                            u_c3 = input(">>>")
                            if u_c3 == "q" or u_c3 == "Q":
                                go = False
                                break
                            if u_c3 == "b" or u_c3 =="B":
                                del dq[:]
                                break
                            else:
                                print("\33[31;1m输入不正确\33[1m")
                    else:
                        print("\33[31;1m输入超出范围!\33[1m")
                elif u_c2 == "q" or u_c2 == "Q":
                    go = False
                    break
                elif u_c2 == "b" or u_c2 == "B":
                    del cc[:]
                    del dq[:]
                    break
                else:
                    print("\33[31;1m输入格式不对!\33[1m")
    elif u_c1.isalpha():
        if u_c1 == "q" or u_c1 == "Q":
            break
        elif u_c1 == "i" or u_c1 == "I":
            print("\33[32;1m添加信息\33[1m".center(40,"="))
            ct_name = input("省:")
            if ct_name == "Q" or ct_name == "q":
                break
            else:
                if city.get(ct_name,0) == 0:
                    city[ct_name] = {}
            dq_name = input("市:")
            if dq_name == "Q" or dq_name == "q":
                break
            else:
                if city[ct_name].get(dq_name,0) == 0:
                    city[ct_name][dq_name]=[]
            while True:
                print("\33[31;1m循环添加,退出请按Q!\33[1m")
                s = input("县:")
                if s == "q" or s == "Q":
                    break
                else:
                    city[ct_name][dq_name].append(s)
        else:
            print("\33[31;1m输入超出范围!\33[1m")
    else:
        print("\33[31;1m输入格式不对!\33[1m")

#12
None ""  () []  {} 0 
#13
l1 = [11,22,33]
l2 = [22,33,44]
#都有的元素
for i in l1:
    if i in l2:
        print(i)
#l2没有的
for i in l1:
    if i not in l2:
        print(i)
#l1没有的
for i in l2:
    if i not in l1:
        print(i)
#互相都没有的元素
for i in l1:
    if i not in l2 :
        print(i)
for k in l2:
    if k not in l1:
        print(k)

#14

#14
for i in range(100,0,-1):
    print(i)
for i in range(1,101):
    print(i)
count = 100
while count >1 :
    count -= 1
    print(count)
count = 0
while count <100 :
    count +=1
    print(count)
    
#15
for i in range(1,10):
    for j in range(1,i+1):
        print(str(i) + "*" + str(j) + "=" + str(i * j), end=' ')
    print()

 

 
 

二、购物车程序

需求:

  • 启动程序后,让用户输入工资,然后打印商品列表
  • 允许用户根据商品编码购买商品
  • 用户选择商品后检测余额是否够,够就直接扣款,不够就提醒
  • 用户可以一直购买商品,也可以随时退出,退出时,打印已购买的商品和余额
shoplist = []
commodity = [['iphonex',8888],['Book',99],['Macpro',7666],['小米6',3200]]
long = len(commodity)
wages = input("请输入你的工资--->")
if wages.isdigit() ==True:
    wages = int(wages)
    print('你的工资是',wages,'')
    while True:
        print('--------商品列表-------')
        for y, p in enumerate(commodity):
            print("{0}  {1} \t{2}".format(y, p[0], p[1], ''))
        need = input("请输入你需要购买的商品编号---->")
        if need == 'q' or need == 'Q':
            print('退出不买了')
            print("-----你的购物车-----")
            for y, p in enumerate(shoplist):
                print(y, p[0], p[1])
            # wages = wages - commodity[need][1]
            print("你剩余", wages, "")
            break
        elif need.isdigit() == True:
            need = int(need)
            if wages >= commodity[need][1]:
                need = int(need)
            elif wages < commodity[need][1]:
                print("骚年去赚钱吧,你还剩", wages, "元了,还想买", commodity[need][0])
                continue
            if need >= 0 and need <= long:
                print('你购买了', commodity[need])
                shoplist.append(commodity[need])
                print("-----你的购物车-----")
                for y, p in enumerate(shoplist):
                    print(y, p[0], p[1])
                wages = wages - commodity[need][1]
                print("你剩余", wages, "")
        else:
            print("你输入的什么玩意,请输入数字")
            continue
else:
    print("你输入的什么玩意,让你输入数字")

三、多级菜单

需求:

  • 现有省市县三级结构,要求程序启动后,允许用户可依次选择进入各级子菜单,
  • 可在任意一级菜单返回上一级
  • 可以在任意一级菜单退出程序
menu = {
    '河北':{
        '承德':{
            '双桥区':'贾营村'
        }
    },
    '北京':{
        '通州区':{
            '东潞苑小区','我家'
        }
    }
}
while True:
    print(menu.keys())
    choice = input("请输入你要查看的省份---")
    if menu.get(choice) != None:
        sub = menu[choice]
        #print(sub.keys())
        while True:
            print(sub.keys())
            choice_sub = input("请输入你要查看的市,或者返回上一级请输入R")
            if choice_sub == 'r' or choice_sub == 'R':
                break
            elif choice_sub == 'q' or choice == 'Q':
                print("程序退出")
                exit()
            elif sub.get(choice_sub) != None:
                print(sub[choice_sub])
                sub_sub = input("是否返回上一层,R=返回,e=退出")
                if sub_sub == 'r' or sub_sub == 'R':
                    print('返回上一层')
                else:
                    print('退出')
                    exit()
    elif choice == 'q' or choice == 'Q':
        print("程序退出")
        exit()



 #三级菜单高效写法

level = menu
L = []
while True:
    for k in level:
        print(k)
    user = input(">").strip()
    if  not  level:continue
    if user in  level:
        L.append(level)
        level = level[user]
    elif user == 'b':
        if len(L) != 0:
            level = L.pop()
        else:
            print('到头了')

 

posted @ 2018-03-13 22:48  SmallNine  阅读(410)  评论(0编辑  收藏  举报