Examples of Python shopping cart simulation and python examples

Source: Internet
Author: User

Examples of Python shopping cart simulation and python examples

1. Features

This program simulates the user's purchase of goods after logging on to the mall. Allows users to log on, purchase commodities, query historical consumption records, and update balances and consumption information. Enter the initial account funds for the first login, and then log on to the system to obtain the balance after the previous consumption from the file. After each purchase, the corresponding amount will be deducted and the balance information will be updated, when you exit, the balance and consumption records are updated to the file for subsequent queries.

2. Implementation Method

Architecture:

This program is written in the python language to break down various tasks and define corresponding functions for processing, so that the program structure is clear and clear. I mainly wrote six functions:

(1) login (name, password)

The user logs on to the function to verify the user name and password. If the login succeeds, the number of logins is returned.

(2) get_balance (name)

Obtain user balance data.

(3) update_balance (name, balance)

Updates the user balance data. When the user exits by pressing the q key, the data is updated to the file.

(4) inquire_cost_record (name)

Query historical user consumption records.

(5) update_cost_record (name, shopping_list)

The user consumption record is updated. When the user exits by pressing the q key, the consumption record is updated to the file.

(6) shopping_chart ()

The main function completes human-computer interaction, function calling, and orderly implementation of various functions.

Main Operations:

(1) follow the prompts and press the number key to select the appropriate options for the operation.

(2) press the q key at any time to exit the logon. Before exiting, the user consumption and balance information are updated.

File used:

(1)userlist.txt

Stores user account information files, including user name, password, logon times, and balance. The number of user logins will be updated each time the user logs in successfully, and the balance information will be updated each time he or she presses the q key to exit.

(2) *** _cost_record.txt

A file that stores a user's ** consumption record. This file is created after the user buys the product for the first time. users who have not purchased the product will not generate this file. Every time you press the q key to exit, the latest consumption record is updated to the file.

3. Flowchart

4. Code

