Python基础二

一、引子

1.1 什么是数据?

  x=8,8是我们要存储的数据

1.2 为何数据要分不同的类型

  数据是用来表示状态的,不同的状态就应该用不同的类型的数据去表示

1.3 数据类型

  数字:整形,长整形,浮点型,复数

  字符串 (在介绍字符编码时介绍字节bytes类型)

  列表

  元组

  字典

  集合

1.4 可根据以下几个方面展开我们数据类型的学习

#######基本使用#######
1 用途

2 定义方式

3 常用操作+内置的方法

#######该类型总结######
1 存一个值or存多个值
    只能存一个值
    可以存多个值,值都可以是什么类型

2 有序or无序

3 可变or不可变

    !!!可变:值变,id不变。可变==不可hash
    !!!不可变:值变,id就变。不可变==可hash

二、数字

2.1 整型与浮点型

#整型int
比如,年纪,身份id,qq号等整型数字相关
定义:
    age=18 #本质age=int(18)

#浮点型float
比如,我们的身高、体重,发的工资、奖金等都与浮点数相关
定义:
    salary=25000.8 #本质salary=float(25000.8)

#我们熟悉的二进制,十进制,八进制,十六进制 

2.2 注意一些区别,了解即可

#长整形(了解)
    在python2中(python3中没有长整形的概念):      
    >>> num=2L
    >>> type(num)
    <type 'long'>

#复数(了解)  
    >>> x=1-2j
    >>> x.real
    1.0
    >>> x.imag
    -2.0 

三、字符串

3.1 字符串需要掌握的基本操作:

按索引取值(正向取+反向取) :只能取

切片(顾头不顾腚再加步长)

字符串的长度len

成员运算in和not in

移除空白字符strip

切分split

循环

s = 'python自动化运维21期'
# s[起始索引:结束索引+1:步长]
print(s[:6])
python

print(s[6:9])
自动化

print(str[:5:2])
pto

print(str[:])
python自动化运维21期

print(s[-1:-5:-1] )#倒着取值,必须加反向步长
期12维

#公共方法:len count
s = 'fdsafsdagsdafjdskahdhjlsadhfkj'
print(len(s))
30

s = 'fdsadd'
print(s.count('d'))
5

# name = 'jinxin123'
# print(name.isalnum()) #字符串由字母或数字组成
# print(name.isalpha()) #字符串只由字母组成
# print(name.isdigit()) #字符串只由数字组成
View Code

3.2 需要掌握的操作及示例:

#1、strip,lstrip,rstrip
#2、lower,upper
#3、startswith,endswith
#4、format的三种玩法
#5、split,rsplit
#6、join
#7、replace
#8、isdigit
#1、strip,lstrip,rstrip

>>> name='*alex***'
>>> name.strip('*')
'alex'
>>> name.lstrip('*')
'alex***'
>>> name.rstrip('*')
'*alex'

#2、lower,upper
>>> name='alex'
>>> name.upper()
'ALEX'
>>> name='Alex'
>>> name.lower()
'alex'

#3、startswith,endswith
>>> name='alex_SB'
>>> name.startswith('a')
True
>>> name.endswith('SB')
True

#4、format的三种玩法
>>> '{} {} {}'.format('egon',18,'male')
'egon 18 male'
>>> '{1} {0} {1}'.format('egon',18,'male')
'18 egon 18'
>>> '{name} {age} {sex}'.format(sex='male',name='egon',age=18)
'egon 18 male'

#5、split,rsplit
>>> name='root:x:0:0::/root:/bin/bash'
>>> name.split(':')#默认分隔符为空格
['root', 'x', '0', '0', '', '/root', '/bin/bash']

>>> name='C:/a/b/c/d.txt'#只想拿到顶级目录
>>> name.split('/',1)
['C:', 'a/b/c/d.txt']

>>> name='a|b|c'
>>> name.rsplit('|')#从右开始切分
['a', 'b', 'c']

