python學習筆記-Day1

  1. python 2到python 3的變化

    a. 主要整合了模塊,去重複模塊

    b. 修改了字符集,不用特別指明字符集即可使用中文


  2. python 2版本使用中文時,需要指定字符集

#_*_coding:utf-8_*_


3. 獲取用戶輸入

name = input("What is your name?")
print("Hello " + name )


4. 字符串的格式化輸出

name = "alex"
print "i am %s " % name

PS: 字符串是 %s;整數 %d;浮點數%f


字符串移除空白

>>> test = ' a test text '
>>> test.strip()
'a test text'


5. 列表的基本操作

列表分片

>>> number = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> number[3:6]
[4, 5, 6]

分片操作的實現需要提供兩個索引作爲邊界,第一個索引的元素是包含在分片內的,而第二個則不包含在分片內



作業:

1.編寫登陸接口

  • 輸入用戶名密碼

  • 認證成功後顯示歡迎信息

  • 輸錯三次後鎖定

#!/usr/bin/env python
import sys, os
pwd = sys.path[0]
auth_file = os.path.join(pwd, "Auth.txt")
userdict={}

def check_exist():
    '''
    檢查文件是否存在!
    :return:
    '''
    if os.path.exists(auth_file) and os.path.isfile(auth_file):
        if os.path.getsize(auth_file) == 0:
            print("%s is empty, can't auth..." % auth_file)
            sys.exit(0)
    else:
        print("%s: No such file! Please check..." % auth_file)
        sys.exit(0)

def loding_dict():
    # 讀取文件
    with open(auth_file, 'r') as f:
        Auth = f.readlines()
    # 讀入文件內容到字典
    for line in Auth:
        user_detail = line.strip('\n').split(':')
        auth_user = user_detail[0]
        auth_passwd = user_detail[1]
        auth_check = user_detail[2]
        userdict[auth_user] = {'user': auth_user, 'password': auth_passwd, "check": auth_check}

def login():
    user = input("please input username: ")
    passwd = input("please input password: ")
    if user not in userdict.keys():
        print("no such user ..")
    elif int(userdict[user]['check']) < 3 :
        # 密碼正確顯示歡迎,密碼錯誤修改auth.txt的check字段
        if passwd == userdict[user]['password']:
            print('welcome %s...' % user)
            sys.exit(0)
        else:
            print('password is invalid...')
            userdict[user]['check'] = int(userdict[user]['check']) + 1
            file = open(auth_file, "r+")
            for item in userdict.values():
                trace_text = ':'.join([item['user'], item['password'], str(item['check'])+'\n'])
                file.write(trace_text)
            file.close()
    else:
        print('user:%s is lock..' % user)

def main():
    check_exist()
    loding_dict()
    while True:
        login()



if __name__ == "__main__":
    main()


2. 多級菜單

  • 三級菜單

  • 可依次選擇進入各子菜單

  • 所需新知識點:列表、字典

#!/usr/bin/env python
import sys

dic = {
    '北京':{
        '朝陽區':{
            '朝陽公園':[
                '公園前門',
                '公園後門'
            ],
            '團結湖':[
                '大湖',
                '小湖'
            ]
        },
        '海淀區':{
            '國家圖書館':[
                '一層',
                '二層'
            ],
            '公主墳':[
                'x公主',
                'y公主'
            ]
        },
        '豐臺區':{
            '嶽各莊':[
                '莊壹',
                '莊貳'
            ],
            '盧溝橋':[
                '前半段',
                '後半段'
            ]
        },
        '通州區':{
            '運河奧體':[
                '運河',
                '奧體'
            ],
            '六環':[
                '五環外',
                '七環內'
            ]
        }
    },
    '上海':{
        '浦東新區':{
            '金橋':[
                'xxx',
                'yyy'
            ],
            '復旦大學':[
                '東門',
                '西門'
            ]
        },
        '嘉定區':{
            '上海國際賽車場':[
                '賽道',
                '觀衆區'
            ],
            '同濟大學':[
                '南門',
                '北門'
            ]
        },
        '虹口區':{
            '廣中路':[
                '路東',
                '路西'
            ],
            '曲陽地區':[
                '區1',
                '區2'
            ]
        },
        '普陀區':{
            '金沙江路':[
                'qqq',
                'sss'
            ],
            '石泉路':[
                '111',
                '222'
            ]
        }
    },
}
def list_print(list):
    count = 0
    for i in list:
        count+=1
        print('%s. %s' % (count,i))

def zero():
    list = []
    tmp = dic.keys()
    for i in tmp:
        list.append(i)
    #return list
    while True:
        list_print(list)
        user_input = input('(q/Q:退出)==> ')
        if user_input.isdigit():
            user_input = int(user_input)
            if user_input <= len(list):
                a_city = list[user_input - 1]
                one(a_city)
            else:
                print("超出了範圍...")
                sys.exit(0)
        elif user_input == 'q' or user_input == 'Q':
            print("即將退出...")
            sys.exit(0)
        elif user_input == '':
            pass
        else:
            print("無效的參數...")
            sys.exit(1)

def one(a_city):
    list = []
    tmp = dic[a_city].keys()
    for i in tmp:
        list.append(i)
    #return  list
    while True:
        list_print(list)
        user_input = input("(q/Q:退出,b/B:返回上一層)==> ")
        if user_input.isdigit():
            user_input = int(user_input)
            if user_input <= len(list):
                area = list[user_input - 1]
                two(a_city, area)
            else:
                print("超出了範圍...")
                sys.exit(0)
        elif user_input == 'q' or user_input == 'Q':
            print("即將退出...")
            sys.exit(0)
        elif user_input == 'b' or user_input == 'B':
            break
        elif user_input == '':
            pass
        else:
            print("無效的參數...")
            sys.exit(1)

def two(a_city, area):
    list = []
    tmp = dic[a_city][area].keys()
    for i in tmp:
        list.append(i)
    #return  list
    while True:
        list_print(list)
        user_input = input("(q/Q:退出,b/B:返回上一層)==> ")
        if user_input.isdigit():
            user_input = int(user_input)
            if user_input <= len(list):
                some_where = list[user_input - 1]
                three(a_city, area, some_where)
            else:
                print("超出了範圍...")
                sys.exit(0)
        elif user_input == 'q' or user_input == 'Q':
            print("即將退出...")
            sys.exit(0)
        elif user_input == 'b' or user_input == 'B':
            break
        elif user_input == '':
            pass
        else:
            print("無效的參數...")
            sys.exit(1)

def three(a_city, area, some_where):
    list = dic[a_city][area][some_where]
    #return  list
    while True:
        list_print(list)
        user_input = input("(q/Q:退出,b/B:返回上一層)==> ")
        if user_input == 'q' or user_input == 'Q':
            print("即將退出...")
            sys.exit(0)
        elif user_input == 'b' or user_input == 'B':
            break
        elif user_input == '':
            pass
        else:
            print("無效的參數...")
            sys.exit(1)

def main():
    zero()

if __name__ == '__main__':
    main()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章