导航

python程序练习(1)

Posted on 2018-03-08 12:13  stumn  阅读(226)  评论(0)    收藏  举报

一.商品买卖程序:

要求:1.启动程序后,让用户输入工资,然后打印商品列表;

      2.允许用户根据商品编码购买商品

      3.用户购买商品后,检测余额是否够,够就直接扣款,不够就提醒

      4.可随时退出,退出时,打印已购买商品和余额

初始版本:

 1 goods= [['apple', 6], ['banana', 3], ['orange', 4]]
 2 shopping_cart = []
 3 
 4 salary = int(input("Salary:"))
 5 while True:
 6     for good in goods:
 7         print(goods.index(good)+1,".  ", end="")
 8         for value in good:
 9             print(value,' ', end="")
10         print()
11     i = int(input('Which one do you want to buy?'))
12     if goods[i-1][1] > salary:
13         print("You don't have enough money!")
14         break
15     else:
16         salary = salary - goods[i-1][1]
17         shopping_cart.append(goods[i-1])
18         print('You balance: ',salary)
19         print('You shopping cart has: ',shopping_cart)
View Code

以下是优化版本:

 1 goods= [['apple', 6], ['banana', 3], ['orange', 4]]
 2 shopping_cart = []
 3 
 4 salary = input("Salary:")
 5 if salary.isdigit():
 6     salary = int(salary)
 7     while True:
 8         for index, good in enumerate(goods):
 9             print(index+1, '. ', good)
10         user_choice = input('Which one do you want to buy?')
11         if user_choice.isdigit():
12             user_choice = int(user_choice) - 1
13             if user_choice < len(goods) and user_choice >= 0:
14                 p_items = goods[user_choice]
15                 if p_items[1] <= salary:
16                     shopping_cart.append(p_items)
17                     salary -= p_items[1]
18                     print("Add %s into shopping cart, your current balance is \033[31;1m%s\033[0m"%(p_items, salary))
19                 else:
20                     print("\033[41;1mYou banlance only left [%s].\033[0m"%(salary))
21             else:
22                 print("Invalid option!")
23         elif user_choice == 'q':
24             for i in shopping_cart:
25                 print(i)
26             print("\033[31;1mYou banlance only left [%s].\033[0m"%(salary))
27             exit()
28         else:
29             print("Invalid option!")
View Code

优化的地方有:

a.  5,11行增加了对输入字符是否是纯数字进行判断,在判断为是纯数字后,将其强制转为int类型;

  若是字母q,则打印购买的物品以及剩余的工资并退出,同时其余输入均判为非法字符;

b.  使用enumerate()得到每个元素的具体位置;

c.  13行判断输入的字符是否在给定范围内;