#6、join
tag=' '
print(tag.join(['egon','say','hello','world']))#可迭代对象必须都是字符串
>>>egon say hello world

#7、replace
name='alex say :i have one tesla,my name is alex'
print(name.replace('alex','SB',1))
>>>SB say :i have one tesla,my name is alex

#8、isdigit可以判断bytes和unicode类型,是最常用的用于于判断字符是否为"数字"的方法
age=input('>>: ')
print(age.isdigit())
>>: 22
True
View Code

3.2 了解即可的操作及示例:

#1、find,rfind,index,rindex,count
#2、center,ljust,rjust,zfill
#3、expandtabs
#4、captalize,swapcase,title
#5、is数字系列
#6、is其他
#find,rfind,index,rindex,count
>>> name='egon say hello'
>>> name.find('o',1,3) #顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引
2

>>> name.index('e',1,3) #同上,但是找不到会报错
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    name.index('e',1,3)
ValueError: substring not found
>>> name.index('e',0,3)
0 
>>> name.count('e',1,3)#顾头不顾尾,如果不指定范围则查找所有
0

#center,ljust,rjust,zfill
>>> name='alex'
>>> name.center(30,'*')
'*************alex*************'
>>> name.ljust(30,'*')
'alex**************************'
>>> name.rjust(30,'*')
'**************************alex'
>>> name.zfill(50)#用0填充
'0000000000000000000000000000000000000000000000alex'

#expandtabs
>>> name='egon\thello'
>>> name
'egon\thello'
>>> name.expandtabs(1)
'egon hello'

#captalize,swapcase,title
>>> name=alex
>>> name.capitalize() #首字母大写
Alex
>>> name.swapcase() #大小写翻转
ALEX
>>> msg='egon say hi'
>>> msg.title() #每个单词的首字母大写
'Egon Say Hi'

#is数字系列
#在python3中
num1=b'4' #bytes
num2=u'4' #unicode,python3中无需加u就是unicode
num3='' #中文数字
num4='' #罗马数字

#isdigt:bytes,unicode
print(num1.isdigit()) #True
print(num2.isdigit()) #True
print(num3.isdigit()) #False
print(num4.isdigit()) #False

#isdecimal:uncicode
#bytes类型无isdecimal方法
print(num2.isdecimal()) #True
print(num3.isdecimal()) #False
print(num4.isdecimal()) #False

#isnumberic:unicode,中文数字,罗马数字
#bytes类型无isnumberic方法
print(num2.isnumeric()) #True
print(num3.isnumeric()) #True
print(num4.isnumeric()) #True

#三者不能判断浮点数
num5='4.3'
print(num5.isdigit())
print(num5.isdecimal())
print(num5.isnumeric())
'''
总结:
    最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景
    如果要判断中文数字或罗马数字,则需要用到isnumeric
'''

#is其他
print('===>')
name='egon123'
print(name.isalnum()) #字符串由字母或数字组成
print(name.isalpha()) #字符串只由字母组成

print(name.isidentifier())
print(name.islower())
print(name.isupper())
print(name.isspace())
print(name.istitle())
View Code

四、布尔型

主要涉及数据类型的转换

int ---> str ,str(int)
str ---> int ,int(str) str必须全部是数字组成。

int --- > bool ,0 False 非零 True
bool ---> int ,int(True) 1 int(False) 0

str ---> bool ,' ' False 非空字符串 True

五、列表

列表是python中的基础数据类型之一,其他语言中也有类似于列表的数据类型,比如js中叫数组,他是以[]括起来,每个元素以逗号隔开,而且他里面可以存放各种数据类型比如:

my_girl_friends=['alex','wupeiqi','yuanhao',4,5] #本质

有了前面字符串的操作,相信列表操作也类似,但是相比于字符串的,列表不仅可以储存不同的数据类型,而且可以储存大量数据,32位python的限制是 536870912 个元素,64位python的限制是 1152921504606846975 个元素。而且列表是有序的,有索引值,可切片,方便取值。