# Author: Byron Li #-*-coding: UTF-8-* contains the user account information file, this includes the user name, password, login times, and balance *** _cost_record.txt, which stores a user's *** consumption record file. After the user buys the product for the first time, users who have not purchased the product will not generate the file ''' import osimport datet Imedef login (name, password): # user login, user name and password verification. If logon succeeds, the number of Logon times with open('userlist.txt ', 'r +', encoding = 'utf-8') is returned ') as f: line = f. readline () while (line): pos = f. tell () line = f. readline () if [name, password] = line. split () [0: 2]: times = int (line. split () [2]) line = line. replace (str (times ). center (5, ''), str (times + 1 ). center (5, '') f. seek (pos) f. write (line) return times + 1 return Nonedef get_balance (name): # obtain user balance data w Ith open('userlist.txt ', 'R', encoding = 'utf-8') as f: line = f. readline () for line in f: if name = line. split () [0]: return line. split () [3] print ("User % s does not exist and cannot obtain its balance information! "% Name) return Falsedef update_balance (name, balance): # update the user balance data with open('userlist.txt ', 'r +', encoding = 'utf-8') as f: line = f. readline () while (line): pos1 = f. tell () line = f. readline () if name = line. split () [0]: pos1 = pos1 + line. find (line. split () [2]. center (5, '') + 5 pos2 = f. tell () f. seek (pos1) f. write (str (balance ). login ust (pos2-pos1-2, '') return True print (" User % s does not exist and its balance information cannot be updated! "% Name) return Falsedef inquire_cost_record (name): # query the user's historical consumption record if needed]): with open('''.join(name,'_cost_record.txt ']), 'R ', encoding = 'utf-8') as f: print ("historical consumption records ". center (40, '=') print (f. read () print ("". center (46, '=') return True else: print ("You have no historical consumption records! ") Return Falsedef update_cost_record (name, shopping_list): # update the user's consumption record if len (shopping_list)> 0: if not OS. path. isfile (''. join ([name, '_cost_record.txt ']): # When the first line is created, the first line is marked with "commodity price" with open (''. join ([name, '_cost_record.txt ']), 'A', encoding = 'utf-8') as f: f. write ("%-5 s % + 20s \ n" % ('item ', 'price') f. write (''. join ([datetime. datetime. now (). strftime ('% C'), 'consumption record']). center (40, '-') # Write consumption time information to facilitate subsequent query f. write ('\ n') f Or product in shopping_list: f. write ("%-5 s % + 20s \ n" % (product [0], str (product [1]) else: with open (''. join ([name, '_cost_record.txt ']), 'A', encoding = 'utf-8') as f: f. write (''. join ([datetime. datetime. now (). strftime ('% C'), 'consumption record']). center (40, '-') f. write ('\ n') for product in shopping_list: f. write ("%-5 s % + 20s \ n" % (product [0], str (product [1]) return True else: print ("You have not purchased this time. Do not update the consumption record! ") Return Falsedef shopping_chart (): # main function, user interaction, function call, result output product_list = [('iphone ', 5000), ('bike', 600 ), ('lenovo computer ', 7800), ('shirt', 350), ('washer ', 1000), ('Mineral water', 3), ('Watch ', 12000)] # store item list shopping_list = [] # The user purchases the item list while (True): username = input ("Enter the User name :") password = input ("Enter password:") login_times = login (username, password) # Check whether the entered username and password are correct. if the entered username and password are correct, the number of logins is returned. if login_times: print ('Welcome % s % d login times! '. Center (50, '*') % (username, login_times) if login_times = 1: balance = input ("Enter salary :") # enter the account funds for the First Login while (True): if balance. isdigit (): balance = int (balance) break else: balance = input ("Incorrect salary input. Please enter again:") else: balance = int (get_balance (username )) # Not the first login to obtain the account balance from the file while (True): print ("Please select whether you want to query the consumption record or purchase the product :") print ("[0] query consumption records") print ("[1] purchase item") choice = input (">>>") if choice. isdigit (): if int (choice) = 0: # query the calendar History consumption record inquire_cost_record (username) elif int (choice) = 1: # buy product while (True): for index, item in enumerate (product_list): print (index, item) choice = input ("Enter the product number to purchase the product:") if choice. isdigit (): if int (choice)> = 0 and int (choice) <len (product_list): if int (product_list [int (choice)] [1]) <balance: # Check whether the balance is sufficient. If the balance is sufficient, the product is successfully purchased. shopping_list.append (product_list [int (choice)]) balance = balance-int (product_list [int (choi Ce)] [1]) print ("\ 033 [31; 1 m % s \ 033 [0 m added to the shopping cart. Your current balance is \ 033 [31; 1 m % s RMB \ 033 [0 m "% (product_list [int (choice)] [0], balance) else: print (" \ 033 [41; 1 m your balance is only % s RMB, cannot purchase % s! \ 033 [0 m "% (balance, product_list [int (choice)] [0]) else: print (" incorrect input number. Please enter it again! ") Elif choice = 'q': # log out of the account and log out. Print the purchase list and balance information before exiting, and update it to the file if len (shopping_list)> 0: print ("this purchase item list ". center (50, '-') for product in shopping_list: print ("%-5 s % + 20 s" % (product [0], str (product [1]) print ("". center (50, '-') print ("your balance: \ 033 [31; 1 m % s RMB \ 033 [0 m" % balance) update_cost_record (username, shopping_list) update_balance (username, balance) print ("log out! ". Center (50, '*') exit () else: print (" You have no purchase record this time. Welcome to purchase it next time! ") Print (" log out! ". Center (50, '*') exit () else: print (" option input error. Please enter it again! ") Else: print (" option input error. Please try again! ") Elif choice = 'q': # log out of account logon print (" log out! ". Center (50, '*') exit () else: print (" option input error. Please enter it again! ") Break else: print ('user name or password is incorrect. Please enter it again! ') Shopping_chart () # main program running

The example of the above Python shopping cart simulation is all the content shared by Alibaba Cloud. I hope you can give me a reference and support the shopping cart.

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.