Python学习笔记(六)

一个简单的购物车代码

li = [
    {'name':'1h1g','price':10},
    {'name':'1h2g','price':20},
    {'name':'2h4g','price':30}
]
for i in li:
    print('No.{}\t商品:{}\t价格:{}'.format(li.index(i)+1,i['name'],i['price']))
shopping_car = {}
while 1:
    money = input('请输入你的钱:')
    if money.isdigit() and int(money) > 0:
        money = int(money)
    else:
        print("输入错误!")
        continue
    while 1:
        selection = input('请输入你要买的商品序号:')
        if selection.isdigit() and int(selection) < len(li) + 1 and int(selection) > 0:
            num = input('请输入你要购买的个数:')
            if num.isdigit() and int(num) > 0:
                if money - li[int(selection) - 1]['price'] * int(num) >= 0:
                    money = money - li[int(selection) - 1]['price'] * int(num)
                    print('你已在购物车里添加{}件{}号商品'.format(num,selection))
                    shopping_car.setdefault(li[int(selection) - 1]['name'])
                    if shopping_car[li[int(selection) - 1]['name']] == None:
                        shopping_car[li[int(selection) - 1]['name']] = 0
                    shopping_car[li[int(selection) - 1]['name']] = shopping_car[li[int(selection) - 1]['name']] +int(num)
                    print('购物车已有{},您的余额还剩{}'.format(shopping_car,money))
                else:
                    print("回家找你老婆要钱去!")
                    break
            else:
                print("输入数字啊!")
        elif selection.upper() == 'Q':
            print("退出成功")
            break
        else:
            print("请输入正确的数据类型")
    print('购物车已有{}'.format(shopping_car))
    break

编码转换

s = 'China中国'
s1 = s.encode('utf-8')
s2 = s.encode('gbk')
print(s,s1,s2)
# China中国 b'China\xe4\xb8\xad\xe5\x9b\xbd' b'China\xd6\xd0\xb9\xfa'

发表评论

您的电子邮箱地址不会被公开。