5.1 列表的主要操作:

#1、按索引存取值(正向存取+反向存取):即可存也可以取      
#2、切片(顾头不顾尾,步长)
#3、长度
#4、成员运算in和not in

#5、追加
#6、删除
#7、循环

5.2 增

>>> li = [1,'a','b',2,3,'a']
>>> li.insert(0,55)#指定索引位置插入
>>> li
[55, 1, 'a', 'b', 2, 3, 'a']
>>> li.append('aaa')#最后增加
>>> li
[55, 1, 'a', 'b', 2, 3, 'a', 'aaa']
>>> li.append([1,2,3])
>>> li
[55, 1, 'a', 'b', 2, 3, 'a', 'aaa', [1, 2, 3]]
>>> li.extend(['q,a,w'])#迭代着添加
>>> li
[55, 1, 'a', 'b', 2, 3, 'a', 'aaa', [1, 2, 3], 'q,a,w']
>>> li.extend(['q,a,w','aaa'])
>>> li
[55, 1, 'a', 'b', 2, 3, 'a', 'aaa', [1, 2, 3], 'q,a,w', 'q,a,w', 'aaa']
View Code

5,3 删

>>> li
[55, 1, 'a', 'b', 2, 3, 'a', 'aaa', [1, 2, 3], 'q,a,w', 'q,a,w', 'aaa']
>>> li.pop(1)#按照位置删除有返回值
1
>>> li
[55, 'a', 'b', 2, 3, 'a', 'aaa', [1, 2, 3], 'q,a,w', 'q,a,w', 'aaa']

>>> li.remove('a')#按照元素去删除
>>> li
[55, 'b', 2, 3, 'a', 'aaa', [1, 2, 3], 'q,a,w', 'q,a,w', 'aaa']

>>> del li[1:3]#按照位置去删除,也可切片删除
>>> li
[55, 3, 'a', 'aaa', [1, 2, 3], 'q,a,w', 'q,a,w', 'aaa']

>>> li.clear()#清空
>>> li
[]
View Code

补充:del 内存级别删除列表

>>> a
[5, 4, 3, 2, 1]
>>> del a
>>> a
Traceback (most recent call last):
  File "<pyshell#80>", line 1, in <module>
    a
NameError: name 'a' is not defined

5.4 改

>>> li = [1,'a','b',2,3,'a']
>>> li[1]='b'
>>> li
[1, 'b', 'b', 2, 3, 'a']

>>> li[1:3]=['a','b']
>>> li
[1, 'a', 'b', 2, 3, 'a']
View Code

5.5 查

切片去查,或者循环去查。

5.6 其他操作

>>> a = ["q","w","q","r","t","y"]
>>> a.count('q')#count统计一个元素出现的次数
2
>>> a.index('q')#查找元素的索引
0

>>> a = [2,1,3,4,5]
>>> a.sort()#原有基础上排序,没有返回值
>>> a
[1, 2, 3, 4, 5]
>>> a.reverse()#原有基础上翻转也没有返回值
>>> a
[5, 4, 3, 2, 1]
View Code

列表经典例题:

l1 = ['alex', 'wusir', 'taibai', 'barry', '老男孩']

使用尽可能多的方法删除索引为奇数为的列表数据!
l1 = ['alex', 'wusir', 'taibai', 'barry', '老男孩']
#第一种方法
del l1[1::2]
print(l1)
#第二种方法
for i in range(len(l1)-1,0,-1):
    if i%2==1:
        l1.remove(l1[i])
print(l1)
#注意:再循环一个列表时,不要对列表进行删除的动作(改变列表元素的个数动作),会出错
View Code

六、字典

字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据。python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可哈希的。可哈希表示key必须是不可变类型,如:数字、字符串、元祖。

字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

6.1 字典的主要操作:

#1、按key存取值:可存可取
#2、长度len
#3、成员运算in和not in

#4、删除
#5、键keys(),值values(),键值对items()
#6、循环

