Python编程之路 ---- 练习2

字符串


# 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
name = " OceAn"
# 1)    移除 name 变量对应的值两边的空格,并输出处理结果

name = ' OceAn'
print(name.strip(''))
# 2)    判断 name 变量对应的值是否以 "Oc" 开头,并输出结果
name = ' OceAn'
if name.startswith('al'):
    print(name)
else:
    print('no') 

# 3)    判断 name 变量对应的值是否以 "n" 结尾,并输出结果

name = ' OceAn'
if name.endswith('X'):
    print(name)
else:
    print('no')
# 4)    将 name 变量对应的值中的 “e” 替换为 “p”,并输出结果
name = ' OceAn'
print(name.replace('e','p'))
# 5)    将 name 变量对应的值根据 “l” 分割,并输出结果。
name = ' OceAn'
print(name.split('c'))
# 6)    将 name 变量对应的值变大写,并输出结果

name = ' OceAn'
print(name.upper())
# 7)    将 name 变量对应的值变小写,并输出结果

name = ' OceAn'
print(name.lower())
# 8)    请输出 name 变量对应的值的第 2 个字符?
name = ' OceAn'
print(name[1])
# 9)    请输出 name 变量对应的值的前 3 个字符?
name = ' OceAn'
print(name[:3])
# 10)    请输出 name 变量对应的值的后 2 个字符?

name = ' OceAn'
print(name[-2:])
# 11)    请输出 name 变量对应的值中 “e” 所在索引位置?

name = ' OceAn'
print(name.index('e'))
# 12)    获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。
name = ' OceAn'
print(name[:-1])

列表

1. 有列表data=['alex',49,[1900,3,18]],分别取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量
a = ['ocean',49,[1900,3,18]]
name = a[0]
age = a[1]
birthday = a[2]
2. 用列表模拟队列

3. 用列表模拟堆栈

4. 有如下列表,请按照年龄排序(涉及到匿名函数)
l=[
    {'name':'alex','age':84},
    {'name':'oldboy','age':73},
    {'name':'egon','age':18},
]
l.sort(key=lambda item:item['age'])
print(l)

 

元组

实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入  

msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
} 
msg_dic={
        'apple':10,
        'tesla':100000,
        'mac':3000,
        'lenovo':30000,
        'chicken':10,
        }
shopping_list=[]
while True:
    for key,item in msg_dic.items():
        print('name:{name} price:{price}'.format(price=item,name=key))
    choice = input("购买商品:").strip()
    if not choice or choice not in msg_dic:
        continue
    count = input("购买数量:").strip()
    if not count.isdigit():
        continue
    shopping_list.append(choice,msg_dic[choice],count)
print(shopping_list)

字典

1 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中

即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
#菜鸟写法
lst = [11,22,33,44,55,66,77,88,99,90]
dict = {'k1':[],'k2':[]}
i = 0
for lst[i] in lst:
    if lst[i] < 66:
        dict['k1'].append(lst[i])
    else:
        dict['k2'].append(lst[i])
    i+=1
print(dict)
2 统计s='hello alex alex say hello sb sb'中每个单词的个数

结果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
#coding=utf-8
from collections import Counter
s='hello alex alex say hello sb sb'
lst = s.split(' ')
res = Counter(lst)
print(res)
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
print(words)
for word in words: #word='alex'
    dic[word]=s.count(word)
    print(dic)


#利用setdefault解决重复赋值
'''
setdefault的功能
1:key存在,则不赋值,key不存在则设置默认值
2:key存在,返回的是key对应的已有的值,key不存在,返回的则是要设置的默认值
d={}
print(d.setdefault('a',1)) #返回1

d={'a':2222}
print(d.setdefault('a',1)) #返回2222
'''
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
for word in words: #word='alex'
    dic.setdefault(word,s.count(word))
    print(dic)



#利用集合,去掉重复,减少循环次数
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
words_set=set(words)
for word in words_set:
    dic[word]=s.count(word)
    print(dic)

 集合

