Home Backend Development Python Tutorial Write shopping mall(1)

Write shopping mall(1)

Jun 23, 2017 pm 03:13 PM
write shopping mall

  作业:购物商城

    商品展示,价格

    买,加入购物车

    付款,钱不够

    具体实现了如下功能:
        1、可购买的商品信息显示
        2、显示购物车内的商品信息、数量、总金额
        3、购物车内的商品数量进行增加、减少和商品的删除
        4、用户余额的充值
        5、用户购买完成进行结账,将最终余额回写到用户文件中。

    一、用户文件说明:

kevin 123 50000sky   123 54000mobi  123 80000
Copy after login

    其中第一列为用户名,第二列为密码,第三列为帐户余额。

    二、流程图如下:

   

import sys,os,getpass,time

def input_handle(s):'''用户输入字符数字转化为数字'''if s.isdigit():    #判断用户输入是否是字符数字
        s = int(s)     #是的话就进行转换return s

def framework(user="",init_money='',now_money='',recharge_money='',value=''):'''架构函数,展示用户的基本信息'''os.system("clear")
    init_money = int(init_money)
    now_money = int(now_money)
    recharge_money = int(recharge_money)
    message = '''******************************************************************************* \033[32;1m欢迎来到小猪猪购物商城\033[0m*******************************************************************************会员:%s\t金额:%d\t当前余额:%d\t充值金额:%d\t购物车:%d'''  %(user,init_money,now_money,recharge_money,value)    print(message)

def goods_list_show(my_dict):'''商品展示模块,用于展示商品'''local_dict = {}'''对商品列表进行遍历并加上数字编号'''i = 1print("商品列表:")
    print("=================================================================================================")
    print("%-5s  %-15s  %-10s  %-10s  %-10s" %("编号","商品名称","商品价格(元)","商品总数量(个)","商品剩余数量(个)"))for k in my_dict.keys():
        v = my_dict[k]if type(v) == dict:
            print("%-5s  %-20s  %-15d  %-18d  %-10d"  %(i,k,v['price'],v['num'],v['sum']))
            local_dict[i] = [k,v["price"],v['num'],v['sum']]
        i += 1print("=================================================================================================")return local_dict

def cart_goods_show(show_dict):'''显示购物车商品,并加上数字编号'''show_all_sum = 0show_all_num = 0'''对商品列表进行遍历并加上数字编号'''message = ('编号',"商品名称","商品价格(元)","商品总数量(个)","购买数量(个)","购买金额(元)")
    print("%-5s \t %-20s \t %-10s \t %-10s \t %-10s \t %-10s" %message)for k in show_dict:
        v = show_dict[k]if type(v) is dict:
            print("%-5s \t %-10s \t %-10d \t %-10d \t %-10d \t %-10d" %(k,v[0],v[1],v[2],v[3],v[4]))
            show_all_num += v[4]
            show_all_num += 1print("请确认你购买的商品,总金额:%d元"%(show_all_sum))return (show_all_sum,show_all_num)