6.2 增

>>> dic={'k1':'v1','k2':3}
>>> dic
{'k2': 3, 'k1': 'v1'}
>>> dic['li'] = ["a","b","c"]
>>> dic
{'li': ['a', 'b', 'c'], 'k2': 3, 'k1': 'v1'}
>>> dic.setdefault('k','v')#在字典中添加键值对,如果只有键那对应的值是none,但是如果原字典中存在设置的键值对,则他不会更改或者覆盖。
'v'
>>> dic
{'li': ['a', 'b', 'c'], 'k': 'v', 'k2': 3, 'k1': 'v1'}
>>> dic.setdefault('k','v1')
'v'
>>> dic
{'li': ['a', 'b', 'c'], 'k': 'v', 'k2': 3, 'k1': 'v1'}
View Code

6.3 删

>>> dic
{'li': ['a', 'b', 'c'], 'k': 'v', 'k2': 3, 'k1': 'v1'}
>>> dic.pop('a','无key,返回默认值')## pop根据key删除键值对,并返回对应的值,如果没有key则返回默认返回值
'无key,返回默认值'
>>> dic.pop('k1')
'v1'
>>> dic
{'li': ['a', 'b', 'c'], 'k': 'v', 'k2': 3}

>>> dic.popitem()#随机删除字典中的某个键值对,将删除的键值对以元祖的形式返回
('li', ['a', 'b', 'c'])
>>> dic
{'k': 'v', 'k2': 3}

>>> dic.clear()#清空字典
>>> dic
{}
View Code

6.4 改

>>> dic ={'name': 'jin', 'weight': '100', 'age': 18, 'sex': 'male'}
>>> dic['weight']='75'
>>> dic
{'name': 'jin', 'weight': '75', 'age': 18, 'sex': 'male'}

>>> dic2 = {"name":"alex","weight":100}
>>> dic2.update(dic)  # 将dic所有的键值对覆盖添加(相同的覆盖,没有的添加)到dic2中
>>> dic2
{'name': 'jin', 'weight': '75', 'age': 18, 'sex': 'male'}
View Code

6.5 查

>>> dic
{'name': 'jin', 'weight': '75', 'age': 18, 'sex': 'male'}
>>> dic['hobby'] # 没有会报错
Traceback (most recent call last):
  File "<pyshell#124>", line 1, in <module>
    dic['hobby']
KeyError: 'hobby'
>>> dic['name']
'jin'
>>> dic.get('name')# dic.get("hobby","默认返回值")没有可以返回设定的返回值
'jin'
>>> dic.get('hobby',"默认返回值")
'默认返回值'
View Code

6.6 其他常规操作

>>> dic
{'name': 'jin', 'weight': '75', 'age': 18, 'sex': 'male'}
>>> dic.items()#以元祖的形式返回键值对,这个类型就是dict_items类型,可迭代的
dict_items([('name', 'jin'), ('weight', '75'), ('age', 18), ('sex', 'male')])

>>> dic.keys()
dict_keys(['name', 'weight', 'age', 'sex'])

>>> dic.values()
dict_values(['jin', '75', 18, 'male'])
View Code

6.7 字典的循环

dic = {"name":"jin","age":18,"sex":"male"}
for key in dic:
    print(key)
for item in dic.items():
    print(item)
for key,value in dic.items():
    print(key,value)
View Code

字典经典例题(坑点):

#删除字典中含有‘k’的key-value
dic = {'k1':'v1','k2':'v2','k3':'v3','r':666}
l1 = []
for i in dic:
     if 'k' in i:
         l1.append(i)
print(l1)
for i in l1:
    del dic[i]
print(dic)
#dict 再循环字典时,不要改变字典的大小。
View Code

七、元祖

#作用:存多个值,对比列表来说,元组不可变(是可以当做字典的key的),主要是用来读

#定义:与列表类型比,只不过[]换成()
age=(11,22,33,44,55)本质age=tuple((11,22,33,44,55))

