Basic python exercises-Simple user card management (not the full version)

Source: Internet
Author: User

Basic python exercises-Simple user card management (not the full version)
The first thing to note is that the system is not completely written, and only a few simple functions are implemented. Of course, other functions are similar. The knowledge point used is also the simplest syntax knowledge. It is mainly used as a beginner like me to practice, so the code is not so perfect, and the structure is not necessarily perfect. Maybe I will look back one day, I think it is very spam. It is for the reference of the original learners only. If you are interested, you can continue to complete it yourself. 1. First, let's take a look at the demonstration of the existing functions (there are still many functions to be improved, and there is no time to change them. We will talk about the areas to be optimized later) 1) log on to [root @ localhost shop] # python main. py welcome to use this card swipe System please input your user_id: 001 please input you password: # Here I stole the lazy and made a password not to Echo. Sucess! Wellcome! Menue: 1 shoping2 withdraw3 query4 user_man5 comm_man6 exitplease input your choice: 2) Shopping menue: 1 shoping2 withdraw3 query4 user_man5 comm_man6 exitplease input your choice: 1 # follow the prompts to enter the shopping mode by 1 id name Price quantity 001 apple 2-490434002 orange 2 9900003 pear 3 10000004 watermelon 3-399700005 peach 4 500 please choose the commodity id you want: 001 please input the quantity of commodity youwant to buy: 800 shopping success # No judgment here Whether the amount is sufficient, so if the number is negative, you can also buy if shopcontinue ("Y" or "N"): # Here you can choose whether to continue 3) Withdrawal menue: 1 shoping2 withdraw3 query4 user_man5 comm_man6 exitplease input your choice: 2 # The withdrawal module is simple. you can enter the withdrawal amount. please input you want to withdraw: 1000 the withdrawal is successful. Withdrawal amount: 1000 current balance: 987372 4) query menue: 1 shoping2 withdraw3 query4 user_man5 comm_man6 exitplease input your choice: 31: Query shopping records 2: Query withdrawal records 3: Query deposit records 4: exit select the query type: 2 # here, only the user_id type amount of the withdrawal record is queried. Time 001 withdrawal 00 2015-09-13 19: 44: 46001 withdrawal 1000 2015-09-13 20: 31: 071: Query shopping records 2: Query withdrawal records 3: Query deposit records 4: exit SELECT query type: 4 5) there are also user management, product management and other functions that have not been completed due to work and other reasons. Of course, there are a lot of detailed functions that will not be demonstrated here and will be commented out in the Code. 2. First, introduce several files used by the system.

[Root @ localhost shop] # ls-ALB | cut-c 43-commodity.txt # Save the product information file, including the product id, price, and quantity login. py # main. py # query of the main function module. py # query module. Here, only the shop module of user withdrawal record can be queried. py login shopping mall user.txt # Save the user information file, including the user ID, user name, password, available amount withdraw_log.pkl # The user saves the withdrawal information log file, pickle file type. Withdraw. py # withdrawal Module

 

