Python job 001: Simulated login system, python001

Source: Internet
Author: User

Python job 001: Simulated login system, python001

Learn python mark with old boys

Job Requirements and tips: Write the logon Interface

'''

Exercise Program: Write the logon Interface

1. Enter the user name and password

2. The welcome information is displayed after the authentication is successful.

3. Lock after three wrong attempts

Enter the user name three times and exit. the user will be locked when the user name is logged in again next time. The user lock information can be saved in the hard disk file to interact with the hard disk file.

You cannot use shell commands. You can only use Python's built-in file calling interfaces (you can add, delete, modify, and Query files). First, learn how to handle files.

4. the user name and password are read from the file. There is also a file to check the account lock.

'''

Job knowledge point:

Simulate the operations, condition statements, and loops of the main exercise files in the login System

1. str. strip ([chars]):

Delete all spaces at the front and back of the string. The chars parameter can be used to customize the characters to be deleted. Optional.

Input (). strip () can remove spaces when a user inputs to avoid unnecessary errors.

Usage:

Account = input ('Enter the account: '). strip ()

 

2. str. upper ()

Converts all lowercase letters in a string to uppercase letters.

Command = input ('Enter the command: '). strip ()

If command. upper () = 'A ':

Add_user (database)

This item is executed no matter whether the input command is A or.

3. dict. get (key)

Obtains the value corresponding to the key in the dictionary. If the key does not exist, None is returned,

If database. get (account) = None:

If the key does not exist, no error is reported.

Flowchart

Sample Code 1
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Author: "David J" # file not used, import sysusers_list = {"jdw": "123", "smz": "123"} locked_count = 0log_error_count = 0 # logon module while True: username = input ("please input your username :"). strip () password = input ("please input your password:") # determine whether the user name and password are the same if username in users_list.keys (): if password = users_list [username]: print ("Logon successful") sys. exit () else: log _ Error_count + = 1 if log_error_count <3: print ("the user name or password is incorrect. Please try again! ") Else: locked_count = 1 print (" retry more than three times, locked! ") Sys. exit () else: log_error_count + = 1 if log_error_count <3: print (" username error, please try again! ") Else: locked_count = 1 print (" retry more than three times, locked! ") Sys. exit ()
Sample Code 2
#! /Usr/bin/env python #-*-coding: UTF-8-*-# @ Author: "David J" # data file userpassword.txt, which is locked after three errors # dictionary and list difference: the list is ordered and accessed using indexes. The entries in the dictionary are accessed using keys # initialize the empty dictionary user_dict ={} # initialize the empty list, with an empty list, the program can add the element user_list = [] # The initial value of User Password error to this list is 0login_error_count = 0 # use while to start an unrestricted loop while True: # interactive input login username and password logon_name = input ("Pls input your username:") pass_word = input ("Pls input your password:") # Read user login data file Us ErPassword.txt '''userpassword.txt example jdw, 123456,0, 0 smz, 123456,0, 0 root, 123456,0, 0 cslc, 123456,0, 0''' users_data = comment', 'R ') # traverse open data cyclically, format the opened data, and save the formatted data to the created user_dict dictionary for user_data in users_data: # Use strip to remove the leading and trailing spaces in the user_data data row. user_list = user_data.strip () # Use commas to separate user_list, and re-save it to user_datas = user_list.split (',') # Replace the 0th digits in the user_datas data row Remove spaces and assign the new variable user_name = user_datas [0]. strip () # Remove the data (password) at the 1st locations in the user_datas data row, and then assign the new variable user_passwd = user_datas [1]. strip () # Remove the leading and trailing spaces, the new variable user_locked = user_datas [2]. strip () # Remove the data at the first position in the user_datas data row (that is, the number of wrong password input, assign the new variable user_error_count # convert the Data Type of user_datas [3] to int user_error_count = int (user_d Atas [3]. strip () # Save the previously defined variable information to the dictionary, and specify the key name for the previous value, that is, the relationship between the key and the value. The key name can start at will, it is recommended that you consider "easy to understand" # If the following key name line is lined up and down, it does not mean a syntax error, but the editor considers that the English spelling is not a correct word, script execution is not affected # according to the Python programming specifications, a space user_dict [user_name] = {'name': user_name, 'Password': user_passwd must be added after the comma and colon, 'locked': user_locked, 'errorcount': user_error_count} # Shut down the userpassword.txt file users_data.close () # determine whether the user account has been locked, match the username entered in the previous interactive interface with the username column saved in the dictionary # match the username entered in the previous interactive interface with the userl in the dictionary The ocked key is matched. if the key corresponding to the user name is 1, it is locked. log out and log on to if logon_name in user_dict.keys (): if user_dict [logon_name] ['locked'] = '1': print ("This user was locked, pls contact administrator! ") Break # match the username and password entered above with the username and password in the dictionary. If the password is successful, the system will be logged on, then exit if logon_name = user_dict [logon_name] ['name'] and pass_word = user_dict [logon_name] ['Password']: print ("Welcome to System! ") Break else: # If the user name is in the dictionary but the password is incorrect, add user_dict [logon_name] ['errorcount'] + = 1 # If the user name is entered correctly, if user_dict [logon_name] ['errorcount'] <3: print ("The password was wrong, pls try again, your have three chance! ") # Add and write new data to userpassword.txt, where errorcount increases with the number of failed attempts, three times are 2, namely, 2 write_data = open('UserPassword.txt ', 'W + ') # retrieve the value in the dictionary into _ user_value and traverse it cyclically for user_value in user_dict.values (): # Write Data user_list = [user_value ['name'], user_value ['Password'], str (user_value ['locked']) to the empty list defined at the beginning of the script. str (user_value ['errorcount'])] # format the data written to user_list and then assign it to users_list = ','. join (user_list) # convert us Data in ers_listis written into userpassword.txt, and newline write_data.write (users_list + '\ n') is carried out at the end of each row. # Close userpassword.txt write_data.close () else: # If the password is incorrect for more than three times, print ("You try three times, Account locked") # When the Output Account is locked, set the value of the locked key in the dictionary to 1, and change the value to 1, user_dict [logon_name] ['locked'] = 1 # after the account is Locked, the number of wrong passwords of the user is cleared, I understand that the lock attribute is 1 and the error count can be cleared. user_dict [logon_name] ['errorcount'] = 0 write_data = o Pen('UserPassword.txt ', 'W +') for user_value in user_dict.values (): user_list = [user_value ['name'], user_value ['Password'], str (user_value ['locked']), str (user_value ['errorcount'])] users_list = ','. join (user_list) write_data.write (users_list + '\ n') write_data.close () break else: # If the user name does not exist, print ("Pls ensure input currect account or password, you can try three times! ") # The value of the username that does not exist in Initialization is set to 0 at the beginning of the program. Here, we will add login_error_count + = 1 # if the number of nonexistent user attempts exceeds 3, the program is interrupted if login_error_count> 2: break

  

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.