#优先掌握的操作:
#1、按索引取值(正向取+反向取):只能取   
#2、切片(顾头不顾尾,步长)
#3、长度
#4、成员运算in和not in

#5、循环

元祖补充:

 

#如果元组里面只有一个元素并且没有逗号隔开,那么他的数据类型与该元素一致。
# tu1 = (1)
# print(tu1,type(tu1))
# tu2 = ('alex')
# print(tu2,type(tu2))
#
# tu3 = (['alex',1,2])
# print(tu3,type(tu3))

 

八、集合

#作用:去重,关系运算,

#定义:
            知识点回顾
            可变类型是不可hash类型
            不可变类型是可hash类型

#定义集合:
            集合:可以包含多个元素,用逗号分割,
            集合的元素遵循三个原则:
             1:每个元素必须是不可变类型(可hash,可作为字典的key)
             2: 没有重复的元素
             3:无序

注意集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值
 

#优先掌握的操作:
#1、长度len
#2、成员运算in和not in

#3、|合集
#4、&交集
#5、-差集
#6、^对称差集
#7、==
#8、父集:>,>= 
#9、子集:<,<=

基本操作:

>>> set1 = {'alex','wusir','ritian','egon','barry'}
>>> set1.add('666') #
>>> set1
{'egon', 'wusir', '666', 'barry', 'ritian', 'alex'}
>>> set1.update('abc')#以最小粒度增加
>>> set1
{'egon', 'wusir', '666', 'barry', 'c', 'b', 'ritian', 'alex', 'a'}
>>> set1.remove('egon')#
>>> set1
{'wusir', '666', 'barry', 'c', 'b', 'ritian', 'alex', 'a'}
>>> set1.pop()#随机删除
'wusir'
>>> set1
{'666', 'barry', 'c', 'b', 'ritian', 'alex', 'a'}
>>> del set1#内存中删除

set1 = {1,2,3,4,5}
set2 = {4,5,6,7,8}
#交集 &  intersectio
# print(set1 & set2)
# print(set1.intersection(set2))

#并集 |   union
# print(set1 | set2)
# print(set1.union(set2))

#差集  -  difference
# print(set1 - set2)
# print(set1.difference(set2))

#反交集 ^ symmetric_difference
# print(set1 ^ set2)
# print(set1.symmetric_difference(set2))  # {1, 2, 3, 6, 7, 8}
# set1 = {1,2,3}
# set2 = {1,2,3,4,5,6}

# print(set1 < set2)
# print(set1.issubset(set2))  # 这两个相同,都是说明set1是set2子集。

# print(set2 > set1)
# print(set2.issuperset(set1))

# s = frozenset('barry')
# s1 = frozenset({4,5,6,7,8})
# print(s,type(s))
# print(s1,type(s1))
View Code

九、Python中有小数据池的概念

#id == is
# a = 'alex'
# b = 'alex'
# print(a == b)  # 数值
# print(a is b)  # 内存地址
# print(id(a))

int -5 ~256 的相同的数全都指向一个内存地址,节省空间。
str:s = 'a' * 20 以内都是同一个内存地址
只要字符串含有非字母元素,那就不是一个内存地址。

课后作业

一、元素分类

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

即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}

l1=[11,22,33,44,55,66,77,88,99,90]
dic={'k1':[],'k2':[]}
for i in l1:
    if i > 66:
        dic['k1'].append(i)
    elif i < 66:
        dic['k2'].append(i)
print(dic)
View Code

二、查找

查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。

    li = ["alec", " aric", "Alex", "Tony", "rain"]

    tu = ("alec", " aric", "Alex", "Tony", "rain")

    dic = {'k1': "alex", 'k2': ' aric',  "k3": "Alex", "k4": "Tony"}

li = ["alec", " aric", "Alex", "Tony", "rain"]
for i in li :
    if i.strip().startswith('a') and i.strip().endswith('c'):
        print(i.strip())