Iii. main module
[Root @ localhost shop] # more main. py #! /Usr/bin/evn python #-*-coding: UTF-8-*-# Main Menu file # import the relevant module import sysimport pickleimport getpass # import the self-built module import loginimport shopimport withdrawimport query print 'Welcome to use this card swiping system' # login interface login_times = 1 while True: # wihle implements incorrect user ID and password. You can repeat user_id = raw_input ('Please input your user_id :'). strip () # pwd = raw_input ('Please input you password :'). strip () # The password is not previously implemented. A more reasonable way is to display the asterisk (*) In the user input. Pwd = getpass. getpass ('Please input you password: ') # The password is not displayed if login. login (user_id, pwd): # implement repeated user input up to three times to avoid infinite loop print 'sucess! Wellcome! 'Break else: if login_times <3: login_times + = 1 continue else: print 'you faild above3 times' sys. exit () while True: # The entire while loop is implemented as long as the user does not actively exit, the program continues to run # print the menu print ('menue: \ n1 \ tshoping \ n2 \ twithdraw \ n3 \ tquery \ n4 \ tuser_man \ n5 \ tcomm_man \ n6 \ texit ') while True: try: # exception handling is only performed here, otherwise, the program exits. Choice_id = int (raw_input ('Please input your choice: ') break failed t Exception, e: print' the input is invalid. Enter the number 'if choice_id = 1: # select 1 to enter the shopping mode while True: # exit this loop through the while loop and return to the previous loop # print the optional product shop. comm_print () comm_id_choice = raw_input ('Please choose the commodity id you want: ') comm_quantity = raw_input ('Please input the quantity of commodity you wantto buy:') shop. shop (user_id, comm_id_choice, comm_quantity) continue_y_n = raw_input ('If shopcontinue ("Y" or "N "):') if continue_y_n = 'y' orcontinue_y_n = 'y': continue if continue_y_n = 'n' orcontinue_y_n = 'N': break elif choice_id = 2: # select 2 to enter the withdrawal mode amount = raw_input ('Please inputyou want to withdraw: ') withdraw. withdraw (user_id, amount) elif choice_id = 3: # select 3 to enter the query mode while True: print '1: query the shopping record \ n2: query the withdrawal record \ n3: query deposit records \ n4: exit 'query_choice = int (raw_input ('select Query type: ') if query_choice = 1: print "shopping query record" elif query_choice = 2: query. q_withdraw_log (user_id) elif query_choice = 3: print 'query the deposit record 'elif query_choice = 4: print 'exit 'break else: print 'byebye 'break elif choice_id = 4: # select 4 to enter the user management mode (not implemented) pass print 'user _ man' elif choice_id = 5: # select 5 to enter the product management mode (not implemented) pass print 'comm _ man 'elif choice_id = 6: # select 6 to exit the system print 'exit sucess' sys. exit () else: continue

 

Iv. logon Module
[Root @ localhost shop] # more login. py #! /Usr/bin/evn python #-*-coding: UTF-8-*-login Login f=file('user.txt ', 'R ') user_id_list = [] user_pwd_list = [] # Read the user name and save it to the user_id_list list # Read the user password and save it to user_pwd_list for line in f. readlines (): if '#' in line. split () [0]: continue else: user_id_list.append (line. split () [0]) user_pwd_list.append (line. split () [2]) f. close () # define the function to determine whether the user's user name and password are correct def login (user_id, pwd): if user_id in user_id_list: if pwd in user_pwd_list: return True else: print ('pwd error') else: print ('user _ id error ')

 

V. Implementation of the shopping module
[Root @ localhost shop] # more shop. py #! /Usr/bin/evn python #-*-coding: UTF-8-*-# shopping deduction function # modify (deduct) by reading the file and saving it to the list) and then save it to the file for implementation # The withdrawal module is similar to this process # mainly used: file read/write, character cutting, list processing defshop (user_id, commodity_id, commodity_quantity ): # define commodity_id_list and price_list to save commodity_id commodity_id_list = [] price_list = [] Comment ', 'R') for line in file_comm.readlines (): if' # 'in line: # simple File Processing: pass else: commodity_id_list.append (line. split () [0]) price_list.append (line. split () [2]) file_comm.close () price = ''for commodity_item in commodity_id_list: if str (commodity_id) = (commodity_item): price = price_list [partition (commodity_item)] # print price break if price = '': print 'select the product does not exist 'Return file_comm.close () # Read the User File file_user1_file('user.txt', 'R ') # defile user_list to save user infomation user_list = [] for user_line in file_user.readlines (): equals (user_line) if user_line.split () [0] = user_id: user_list [user_list.index (user_line)] = user_line.split () [0] + '\ t' + user_line.split () [1] +' \ t' + user_line.split () [2] + '\ t' + str (int (user_line.split () [3])-int (price) * int (commodity_quantity) +' \ n' file_user.close () # Read the product file file_comm = file('commodity.txt ', 'R') comm_list = [] for comm_line in file_comm.readlines (): comm_list.append (comm_line) # The remaining amount of the product is not determined () [0] = commodity_id: comm_list [comm_list.index (comm_line)] = comm_line.split () [0] + '\ t' + comm_line.split () [1] + '\ t' + comm_line.split () [2] +' \ t' + str (int (comm_line.split () [3])-int (commodity_quantity )) + '\ n' file_comm.close () print 'shopping success' # Write the user file to file_user1_file('user.txt', 'w') file_user.write (''. join (user_list) file_user.close () # Write the product file to file_comm1_file('commodity.txt ', 'w') file_comm.write (''. join (comm_list) file_comm.close () def comm_print (): file_comm1_file('commodity.txt ', 'R') print 'id \ t name \ t price \ t quantity' for line in file_comm.readlines (): if '#' not in line: print line, file_comm.close ()

 

