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()