d.  在18,20行使用    \033[31;1m()\033[0m  将()中的内容显示高亮;

e.  这里使用exit(0退出程序

以下是进一步优化版本:

优化的内容:

用户入口:1.商品信息被存在文件内; 2.已购商品,余额记录;

商家入口:1.可添加商品,修改商品的价格。

  1 import time
  2 
  3 seller = ['seller', 123456]
  4 buyer = ['buyer', 112233]
  5 
  6 current = input("seller or buyer?")
  7 if current == "seller":
  8     username = input('Username: ')
  9     password = input('Password: ')
 10     if password.isdigit():
 11         password = int(password)
 12     if username == seller[0] and password == seller[1]:
 13         print("log in......")
 14         time.sleep(5)
 15         with open("f_goods", "r") as f1:
 16             goods = eval(f1.read())
 17             for index, good in enumerate(goods):
 18                 print(index + 1, '. ', good)
 19             while True:
 20                 choice = input("change or add?")
 21                 if choice == "change":
 22                     seller_choice = input("Which one do you want to change?")
 23                     if seller_choice.isdigit():
 24                         seller_choice = int(seller_choice) - 1
 25                         if seller_choice < len(goods) and seller_choice >= 0:  # 判断商家的选择是否在目前所有商品的范围内
 26                             choice = input("name or price?")
 27                             if choice == 'goods':  # 修改货物的名称
 28                                 g_item = input("Good name:")
 29                                 goods[seller_choice][0] = g_item
 30                             elif choice == 'price':  # 修改货物的价格
 31                                 p_item = input("Good price:")
 32                                 if p_item.isdigit():
 33                                     goods[seller_choice][1] = int(p_item)
 34                             elif choice == 'q':
 35                                 exit()
 36                             else:
 37                                 print("\033[46;1mInvalid option!\033[0m")
 38                     with open("f_goods", "w") as f2:  #在文件中又以可读的方式打开了f_goods
 39                         f2.write(str(goods))
 40                 elif choice == "add":
 41                     good_name = input("Goods name:")
 42                     good_price = input("Goods price:")
 43                     if good_price.isdigit():
 44                         list = [good_name, int(good_price)]
 45                         goods.append(list)
 46                     with open("f_goods", "w") as f2:
 47                         f2.write(str(goods))
 48                 elif choice == 'q':
 49                     exit()
 50                 else:
 51                     print("\033[41;1mWrong username or password!\033[0m")
 52     else:
 53         print("\033[38;1mInvalid option!\033[0m")
 54 
 55 
 56 elif current == "buyer":
 57     username = input('Username: ')
 58     password = input('Password: ')
 59     if password.isdigit():
 60         password = int(password)
 61     if username == buyer[0] and password == buyer[1]:
 62         print("log in......")
 63         time.sleep(5)
 64         with open("f_goods", "r") as f1, open("f_cart", "r") as f2:
 65             goods = eval(f1.read())
 66             cart_info = eval(f2.read())
 67             for index, good in enumerate(goods):
 68                 print(index + 1, '. ', good)
 69             banlance = cart_info["banlance"]
 70             shopping_cart = cart_info["shopping_cart"]
 71             print("Banlance:", banlance)
 72             while True:
 73                 user_choice = input('Which one do you want to buy?')
 74                 if user_choice.isdigit():
 75                     user_choice = int(user_choice) - 1
 76                     if user_choice < len(goods) and user_choice >= 0:
 77                         p_items = goods[user_choice]
 78                         if p_items[1] <= banlance:
 79                             shopping_cart.append(p_items)
 80                             banlance -= p_items[1]
 81                             print("Add %s into shopping cart, your current balance is \033[31;1m%s\033[0m" % (
 82                                 p_items, banlance))
 83                         else:
 84                             print("\033[41;1mYou banlance only left [%s].\033[0m" % (banlance))
 85                     else:
 86                         print("Invalid option!")
 87                 elif user_choice == 'q':
 88                     for i in shopping_cart:
 89                         print(i)
 90                     print("\033[31;1mYou banlance only left [%s].\033[0m" % (banlance))
 91                     cart_info["banlance"] = banlance
 92                     cart_info["shopping_cart"] = shopping_cart
 93                     with open("f_cart", "w") as f3:
 94                         f3.write(str(cart_info))
 95                     exit()
 96                 else:
 97                     print("Invalid option!")
 98 
 99 else:
100     print("Invalid option!")
101 
102 #用到的文件
103 f_goods = [['banana', 3], ['orange', 4],  ['apple', 5], ['sweets', 20]]
104 f_cart = {'shopping_cart': [], 'banlance': 100}  #初始余额为100元
View Code

这里还可以进一步优化,比如进行代码的重构,增添用户入口的清空购物车以及充值功能,以及商家入口的删除商品功能等。

 二.多级菜单程序

 1 solar_system = {'_earth': {'_sky': {'bird': 'fly'},
 2                            '_ocean': {},
 3                            '_mountain': {}
 4                            },
 5                 '_moon': None,
 6                 '_mars':{'mars': {}}
 7                 }
 8 
 9 exit_flag = True
10 while exit_flag:
11     for key1 in solar_system.keys():
12         print(key1)
13     choice1 = input("Which one would you want to watch?")
14     if choice1 in solar_system.keys():
15         if solar_system[choice1]:
16             for key2 in solar_system[choice1].keys():
17                 print(key2)
18             choice2 = input("Which one would you want to watch?")
19             if choice2 in solar_system[choice1].keys():
20                 if solar_system[choice1][choice2]:
21                     for key3 in solar_system[choice1][choice2].keys():
22                         print(key3)
23                     choice3 = input("Would you want you exit?")
24                     if choice3 == 'q':
25                         exit_flag = False
26                     else:
27                         print("\033[41;1mInvalid input!\033[0m")
28                 else:
29                     print("\033[41;1mNot exit!\033[0m")
30             elif choice1 == 'q':
31                 exit_flag = False
32             else:
33                 print("\033[41;1mInvalid input!\033[0m")
34         else:
35             print("\033[41;1mNot exit!\033[0m")
36     elif choice1 == 'q':
37         exit_flag = False
38     else:
39         print("\033[41;1mInvalid input!\033[0m")
View Code

一层一层好复杂,并且还有好多弊端,比如,各下层的技术不同,无法处理字符串等。