一.关系运算
  有如下两个集合,pythons是报名python课程的学员名字集合,linuxs是报名linux课程的学员名字集合
  pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
  linuxs={'wupeiqi','oldboy','gangdan'}
  1. 求出即报名python又报名linux课程的学员名字集合
  2. 求出所有报名的学生名字集合
  3. 求出只报名python课程的学员名字
  4. 求出没有同时这两门课程的学员名字集合
#coding=utf-8
pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
linuxs={'wupeiqi','oldboy','gangdan'}
second = pythons|linuxs
first = pythons&linuxs
forth = pythons^linuxs
third = pythons-linuxs
print(first)
print(second)
print(third)
print(forth)
 
二.去重

   1. 有列表l=['a','b',1,'a','a'],列表元素均为可hash类型,去重,得到新列表,且新列表无需保持列表原来的顺序

   2.在上题的基础上,保存列表原来的顺序

   3.去除文件中重复的行,肯定要保持文件内容的顺序不变
   4.有如下列表,列表元素为不可hash类型,去重,得到新列表,且新列表一定要保持列表原来的顺序

l=[
    {'name':'egon','age':18,'sex':'male'},
    {'name':'alex','age':73,'sex':'male'},
    {'name':'egon','age':20,'sex':'female'},
    {'name':'egon','age':18,'sex':'male'},
    {'name':'egon','age':18,'sex':'male'},
]  
#有列表l=['a','b',1,'a','a'],列表元素均为可hash类型,去重,得到新列表,且新列表无需保持列表原来的顺序
l=['a','b',1,'a','a']
new_l = set(l)
print(new_l)

#有列表l=['a','b',1,'a','a'],列表元素均为可hash类型,去重,得到新列表,且新列表需保持列表原来的顺序
l=['a','b',1,'a','a']
new_l = list(set(l))
new_l.sort(key=l.index)
print(new_l)

#有如下列表,列表元素为不可hash类型,去重,得到新列表,且新列表一定要保持列表原来的顺序
l=[
    {'name':'egon','age':18,'sex':'male'},
    {'name':'alex','age':73,'sex':'male'},
    {'name':'egon','age':20,'sex':'female'},
    {'name':'egon','age':18,'sex':'male'},
    {'name':'egon','age':18,'sex':'male'},
]
# print(set(l)) #报错:unhashable type: 'dict'
s=set()
l1=[]
for item in l:
    val=(item['name'],item['age'],item['sex'])
    if val not in s:
        s.add(val)
        l1.append(item)

print(l1)

数据类型总结

 按存储空间的占用分(从低到高)

数字
字符串
集合:无序,即无序存索引相关信息
元组:有序,需要存索引相关信息,不可变
列表:有序,需要存索引相关信息,可变,需要处理数据的增删改
字典:无序,需要存key与value映射的相关信息,可变,需要处理数据的增删改

按存值个数区分

标量/原子类型数字,字符串
容器类型列表,元组,字典

 

 

 

按可变不可变区分

可变列表,字典
不可变数字,字符串,元组

 

 

 

按访问顺序区分

直接访问数字
顺序访问(序列类型)字符串,列表,元组
key值访问(映射类型)字典

 

 

 

 

用户名和密码存放于文件中,格式为:egon|egon123
启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额

 

import os

product_list = [['Iphone7',5800],
                ['Coffee',30],
                ['疙瘩汤',10],
                ['Python Book',99],
                ['Bike',199],
                ['ViVo X9',2499],

                ]

shopping_cart={}
current_userinfo=[]

db_file=r'db.txt'

