码迷,mamicode.com
首页 > 编程语言 > 详细

Python 练习题_简易购物车

时间:2017-12-30 16:00:27      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:option   练习   style   tar   ice   post   invalid   退出   --   

命题:

  1. 启动程序后,让用户输入工资,然后打印商品列表
  2. 允许用户根据商品编号购买商品
  3. 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 
  4. 可随时退出,退出时,打印已购买商品和余额

伪代码

shopping_car = []
balance = input usrs balance
(check parameters legality)

while TRUE {
    show commodity list
    choice = user input
    if choice.isdigit {
        if choice > number of commodity{
            print("invalid input")
            continue
        }
        item = commodity[choice]
        if item.price < balance {
            shopping_car.append(item)
            balance -= item.price
            print("item add success, balance:%d")
        }
        else{
            print("balance is not enough!")
        }
    }
    else{
        if choice == q{
            print("your shopping things & balance")
            break
        }else {
            print("invalid input")
        }
    }
}

 

源码:

#! /usr/local/bin/python3.5

import sys

commodity = [
    ("iphone", 5888),
    ("MacBook", 12888),
    ("StarBark", 60),
    ("Bike", 1000)
]

shopping_car = []

while True:
    balance = input("input your balance:")
    if balance.isdigit():                            #检查是不是整形
        balance = int(balance)                        #类型转换整形
        break
    else:
        if balance == q:
            sys.exit(0)
        else:
            print("----->Invalied input!!!")


while True:
    for index, cl in enumerate(commodity):    #对于list,该函数将其转换为索引序列
        print("\n", index, cl)
    uc = input("Input your choice:")    #输入选择
    if uc.isdigit():
        uc = int(uc)
        if uc < len(commodity) and uc >=0:
            item = commodity[uc]
            if item[1] <= balance:
                shopping_car.append(item)
                balance -= item[1]
                print("%s add shopping car sucess!"%item[0])
            else:
                print("your balance is not enough!")
        else:
            print("------->Invalid input!")
    elif uc == q:
        print("----------shopping list-----------")
        for c in shopping_car:
            print(c)
        print("your balance:%d"%balance)
        break;
    else:
        print("------->Invalid option")

 

Python 练习题_简易购物车

标签:option   练习   style   tar   ice   post   invalid   退出   --   

原文地址:https://www.cnblogs.com/yangdadahome/p/8149896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!