python 基础(实例1——登陆小游戏)

一个简单的登陆小游戏,输入用户名和密码,如果和user_passwd.txt中内容匹配,则打印“welcome to login…”,如果三次输入错误则将该用户列入黑名单,无法再用该用户名登陆。

1.python 对.txt文件的操作

  a.python对文件的读取

1 with open('user_passwd.txt') as f:
2     lines = f.readlines()
3     for line in lines:
4         print(line)

  b.pyhton对文件的写入

1 with open('user_passwd.txt','a') as f:
2     f.write(str)

2.split() 函数

  当拿到文件的一行是往往需要对其进行切割才能得到我们想要的字段,split()函数会返回一个列表

  str.split(s,[number_1])[number_2]

  parameter s:切割点

  parameter number_1: 切割段数

  parameter number_2: 取切割后的列表的第number_2个元素

登陆小游戏代码实现

 1 flag = 0
 2 for i in range(3):
 3     if flag == 1:
 4         break
 5     username = input("name:")
 6     passwd = input("password:")
 7     with open('black_list.txt') as f:     #is username in black_list
 8         lines = f.readlines()
 9         for line in lines:
10             if username+'\n' == line:
11                 print("sorry, you are in black_list!")
12                 exit(0)      #exit
13     with open('user_passwd.txt') as f:        # not in black_list
14         lines = f.readlines()
15         for line in lines:
16             str_1 = line.split(',')[0]
18             str_2 = line.split(',')[1]
20             if username == str_1 and passwd + '\n' == str_2:
21                 print("welcome to login...")
22                 flag = 1
23                 break
24         else:
25             print("username or password is not correct!")
26     if i == 2 and flag == 0:       # write in black_list
27         with open('black_list.txt','a') as f:
28             f.write(username)
29             f.write('\n')

 

  

 

 

 

  

  

点赞