Vi. Withdrawal Module
[Root @ localhost shop] # more withdraw. py #! /Usr/bin/evn python #-*-coding: UTF-8-*-# import the pickle module import pickleimport time # withdrawal Module

 

# Define the withdrawal function. The parameters are user_id (User Name) and amount (Withdrawal amount ).
def withdraw(user_id,amount):       f_user=file('user.txt','r')       user_list=[]       for user_item in f_user.readlines():                user_list.append(user_item)                ifuser_id==user_item.split()[0]:                        ifint(user_item.split()[3])-int(amount) >=0:

 

# Determine whether the user amount is sufficient.
User_list [user_list.index (user_item)] = user_item.split () [0] + '\ t' + user_item.split () [1] +' \ t' + user_item.split () [2] + '\ t' + str (int (user_item.split () [3])-int (amount) +' \ n' withdraw_log (user_id, amount) print 'withdrawal successful, withdrawal amount: % s' % amount print 'current balance:', str (int (user_item.split () [3])-int (amount )) return 'true' else: print 'the balance is insufficient. withdrawal failed. 'print' current balance: ', str (int (user_item.split () [3]) return 'false' f_user.close () f_user=file('user.txt ', 'w') f_user.write (''. join (user_list) f_user.close ()

 

# Define the withdraw_log function to save the deposit log. Parameters user_id (username) and amount (Withdrawal amount) # simple usage of the pickle module and simple dictionary usage are referenced here
Def withdraw_log (user_id, amount): log_dic ={} ISOTIMEFORMAT = '% Y-% m-% d % X 'new_log = (user_id, 'withdrawal', amount, time. strftime (ISOTIMEFORMAT, time. localtime () log_file = file ('withdraw _ log. pkl ', 'R') log_dic = pickle. load (log_file) log_file.close () # modify the read dictionary as needed if log_dic.has_key (user_id): log_dic [user_id]. append (new_log) else: log_dic [user_id] = [new_log] # Dumping the modified dictionary to the file withdraw_log log_file = file ('withdraw _ log. pkl ', 'w') pickle. dump (log_dic, log_file) log_file.close ()

 

VII. query module
[root@localhost shop]# more query.py#!/usr/bin/evn python#-*- coding:utf-8 -*-import pickle

 

# Only the withdrawal log query function is implemented here, mainly through the pickle function.
Def q_withdraw_log (user_id): withdraw_log ={} f_withdraw_log = file ('withdraw _ log. pkl ', 'R') withdraw_log = pickle. load (f_withdraw_log) # print withdraw_log partition () if partition (user_id): print 'user _ id \ t class \ t amount \ t time 'for withdraw_log_item inwithdraw_log [user_id]: printuser_id, '\ t', withdraw_log_item [1],' \ t', withdraw_log_item [2], '\ t', withdraw_log_item [3]

 

8. Summary This article is only used to learn the basic practice of python.

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.