代码改变世界

python基础01之流程控制

2016-10-17 16:23  山林骏  阅读(538)  评论(0)    收藏  举报

流程控制对于任何编程来说都是命根子!!!

初学python,就用一个在命令行模拟用户登录的小程序,来展示一下python的命根子吧!!!

各位看官,上眼!!!我要开始表演啦!!!

首先,来张流程图!

OK!流程图欣赏完毕,麻雀虽小,五脏俱全!这就是所有的要求!没有其他要求,再重申一遍,没有其他要求!这些要求对于像山林骏这样的初学者已经足够折腾的了!

开干!!!

 1 #!usr/bin/env python
 2 import sys
 3 retry_limit = 3
 4 retry_count = 0
 5 account_file = './accounts.txt'
 6 lock_file = './account_lock.txt'
 7 username=‘’
 8 
 9 while retry_count < retry_limit:
10     username = input('\033[32;1mUsername:\033[0m')
11     lock_check = open(lock_file)
12     for line in lock_check.readlines():
13         line=line.replace('\n','')
14         if username == line:
15             #print(username, line)
16             sys.exit('\033[31;1mUser %s is locked!\033[0m' %username)
17     password = input('\033[32;1mPassword:\033[0m')
18 
19     f = open(account_file)
20     match_flag = False
21     for line in f.readlines():
22         user,passwd = line.strip('\n').split()
23         if username == user and password == passwd:
24             print ('Match!',username)
25             match_flag = True
26     f.close()
27     if match_flag == False:
28         print ('User unmatched!')
29         retry_count +=1
30     else:
31         print ("Welcome !")
32         sys.exit()
33 else:
34     print ("Your account is locked!")
35     f = open(lock_file,'ab')
36     f.write(username)
37     f.close()

 

在上面的小程序里,涉及了python中的while/for/if 这三个最常用的流程控制法宝的基本语法及基本用法!

完美!

山林骏的第一个python就这么诞生了!

此刻响起了经久不息的掌声!