while True:
    print('''
登陆
注册
购物
    ''')

    choice=input('>>: ').strip()

    if choice == '1':
        #1、登陆
        tag=True
        count=0
        while tag:
            if count == 3:
                print('\033[45m尝试次数过多,退出。。。\033[0m')
                break
            uname = input('用户名:').strip()
            pwd = input('密码:').strip()

            with open(db_file,'r',encoding='utf-8') as f:
                for line in f:
                    line=line.strip('\n')
                    user_info=line.split(',')

                    uname_of_db=user_info[0]
                    pwd_of_db=user_info[1]
                    balance_of_db=int(user_info[2])

                    if uname == uname_of_db and pwd == pwd_of_db:
                        print('\033[48m登陆成功\033[0m')

                        # 登陆成功则将用户名和余额添加到列表
                        current_userinfo=[uname_of_db,balance_of_db]
                        print('用户信息为:',current_userinfo)
                        tag=False
                        break
                else:
                    print('\033[47m用户名或密码错误\033[0m')
                    count+=1

    elif choice == '2':
        uname=input('请输入用户名:').strip()
        while True:
            pwd1=input('请输入密码:').strip()
            pwd2=input('再次确认密码:').strip()
            if pwd2 == pwd1:
                break
            else:
                print('\033[39m两次输入密码不一致,请重新输入!!!\033[0m')

        balance=input('请输入充值金额:').strip()

        with open(db_file,'a',encoding='utf-8') as f:
            f.write('%s,%s,%s\n' %(uname,pwd1,balance))

    elif choice == '3':
        if len(current_userinfo) == 0:
            print('\033[49m请先登陆...\033[0m')
        else:
            #登陆成功后,开始购物
            uname_of_db=current_userinfo[0]
            balance_of_db=current_userinfo[1]

            print('尊敬的用户[%s] 您的余额为[%s],祝您购物愉快' %(
                uname_of_db,
                balance_of_db
            ))

            tag=True
            while tag:
                for index,product in enumerate(product_list):
                    print(index,product)
                choice=input('输入商品编号购物,输入q退出>>: ').strip()
                if choice.isdigit():
                    choice=int(choice)
                    if choice < 0 or choice >= len(product_list):continue

                    pname=product_list[choice][0]
                    pprice=product_list[choice][1]
                    if balance_of_db > pprice:
                        if pname in shopping_cart: # 原来已经购买过
                            shopping_cart[pname]['count']+=1
                        else:
                            shopping_cart[pname]={'pprice':pprice,'count':1}

                        balance_of_db-=pprice # 扣钱
                        current_userinfo[1]=balance_of_db # 更新用户余额
                        print("Added product " + pname + " into shopping cart,\033[42;1myour current\033[0m balance " + str(balance_of_db))

                    else:
                        print("买不起,穷逼! 产品价格是{price},你还差{lack_price}".format(
                            price=pprice,
                            lack_price=(pprice - balance_of_db)
                        ))
                    print(shopping_cart)
                elif choice == 'q':
                    print("""
                    ---------------------------------已购买商品列表---------------------------------
                    id          商品                   数量             单价               总价
                    """)

                    total_cost=0
                    for i,key in enumerate(shopping_cart):
                        print('%22s%18s%18s%18s%18s' %(
                            i,
                            key,
                            shopping_cart[key]['count'],
                            shopping_cart[key]['pprice'],
                            shopping_cart[key]['pprice'] * shopping_cart[key]['count']
                        ))
                        total_cost+=shopping_cart[key]['pprice'] * shopping_cart[key]['count']

                    print("""
                    您的总花费为: %s
                    您的余额为: %s
                    ---------------------------------end---------------------------------
                    """ %(total_cost,balance_of_db))

                    while tag:
                        inp=input('确认购买(yes/no?)>>: ').strip()
                        if inp not in ['Y','N','y','n','yes','no']:continue
                        if inp in ['Y','y','yes']:
                            # 将余额写入文件

                            src_file=db_file
                            dst_file=r'%s.swap' %db_file
                            with open(src_file,'r',encoding='utf-8') as read_f,\
                                open(dst_file,'w',encoding='utf-8') as write_f:
                                for line in read_f:
                                    if line.startswith(uname_of_db):
                                        l=line.strip('\n').split(',')
                                        l[-1]=str(balance_of_db)
                                        line=','.join(l)+'\n'

                                    write_f.write(line)
                            os.remove(src_file)
                            os.rename(dst_file,src_file)

                            print('购买成功,请耐心等待发货')

                        shopping_cart={}
                        current_userinfo=[]
                        tag=False


                else:
                    print('输入非法')


    else:
        print('\033[33m非法操作\033[0m')

购物车程序面条版

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值