tu = ("alec", " aric", "Alex", "Tony", "rain")
for i in tu :
    if i.strip().startswith('a') and i.strip().endswith('c'):
        print(i.strip())

dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"}
for i in dic:
    if dic[i].strip().startswith('a') and dic[i].strip().endswith('c'):
        print(dic[i].strip())
View Code

三、输出商品列表,用户输入序号,显示用户选中的商品

    商品 li = ["手机", "电脑", '鼠标垫', '游艇']

li = ["手机", "电脑", '鼠标垫', '游艇']
for i in li:
    print(li.index(i) + 1, i)
while True:
    cmd=input('请输入序号:')
    if not cmd.isdigit() or int(cmd) > 4 or int(cmd) == 0:
        print('请重新输入!')
        continue
    else:
        print(li[int(cmd) - 1])
View Code

四、购物车

功能要求:

要求用户输入总资产,例如:2000

显示商品列表,让用户根据序号选择商品,加入购物车

购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。

附加:可充值、某商品移除购物车

goods = [

    {"name": "电脑", "price": 1999},

    {"name": "鼠标", "price": 10},

    {"name": "游艇", "price": 20},

    {"name": "美女", "price": 998},

]

goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},
]

shopping_car = []
shopping_car_list=[]
shopping_car_dic={}
goods_sum = 0
sum_cost = 0

flag = True
while flag:
    money = input('Please input your pay_money: ')
    if money.strip() and money.isdigit():
        break
print('========商品列表======')
for i, j in enumerate(goods, 1):
    print(i, j['name'], j['price'])