def cart_goods_modify(modify_dict,modify_goods_dict):'''购物车商品修改列表'''a_flag = 1while a_flag:
        index = input("请输入商品编号|完成修改(q):" %modify_dict[index][2])if len(index) != 0:
            index = input_handle(index)if index == "q":breakelif index in modify_dict:
            b_flag = 1name = modify_dict[index][0]while b_flag:
                num = input("请输入新的商品数量(最大值为%d)|完成修改(q):" %modify_dict[index][2])if len(num) != 0:
                    num = input_handle(num)if num == 'q':breakelif num == 0:
                        modify_goods_dict[name]['num'] = modify_dict[index][2]
                        del modify_dict[index]
                        b_flag = 0elif num > 0 and num <= modify_dict[index][2]:
                        modify_dict[index][3] = num
                        modify_dict[index][4] = modify_dict[index][1] * num
                        modify_goods_dict[name][&#39;num&#39;] = modify_dict[index][2] - num
                        b_flag = 0else:
                        passelse:
             passreturn  (modify_dict,modify_goods_dict)

def shopping_cart_show(my_cart,my_goods_dict):&#39;&#39;&#39;购物车展示&#39;&#39;&#39;print("欢迎来到你的购物车".center(80,"#"))
    goods_all_sum = 0goods_all_num = 0if my_cart:&#39;&#39;&#39;调用购物车商品列表函数,并返回商品总金额和总数量&#39;&#39;&#39;(goods_all_sum,goods_all_num) = cart_goods_show(my_cart)
        choice = input("请进行如下操作:修改记录(c)|继续购物(!c)")if choice == "c":
            (my_shop_cart,my_goods_dict) = cart_goods_modify(my_cart,my_goods_dict)
            (goods_all_sum,goods_all_num) = cart_goods_show(my_cart)else:
            passelse:
        print("您当前的购物车为空".center(80,"#"))

    time.sleep(2)return (goods_all_sum,goods_all_num,my_goods_dict)

def balance_recharge(recharge_init_balance,recharge_now_balance,recharge_money):
    recharge_flag = 1while recharge_flag:
        recharge_num = input("请输入充值金额|返回(b)|退出(q):")if len(recharge_num) != 0:
            recharge_num = input_handle(recharge_num)if recharge_num == "q":
            sys.exit(0)
        elif recharge_num == &#39;b&#39;:breakelif type(recharge_flag) is int and recharge_num > 0:
            recharge_init_balance += recharge_num
            recharge_now_balance += recharge_num
            recharge_money += recharge_num
            recharge_flag = 0print("充值成功,请查收".center(80,"#"))else:
            passreturn (recharge_init_balance,recharge_now_balance,recharge_money)

def user_billing(billing_list,my_cart,billing_balance):'''结帐模块'''print("欢迎来到结帐模块".center(80,"#"))if my_cart:'''调用购物车商品列表函数'''cart_goods_show(my_cart)
        billing_flag = input("请确认是否商品结算(y|n):")if billing_flag == "y":
            billing_file = open("info.txt",'w')for user_info in billing_list:
                billing_file.writelines(user_info)
            billing_file.close()
            sys.exit("结帐成功,您当前余额:%d".center(80,"#") %billing_balance)else:
            print("退出结算菜单,继续购物".center(80,"#"))
            time.sleep(2)else:
        print("您当前的购物车为空,无需结算!")
        time.sleep(2)'''主程序开始'''if __name__ == "__main__":
    goods_list = {             'iphone6': {'price':6000,'num':10,'sum':10},             'ipad': {'price':3000,'num':20,'sum':20},             'mi4': {'price':2000,'num':43,'sum':43},             'huawei6_plus': {'price':1999,'num':8,'sum':8},
            }
    i  = 0while i < 3:                                                  #只要用户登录不超过3次就不断循环
        username = input("请输入用户名:")
        password = input("请输入密码:")
        user_file = open("info.txt",&#39;r&#39;)
        user_list = user_file.readlines()
        user_file.close()for user_line in user_list:&#39;&#39;&#39;分别获取当前账号、密码和余额信息&#39;&#39;&#39;user,passwd,init_balance = user_line.strip(&#39;\n&#39;).split()
            init_balance = int(init_balance)
            now_balance = init_balance
            my_goods_sum = 0if user == username and password == passwd:
                user_shopping_cart = {}
                user_shopping_cart_count = 0recharge_value = 0line_num = user_list.index(user_line)
                first_flag = 1while first_flag:&#39;&#39;&#39;调用框架函数输出用户信息&#39;&#39;&#39;framework(username,init_balance,now_balance,recharge_value,user_shopping_cart_count)
                    goods_output_dict = goods_list_show(goods_list)   #输出商品信息
                    goods_index = input("请选择菜单:输入商品编号 | 购物车(c) | 余额充值(r) | 结账(b) | 退出(q) :")if len(goods_index) != 0:
                        goods_index = input_handle(goods_index)if goods_index == &#39;q&#39;:
                        sys.exit(0)

                    elif goods_index == &#39;c&#39;:&#39;&#39;&#39;调用购物车显示函数,并返回购物车商品总金额&#39;&#39;&#39;(my_goods_sum,user_shopping_cart_count,goods_list) = shopping_cart_show(user_shopping_cart,goods_list)
                        now_balance = init_balance - my_goods_sumif now_balance < 0:
                            print("您的余额不足,请及时充值!")
                            time.sleep(2)

                    elif goods_index == &#39;r&#39;:
                        (init_balance,now_balance,recharge_value) = balance_recharge(init_balance,now_balance,recharge_value)

                    elif goods_index == &#39;b&#39;:&#39;&#39;&#39;更新用户的余额&#39;&#39;&#39;user_list[line_num] = user + &#39; &#39; + passwd + &#39; &#39; + repr(now_balance) + &#39;\n&#39;user_billing(user_list,user_shopping_cart,now_balance)

                    elif goods_index in goods_output_dict:&#39;&#39;&#39;取出goods_index商品列表信息并进行赋值和展示&#39;&#39;&#39;(goods_name,goods_price,goods_num) = (goods_output_dict[goods_index][0],goods_output_dict[goods_index][1],goods_output_dict[goods_index][2])
                        print(&#39;【 编号:%-5d \t 名称:%-15s \t 价格:%-5d(元) \t 数量:%-5d(个)】&#39; % (goods_index, goods_name, goods_price, goods_num))

                        second_flag = 1while second_flag:
                            buy_num = input(&#39;请输入购买商品个数(最大值为%d) | 返回(b) | 退出(q): &#39; % goods_num)if len(buy_num) != 0:
                                buy_num = input_handle(buy_num)if buy_num == &#39;q&#39;:
                                sys.exit(0)
                            elif buy_num == &#39;b&#39;:breakelif type(buy_num) is int and buy_num > 0 and buy_num <= goods_num:
                                my_goods_sum = goods_price * buy_numif my_goods_sum <= now_balance:
                                    print('购买商品 %s 总价格为 : %d' % (goods_name, my_goods_sum))
                                    add_flag = input("请确认是否加入购物车(y | n):")if add_flag == "y":'''判断购物车不存在该商品'''if goods_index not in user_shopping_cart:
                                            user_shopping_cart_count += 1'''购物车商品数量加一'''user_shopping_cart[goods_index] = [goods_name,goods_price,goods_num,buy_num,my_goods_sum]else:
                                            user_shopping_cart[goods_index][3] += buy_num
                                            user_shopping_cart[goods_index][4] += my_goods_sum

                                        now_balance -= my_goods_sum

                                        goods_list[goods_name]['num'] -= buy_num
                                        second_flag = 0else:breakelse:
                                    print("您的余额不足,请充值或重新选择,谢谢!")
                                    time.sleep(2)else:
                                passelse:
                         passelse:if i != 2:
                print('用户或密码错误,请重新输入,还有 %d 次机会' % (2 - i))
            i += 1else:
        sys.exit('用户或密码输入错误超过三次,退出系统,欢迎下次光临')
Copy after login

    上述代码不难,难的是思路,思路很重要,要知道如何一步一步去操作,用的也都是我们常用的知识,其实归根揭底我们写程序,大部分使用的都是字符串,字典,列表的功能。还有一些模块之类的。在写程序的过程中,思路显得尤为重要。知道了思路,就考虑如何使用代码去实现,上面程序中学到了如下知识点;

    1、输出格式对其:print("%-5s %-15s %-10s %-10s %-10s" %("编号","商品名称","商品价格(元)","商品总数量(个)","商品剩余数量(个)")),上面代码能够实现对其格式的功能,让我们输出的字符串格式统一,比如上述代码中,编号左对齐5个字符,商品名称左对齐15个字符等等;

    2、str.center()的使用,如print("欢迎来到你的购物车".center(80,"#"))

 

The above is the detailed content of Write shopping mall(1). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to write Bloom filter algorithm using C# How to write Bloom filter algorithm using C# Sep 21, 2023 am 10:24 AM

How to use C# to write a Bloom filter algorithm. The Bloom Filter (BloomFilter) is a very space-efficient data structure that can be used to determine whether an element belongs to a set. Its basic idea is to map elements into a bit array through multiple independent hash functions and mark the bits of the corresponding bit array as 1. When judging whether an element belongs to the set, you only need to judge whether the bits of the corresponding bit array are all 1. If any bit is 0, it can be judged that the element is not in the set. Bloom filters feature fast queries and

Write a method to calculate power function in C language Write a method to calculate power function in C language Feb 19, 2024 pm 01:00 PM

How to write exponentiation function in C language Exponentiation (exponentiation) is a commonly used operation in mathematics, which means multiplying a number by itself several times. In C language, we can implement this function by writing a power function. The following will introduce in detail how to write a power function in C language and give specific code examples. Determine the input and output of the function The input of the power function usually contains two parameters: base and exponent, and the output is the calculated result. therefore, we

How to write a dynamic programming algorithm using C# How to write a dynamic programming algorithm using C# Sep 20, 2023 pm 04:03 PM

How to use C# to write dynamic programming algorithm Summary: Dynamic programming is a common algorithm for solving optimization problems and is suitable for a variety of scenarios. This article will introduce how to use C# to write dynamic programming algorithms and provide specific code examples. 1. What is a dynamic programming algorithm? Dynamic Programming (DP) is an algorithmic idea used to solve problems with overlapping subproblems and optimal substructure properties. Dynamic programming decomposes the problem into several sub-problems to solve, and records the solution to each sub-problem.

How to use C++ to write a simple student course selection system? How to use C++ to write a simple student course selection system? Nov 02, 2023 am 10:54 AM

How to use C++ to write a simple student course selection system? With the continuous development of technology, computer programming has become an essential skill. In the process of learning programming, a simple student course selection system can help us better understand and apply programming languages. In this article, we will introduce how to use C++ to write a simple student course selection system. First, we need to clarify the functions and requirements of this course selection system. A basic student course selection system usually includes the following parts: student information management, course information management, selection

How to write a simple hotel reservation system using C++? How to write a simple hotel reservation system using C++? Nov 03, 2023 am 11:54 AM

The hotel reservation system is an important information management system that can help hotels achieve more efficient management and better services. If you want to learn how to use C++ to write a simple hotel reservation system, then this article will provide you with a basic framework and detailed implementation steps. Functional Requirements of a Hotel Reservation System Before developing a hotel reservation system, we need to determine the functional requirements for its implementation. A basic hotel reservation system needs to implement at least the following functions: (1) Room information management: including room type, room number, room

How to write a simple minesweeper game in C++? How to write a simple minesweeper game in C++? Nov 02, 2023 am 11:24 AM

How to write a simple minesweeper game in C++? Minesweeper is a classic puzzle game that requires players to reveal all the blocks according to the known layout of the minefield without stepping on the mines. In this article, we will introduce how to write a simple minesweeper game using C++. First, we need to define a two-dimensional array to represent the map of the Minesweeper game. Each element in the array can be a structure used to store the status of the block, such as whether it is revealed, whether there are mines, etc. In addition, we also need to define

How to write KNN algorithm in Python? How to write KNN algorithm in Python? Sep 19, 2023 pm 01:18 PM

How to write KNN algorithm in Python? KNN (K-NearestNeighbors, K nearest neighbor algorithm) is a simple and commonly used classification algorithm. The idea is to classify test samples into the nearest K neighbors by measuring the distance between different samples. This article will introduce how to write and implement the KNN algorithm using Python and provide specific code examples. First, we need to prepare some data. Suppose we have a two-dimensional data set, and each sample has two features. We divide the data set into

How to write a binary search algorithm using C# How to write a binary search algorithm using C# Sep 19, 2023 pm 12:42 PM

How to use C# to write a binary search algorithm. The binary search algorithm is an efficient search algorithm. It finds the position of a specific element in an ordered array with a time complexity of O(logN). In C#, we can write the binary search algorithm through the following steps. Step 1: Prepare data First, we need to prepare a sorted array as the target data for the search. Suppose we want to find the position of a specific element in an array. int[]data={1,3,5,7,9,11,13

See all articles