The first day after reading the Python teaching video, immediately wrote a short code, the middle encountered some problems, want to immediately record down, share with you.
Writing the Login interface
- Enter User name password
- Show welcome message after successful authentication
- Three-time error after locking
1. Use Dict to read and write files (because you want to use the Key,value structure):
1) write to the file using the Dict format:
UserFile =Open"C:/users/administrator/pycharmprojects/untitled/day1/userdata.ini","W")
temp = {}
temp[' Name '] = "Shelly"
temp[ ' passwd '] = Userfile.write (str (temp) + \n")
Temp[ ' name '] = " Nancy "
Temp[ ' passwd '] = " 234567 "
Userfile.write (str (temp) + \n Userfile.close ()
2) read from the file using the Dict format:
UserFile =Open"C:/users/administrator/pycharmprojects/untitled/day1/userdata.ini", lines = Userfile.readlines ()
for line in lines:
data = eval (line)
Verifydata = false
if Data[ ' name '] = = Username and data[ ' passwd '] = = passwd:
print (" Welcome {_name} login ". Format (_name = username))
Userfile.close ()
exit () /span>
1. Read by line:
I will be locked in the name of the file, the line, the results in matching the user input name, whether the user name is locked, read the file by line, to match, found that the value read out has a newline character, resulting in a problem with the judgment.
The values that are read directly on the line will change to: shelly\n
Workaround:
data = Line.split () [0]
The data read will then be translated into the desired: Shelly.
#coding =utf-8
Import OS
Count =3
While Count >0:
Username =Input"Please input username:")
LockFile =Open"C:/users/administrator/pycharmprojects/untitled/day1/locklist.cfg","R")
lines = Lockfile.readlines ()
For lineIn lines:
If username = = Line.split () [0]:
Print"Account is locked!!!")
Exit ();
Lockfile.close ()
passwd =Input"Please input your Passworld:")
UserFile =Open"C:/users/administrator/pycharmprojects/untitled/day1/userdata.ini","R")
lines = Userfile.readlines ()
For lineIn lines:
data =Eval (line)
Verifydata =False
If data[' name '] = = Usernameand data[' passwd '] = = passwd:
Print"Welcome {_name} login". Format (_name = username))
Userfile.close ()
Exit ()
Count-=1
If Count > 0:
print ( "Your username or Passworld is wrong!only has {_count} chance". Format (_count = count))
else:
LockFile = open (" C:/users/administrator/pycharmprojects/untitled/day1/lockliat.cfg ", Lockfile.write (Username+" \n")
Lockfile.close ()
print (" Sorry,you has no chance! ")
Userfile.close ()
Learn python for the first time---write the login interface (about while, if, for statements, Dict, and read and write files)