print('====================== \n请选择商品的序号,添加购物车,输入q时停止添加,开始结算')
while flag:
    list_buy = ['1','2','3','4','q']
    chose_product = input('Please enter the goods number or q:  ')
    if chose_product not in list_buy:
        print('请输入正确的商品序号或者q!')
        continue
    elif chose_product in ['1','2','3','4']:
        shopping_car_list.append(chose_product)
        print(shopping_car_list)
        continue
    elif chose_product == 'q':
        while flag:
            print('目前所选商品清单及消费信息如下:')
            if shopping_car_list.count('1') != 0:
                print('所购买%s的数量为%s,花费%s' %(goods[0]['name'],shopping_car_list.count('1'),shopping_car_list.count('1')*goods[0]['price']))
                shopping_car_dic['电脑']=shopping_car_list.count('1')
            if shopping_car_list.count('2') != 0:
                print('所购买%s的数量为%s,花费%s' %(goods[1]['name'],shopping_car_list.count('2'),shopping_car_list.count('2')*goods[1]['price']))
                shopping_car_dic['鼠标'] = shopping_car_list.count('2')
            if shopping_car_list.count('3') != 0:
                print('所购买%s的数量为%s,花费%s' %(goods[2]['name'],shopping_car_list.count('3'),shopping_car_list.count('3')*goods[2]['price']))
                shopping_car_dic['游艇'] = shopping_car_list.count('3')
            if shopping_car_list.count('4') != 0:
                print('所购买%s的数量为%s,花费%s' %(goods[3]['name'],shopping_car_list.count('4'),shopping_car_list.count('4')*goods[3]['price']))
                shopping_car_dic['美女'] = shopping_car_list.count('4')
            sum = 0
            for i in range(4):
                sum += shopping_car_list.count(str(i+1))*goods[i]['price']
            print('消费总金额为:%s'%(sum))
            if int(money) < sum:
                print('余额不足!')
                while flag:
                    cmd=input('充值请输入r,调整购物车请输入m,退出放弃购买请输入q:')
                    if cmd not in ('r','m','q'):continue
                    elif cmd == 'r':
                        while flag:
                            r_money=input('请输入充值金额: ')
                            money=int(money) + int(r_money)
                            if int(money) > sum :
                                print('消费总金额为:%s ,余额为%s'%(sum,money-sum))
                                flag = False
                            else:
                                print('充值额度不足,请继续充值!')
                                continue
                    elif cmd == 'm':
                        print('开始调整购物车')
                        print('========商品列表======')
                        for i, j in enumerate(goods, 1):
                            print(i, j['name'], j['price'])
                        print('====================== \n请选择商品的序号,调整购物车,输入q时停止调整!\n商品列表和数量如下:')
                        print(shopping_car_dic)
                        while flag:
                            cmd=input('请输入需要删除商品的序号或者q结束调整:')
                            if cmd not in ('1','2','3','4','q'):
                                continue
                            if cmd == '1':
                                quantity=input('请输入删除电脑的数量:')
                                if 0 < int(quantity) <= shopping_car_dic['电脑']:
                                    shopping_car_dic['电脑'] -= int(quantity)
                                    print(shopping_car_dic)
                                else:
                                    print('请输入大于0,小于等于%s的个数' %(shopping_car_dic['电脑']))
                            if cmd == '2':
                                quantity1=input('请输入删除鼠标的数量:')
                                if int(quantity1) <= shopping_car_dic['鼠标']:
                                    shopping_car_dic['鼠标'] -= int(quantity1)
                                    print(shopping_car_dic)
                                else:
                                    print('请输入小于%s的个数' %(shopping_car_dic['鼠标']))
                            if cmd == '3':
                                quantity2=input('请输入删除游艇的数量:')
                                if int(quantity2) <= shopping_car_dic['游艇']:
                                    shopping_car_dic['游艇'] -= int(quantity2)
                                    print(shopping_car_dic)
                                else:
                                    print('请输入小于%s的个数' %(shopping_car_dic['游艇']))
                            if cmd == '4':
                                quantity3=input('请输入删除美女的数量:')
                                if int(quantity3) <= shopping_car_dic['美女']:
                                    shopping_car_dic['美女'] -= int(quantity3)
                                    print(shopping_car_dic)
                                else:
                                    print('请输入小于%s的个数' %(shopping_car_dic['美女']))
                            if cmd == 'q':
                                for i in shopping_car_dic:
                                    if i == goods[0]['name']:
                                        sum_cost += goods[0]['price'] * shopping_car_dic[i]
                                    if i == goods[1]['name']:
                                        sum_cost += goods[1]['price'] * shopping_car_dic[i]
                                    if i == goods[2]['name']:
                                        sum_cost += goods[2]['price'] * shopping_car_dic[i]
                                    if i == goods[3]['name']:
                                        sum_cost += goods[3]['price'] * shopping_car_dic[i]
                                if int(money) > sum_cost:
                                    print('本次消费金额为:%s, 余额为:%s' % (sum_cost, int(money) - sum_cost))
                                    flag = False
                                else:
                                    continue
                    elif cmd == 'q':
                        flag = False
            else:
                print('余额为:%s:'%(int(money)-sum))
                flag =False
View Code
goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998},]
j=1
b=[]
p={}
n={}
tag=True
while True:
    qian=input('请输入您的购买金额:')
    if qian.strip() and qian.isdigit():
        money=int(qian)
        break
    continue
print('***************商品列表***************')
for i in goods:
    print(j,i['name'],i['price'])
    p[str(j)]=i['price']
    n[str(j)]=i['name']
    j+=1
