Python How to write a sample code share for a shopping cart program

Source: Internet
Author: User
Tags string back
Requirements

1, after starting the program, enter the user name password, if it is the first time to log in, let the user enter wages, and then print the product list

2. Allow users to purchase goods according to the product number

3, the user selects the goods, checks whether the balance is enough, enough on the direct debit, not enough on the reminder

4, can withdraw at any time, exit, print purchased goods and balance

5, in the user process, the key output, such as the balance, the product has been added to the shopping cart and other messages, need to highlight

6, the user after the next login, enter the user name password, directly back to the last state, that is, the balance of the last consumption or those, re-login to continue to purchase

7, allow to query the previous consumption records

1) Writing Ideas

Writing ideas refer to the flowchart in the GitHub link below

2) Concrete Implementation

#-*-Coding:utf-8-*-# author:chuixin zeng# importing JSON module import json# Import date Time Module import datetime# import System OS module import os# custom Welcome Info Info = "' 1. Press "A" to register 2. Press "B" to log in to 3. Press "Q" to exit "# custom error message _error_info = ' input wrong, please check and re-enter!" ' # defines a _save_account function # used to save the shopping-related information to a JSON file, such as shopping time, shopping history, shopping list, account balances, creating new users and existing user information Def _save_account (database,    Filename= ' Database.json '): # Open and Writable file, if the file already exists, the previous content will be cleared # using the WITH AS statement is more efficient, you do not need to set how to read the file and then how to close the file, a with as to handle all read and write close operation with open (filename, ' W ') as F: # F is equivalent to a variable that assigns an open and modified file operation to F Json.dump (database,f) # json.dump is a Python data type list JSON Encoding parsing # defines a _load_database function for reading information from a JSON file, the default loaded database is Database.json file def _load_database (filename= ' Database.json ')  : with open (filename) as F:database = Json.load (f) # Decodes JSON data, converts a JSON-encoded string back to a python data structure return database #    Returns the decoded data # defines a function _set_shopping_time, sets and records the time of the purchase, and defines a parameter account in the function that is used to save the accounts information def _set_shopping_time: Database = _load_database () # sets which databases to log to, using the previously defined function _load_database defined database.json d1 = Datetime.daTetime.now () # Set shopping time to current time D2 = D1.strftime ('%y-%m-%d%h:%m:%s ') # Convert current time to format database[account][' shopping_time '] = D2 # to log the converted time to the Shopping_time key in the dictionary _save_account (database) # Save the shopping time to the database, where the databases refer to the Database.json file # defines a function,  Used to get saved shopping time Def _get_datetime (account): Database = _load_database () data = database[account][' Shopping_time '] # Return the value of the variable data, the variable data is saved is the account key corresponding to the shopping time value, this value is decoded from the JSON inside the dictionary # from JSON to Python recognizable dictionary data decoding process by the _load_database function to complete the return data# defines a function _get_shopping_history to query the shopping history def _get_shopping_history (account): Database = _load_database = database[account][' shopping_list ' # Add an empty list with the bottom for loop to merge duplicates from the shopping list with AA = [] for I in the history: # will the cart inside the SH opping list and AA empty lists to compare, if not inside the list, add to the list # also means that if the list has been added, to achieve the shopping cart to go to the heavy function if I not in aa:aa.append  (i) # then loop through the shopping list inside the AA list for j in AA: # count the number of each item purchased, that is, the quantity of each item in the AA list, and the quantity from the history's original list (the list that has not been redirected) Count = History.count (j) # Statistics on the date of purchase of goods, dayThe period is the date of the item that corresponds to the account dictionary. _get_datetime (account) # Prints the number of items purchased, date and product name print (' you purchased%s piece%s ' in%s '% (date,c OUNT,J) # defines a function login, used to log on to System Def _login (): Database = _load_database () # Loads the databases, using the previously defined functions to load the database blacklist = _load_d Atabase (' Blacklist.json ') # Set the user's blacklist list, the user in the list will not be allowed to sign in to the shopping system print (' Welcome to the shopping system!            ') # Print welcome message # First Dead loop while True:account = input ("Please enter your account login system (press Q to exit):") If accounts in blacklist: # If the account is in the blacklist, exit login print ("Your account has been locked, please contact the administrator to handle!") ") _logout () # directly calls the following defined _logout () function # to determine if the user entered Q, exit the shopping system elif account = = ' Q ': _logou T () # To determine if the user is inside the database, continue to determine if the user entered the correct password # here use while loop and count counter, if the input error password is greater than 3 times, then lock the account elif accounts in Databas E:count = 0 while count < 3:pwd = input (' Please enter password: ') # If the user enters the password and the database             The saved password matches if pwd = = database[account][' pwd ']: # goes into the dead loop while True:           # First Login successful, first get the balance of the user account, tell the user how much money left, the balance through the _get_balance function to get account_balance = _get_balance (accou                        NT) # Highlight print account balance information print (' Your account balance is \033[32m%d\033[0m '% account_balance) # Let the user enter a specific letter into a specific menu, and use strip to remove the message before and after the space Command = input (' press H to search shopping history, press S to start shopping, press T to recharge, start shopping after purchase                        The material history will be emptied: '). Strip () # Import user shopping Information database = _load_database () # Determine if the user entered H, then query the purchase history if Command = = ' h ': # to determine if the shopping time is not empty, prove that the user has purchased History if database[account][' Shopping_time ']! = None: # load function _get_sho                                Pping_history, export shopping history information _get_shopping_history (account) Else: Print (' You have not bought anything in this shop! ') elif command = = ' t ': # If the user enters T, load the defined _top_up function, perform recharge operation _TOP_UP (account) elif Command = = ' s ':                            # If the user enters S, the shopping list and time in the dictionary are initialized to null # Note: This dictionary is converted from a JSON file with historical data, so it needs to be emptied first.                            # After the user has finished shopping, the new dictionary data, that is, the shopping data, will be written back to the JSON file database[account][' shopping_list ' = []                            database[account][' shopping_time ' = None # Call the _save_account function to save the empty operation to the database file                            _save_account (database) # Call the shopping function to start shopping                            _shopping (account) Else: # Output error message if the user's action does not match all of the above                    # here is a direct call to the previously defined _error_info function, output error message print (_error_info) Else:            Count + = 1 # tells the user how many more chances to try to log on to print (' Input password error, you also have%s opportunity '% (3-count)) # Add user account to blacklist, saved as a dictionary, value is set to None # The Setdefalut usage of the dictionary is used, and if the dictionary contains a given key, the value corresponding to that key is returned, otherwise the value set for the key is returned Blacklist.setdefault ( Account) # After the user enters three error actions, it jumps out of the while loop, and then prints the message telling the user that the username is locked print (' Your account is locked! # to save the locked account information to the Blacklist list _save_account (blacklist, ' Blacklist.json ') # Call the function that exits the login _l Ogout () Else:print (' account does not exist, please try again! or enter B to return to the previous level, enter Q and exit the shopping program! ') # define a function _set_shopping_list to set the shopping list Def _set_shopping_list (account,c_name,num): Database = _load_database () # Use for Loop add the number of items purchased for I in range (num): # Add the purchased item to the list corresponding to the dictionary shopping_list key database[account][' shopping_list '].a Ppend (c_name) # Saves the purchase information to a JSON file by calling the _save_account function _save_account (database) # defines a function _set_balance, which is used to calculate what is left after the purchase Balance def _set_balance (account,num): Database = _load_database () # After purchasing a product, deduct the price of the purchased item database[account][' Balance ']-= Num # Saves the balance information to a JSON file by calling the _save_account function _save_account (database) # defines a function to perform a recharge operation def _top_up (account): Database = _load_database () # enters Loop while True: # provides an interactive interface for users to enter the amount to recharge num = input (' Please enter the amount you want to recharge: ') # to determine if the user entered is not a pure number, then the amount after the top up update to the database if Num.isdigit (): # To determine whether the input is a pure number (the data to be recharged must be a pure number) database[account]["b Alance "] + = int (num) # converts" pure number "in str format to int format _save_account (database) # Save to file Account_balance = _get _balance (account) # then read the balance information from the file # Highlight the balance information printed after the top-up print (' You have successfully topped up, your balance is \033[32m%d\033[0m yuan '% account_bal ance) # The balance has already been printed, so here is a return none to return the balance returned without return # none # If the user entered is not a pure number, then prompted to enter an error, re- Make a while loop and let the user reenter Else:print (' Your input is wrong, please re-enter! ') # define a function _get_balance to get the account balance def _get_balance: Database = _load_database () # reads the balance information from the account in the dictionary to the account_balance variable  Volume account_balance = database[account][' balance '] # returns the value of the account balance variable return account_balance# define a function _shopping, used to execute the shopping program def _shopping (account): # defines a dictionary for saving the product menu goods = {' Home appliance class ': {' TV ': {' Xiaomi TV ': 3999, ' Le video tv ': 4299}, ' air conditioning ': {' gree air conditioning ': 8999, ' Haier air conditioning ': 6000}, ' refrigerator ': {' Midea refrigerator ': 5099, ' Siemens Refrigerator ': 4599}}, ' 3C class ': {' computer ': {' Lenovo Notebook ': 6888, ' Mac air ': 8009}, ' phone ': {' Xiaomi 5 ': 1999, ' IPhone6 ': 529    9}}, ' Life class ': {' shoes ': {' Nike basketball Shoes ': 899, ' Anta ': 399}, ' t-shirts ': {' mori ': 89, ' jeanswest ': 75, ' Uniqlo ': 97}}            # First-level dead loop while True: # loop directly to product name by using enumerate for I in Enumerate (Goods.keys ()): # Print First level menu        Print (i) # provides an interactive interface that allows the user to enter the category name of the product to be selected, select the first menu choose = Input (' Please enter the name of the product category you want to select (Enter Q exit): '). Strip () # defines an empty string to hold a level two menu str1 = ' If choose in goods: # If the user enters the correct category, then print out all the items in the product category fo R i in enumerate (Goods[choose].keys ()): # Print User selected level menu below the level two menu print (i) # Two-level menu            Append to str1 variable str1 + = (i[1] + ' \ n ') # All level two menus are added to the str1 after str1 add: str1 + = ': ' # Second Stage dead loop WHile True: # classification comes from the previous choose Interactive input, categorized below the list to the STR1 variable # lets the user choose a level two menu C_name = Inpu                T ("Enter the name of the%s category you want to select (Enter B to return, enter Q to exit): \n%s"% (choose, str1)). Strip () # defines an empty string for saving level three menu str2 = '                if c_name = = ' B ': # If the user enters B, it interrupts the current while loop and returns to the upper upper loop, which returns to the top menu break                elif C_name = = ' Q ': # If the user enters Q, call the _log_out function, exit the login _logout (account)                    # If the user entered the name in the level two menu, then through for the user selected level two menu items below the level three menu traverse out Elif c_name in Goods[choose]: For I in Goods[choose][c_name].keys (): # Print the Level three menu below the two-level menu and print the item and price # I                        From Keys the key name (item name), Goods[choose][c_name][i] takes the value of the key, that is, the price print (I,goods[choose][c_name][i])                        STR2 + = (i + ' \ n ') str2 + = ': ' # third-level dead loop while True: # inThe interactive interface allows the user to enter the name of the product to be purchased, the product catalog from the STR2 variable p_name = input (' Please enter the name of the product you want to buy (input B returns to the previous level, q exit, h query cart): \n%s '                        % str2). Strip () # If the user enters B, jump out of the while loop at this level and go back to the previous level                        if p_name = = ' B ': Break # If the user entered Q, then call the _logout function directly, exit the shopping elif P_name = = ' Q ': _logout (account) # If the user enters the H, query the JSON file for the shopping calendar                            Shi Elif p_name = = ' h ': Database = _load_database ()                                # There is a shopping history, then call the _get_shopping_history function, output shopping history if database[account][' Shopping_time ']! = None:                            _get_shopping_history () # Plum Shopping History, then tell the user no shopping history Else:print (' You do not have a shopping record in this shop! ') # If the product name entered by the user is elif in the selected product category P_naMe in Goods[choose][c_name]: # layer Fourth dead loop while True:                                # Interactive interface lets users enter the number of items to buy num = input (' Please enter the number of items to be purchased: '). Strip () # If the user enters a pure number if Num.isdigit (): # First convert a pure number to an integer                                    Type num = int (num) # defines a account_balance variable that holds the current account balance Account_balance = _get_balance (account) # defines a price variable, total price                                    Grid = Unit Price * Quantity, unit price from the dictionary, quantity from num prices = (goods[choose][c_name][p_name]) * num                                        # to determine if the account balance is greater than the amount of the purchased item, you can purchase if account_balance >= Price: # Call the _set_balance function to calculate how much the account balance is after purchase # #计算方法在_set_bal                Inside the ance function                        _set_balance (account,price) # Prompt user has successfully purchased a product Print (' You have successfully purchased%d items:%s! '                                        % (Num,p_name)) # Call the _set_shopping_list function to save the list of purchased items in a JSON file _set_shopping_list (Account,p_name,num) # defines the account_balance variable by using the _g                                        Et_balance function re-obtains the balance information of the account Account_balance = _get_balance # print tells the user how much money is left after the product has been purchased print (' Your current account balance is \033[31m%d\033[0m '% acc                                        Ount_balance) # Call the _set_shopping_time function to write the shopping time to the JSON file                                        _set_shopping_time (account) # exits the current loop, up to the previous cycle, and the user can choose whether to continue shopping   Break # If the user's account balance is less than the amount of the item, tell the user that the balance is insufficient and cannot purchase                                 Else:print (' Your account balance is insufficient, please recharge it in time! ') G = input ("Recharge input t, return to input B above, exit input Q ':") if G                                            = = ' Q ': _logout () if G = = ' B ':                                        break if G = = ' t ':                                # Here I added a call _top_up function, when the account balance is not live, immediately prompt users to recharge _top_up                                    # If the number entered when the user buys the product is not a purely numeric type, call the _error_info function and output the error message else:                        Print (_error_info) # Call the _error_info function to output an error message if the user enters an incorrect product name for the purchase                Else:print (_error_info) # # Call the _error_info function to output an error message if the user enters a purchased product classification information that is incorrect Else:print (' LoseIn error, please re-enter! ') # If the user input is not a commodity classification, but Q, then call the _logout function to exit the login elif choose = = ' Q ': _logout (account) # If the user input information is neither In the product classification, nor Q, tells the user to reenter Else:print (' input error, please re-enter! ') #def _add_user (): # First Call the _load_database function, decode the JSON file, put the database variable database = _load_database (' Database.json ') # Execute while Loop while True: # provides an interactive interface that lets the user enter the user name to be created username = input (' Please enter your account name: '). Strip () # Determine if there is a user with duplicate names , if any, tells the user to continue executing the while loop, allowing the user to enter if username in Database:print (' username already exists and does not need to be created repeatedly!        ') # If not, the user input information is valid, interrupt while loop Else:break # execute while Loop while True: # Let the user enter the password two times PWD1 = input (' Please enter your account password: '). Strip () Pwd2 = input (' Please re-enter your account password: '). Strip () # two times the password information entered is correct # if the mask is incorrect, then Continue the While loop to let the user reenter the IF pwd1! = Pwd2:print (' 2 input password is not allowed, please re-enter ') # If the password entered is correct, then tell the user to create the account successfully Els E:print (' Create user success, start shopping! ') # Save user-created account and password information to database Dictionary # usernameFor user account, pwd1 for user password, balance for account balance, shopping_list for shopping list, shopping_time for shopping time database[username] = {' pwd ':p wd1, ' balance ': 0 , ' shopping_list ': [], ' Shopping_time ': None} # Call the _save_account function to save the created account information and the initial balance of the account, the initial shopping time information to the JSON file _s Ave_account (Database) # exit while loop break# set the default variable account = None to determine if a login is logged in, and if you exit without logging in, do not print the shopping information # If you have already logged in , print the shopping history information def _logout (Account=none): if account! = None: _get_shopping_history (account) exit (' Thank you for shopping! ') # define a main function for the initial login interface to determine the DEF main (): # Execute while Loop while True: # Print the login prompt information, the info definition at the beginning of the program, is a string type print (i        NFO) # provides an interactive interface that allows the user to enter command information command = input (' Please enter directive: '). Strip () # If the user enters an uppercase A, call the _add_user function to create a new user If command.upper () = = ' A ': _add_user () # If the user enters a uppercase B, call the _login function to log in Elif command.upper () = = '        B ': _login () # If the user enters Q, call the _logout function, exit the login elif command.upper () = = ' Q ': _logout () # If the user does not follow the prompts to enter, then tell the user to re-loseRe-executes the while loop else:print (' input error, reenter ') # executes the main function if __name__ = = ' __main__ ': Main () 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.