print('***请选择商品的序号添加至购物车(每次一件,输入5完成选购)***')
while tag:
    buy=input('请输入您选购商品的序号:')
    if not buy in ['1','2','3','4','5']:
        print('请输入正确序号')
        continue
    elif int(buy)>=0 and int(buy)<=4:
        b.append(buy)
        continue
    elif len(b)==0:
        print('购物车为空')
        continue
    elif buy=='5':
        while tag:
            print('您的购物车清单如下:')
            if b.count('1')!=0:
                print('名称:%s  数量:%s  价格:%s'% (n['1'], b.count('1'), b.count('1')*p['1']))
            if b.count('2')!=0:
                print('名称:%s  数量:%s  价格:%s'% (n['2'], b.count('2'), b.count('2')*p['2']))
            if b.count('3') != 0:
                print('名称:%s  数量:%s  价格:%s'% (n['3'], b.count('3'), b.count('3')*p['3']))
            if b.count('4')!=0:
                print('名称:%s  数量:%s  价格:%s'% (n['4'], b.count('4'), b.count('4')*p['4']))
            s = 0
            for i in b:
                s+=p[i]
            if s>money:
                print('账户余额不足,差额为¥%s,请重新选择。' %(s-money))
                while tag:
                    print('选择充值请按c,选择删除商品请按d,退出购买请按t,重新提交请按a')
                    x=input('>>>:')
                    if not x in ['c','d','t','a']:
                        print('请重新选择功能')
                        continue
                    if x == 'c':
                        chong=input('请输入充值金额:')
                        money+=int(chong)
                        break
                    if  x == 'd' :
                        while True:
                            print('您的购物车清单如下:')
                            if b.count('1') != 0:
                                print('序号:1  名称:%s  数量:%s  价格:%s' % (n['1'], b.count('1'), b.count('1') * p['1']))
                            if b.count('2') != 0:
                                print('序号:2  名称:%s  数量:%s  价格:%s' % (n['2'], b.count('2'), b.count('1') * p['2']))
                            if b.count('3') != 0:
                                print('序号:3  名称:%s  数量:%s  价格:%s' % (n['3'], b.count('3'), b.count('3') * p['3']))
                            if b.count('4') != 0:
                                print('序号:4  名称:%s  数量:%s  价格:%s' % (n['4'], b.count('4'), b.count('4') * p['4']))
                            print('您的余额为%s' % (money - int(b.count('1') * p['1']) - int(b.count('2') * p['2']) - int(
                                b.count('3') * p['3']) - int(b.count('4') * p['4'])))
                            de=input('请输入要删除物品的序号(输入5结束):')
                            if de == '5':
                                print('删除完成')
                                break
                            elif not de in ['1','2','3','4','5'] or not de in b :
                                print('购物车中无对应的商品')
                                continue
                            elif int(de) >= 0 and int(de) <= 4 :
                                b.remove(de)
                                continue
                    if x == 'a': break
                    if x == 't':
                        tag=False
                        print('退出购买,您的余额为¥%s' %money)
            else:
                print('添加购物车成功,余额为¥%s。\n完成购买请按w,继续购买请按j' %(money-s))
                while tag:
                    k = input('请输入您的选择:')
                    if not k in ['w','j']:
                        print('请重新选择功能')
                        continue
                    if k == 'w':
                        tag=False
                        print('购物完成')
                    if k == 'j':
                        break
                break
优化答案

 

选做题:用户交互,显示省市县三级联动的选择

dic = {

    "河北": {

        "石家庄": ["鹿泉", "藁城", "元氏"],

        "邯郸": ["永年", "涉县", "磁县"],

    }

    "河南": {

        ...

    }

    "山西": {

        ...

    } 

}

dic = {
    "河北": {
        "石家庄": ["鹿泉", "藁城", "元氏"],
        "邯郸": ["永年", "涉县", "磁县"],
    },
    "河南": {
        "郑州": ["上街", "中牟", "新密"],
        "三门峡": ["渑池", "陕县", "卢氏"],
    },
    "山西": {
        "太原": ["清徐", "阳曲", "古交"],
        "大同": ["阳高", "广灵县", "浑源"],
    }
}
print('可查询省份:河北、河南、山西....')
while True:
    sheng=input('请输入你所要查询的省份:')
    if not sheng in dic:
        print('输入错误')
        continue
    break
for a in dic[sheng]:
    print(a,end=' ')
print()
while True:
    shi=input('请输入你所要查询的城市:')
    if not shi in dic[sheng]:
        print('输入错误')
        continue
    break
for b in dic[sheng][shi]:
    print(b,end=' ')

参考答案
View Code

转载于:https://www.cnblogs.com/xiao-xiong/p/8746610.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值