Python学习笔记 4

来源:互联网 发布:局域网协作软件 编辑:程序博客网 时间:2024/05/25 21:34

1. 学习笔记

1.1 python 三元运算符: x= a if a >b else b

这里写图片描述

1.2 python 列表组合 zip(lst1,lst2)

这里写图片描述
注意,在python3中关于zip有以下解释:

zip Found at: builtinszip(iter1 [,iter2 [...]]) --> zip object    Return a zip object whose .__next__() method returns a tuple where    the i-th element comes from the i-th iterable argument.  The .__next__()    method continues until the shortest iterable in the argument sequence    is exhausted and then it raises StopIteration.

1.3 python 迭代 for i,j in enumerate(lst):

lst=['a','b','c','d','e']for i,j in enumerate(lst):    print(i,j)

运行结果:
这里写图片描述

1.4 Python数据类型转换
以下几个内置的函数可以执行数据类型之间的转换。这些函数返回一个新的对象,表示转换的值。
这里写图片描述

1.5 python 查看变量的数据类型:

>>> n=1>>> type(n)<type 'int'>>>> n="runoob">>> type(n)<type 'str'>>>> 

此外还可以用 isinstance 来判断:
isinstance(…)

isinstance(object, class-or-type-or-tuple) -> bool#传入的参数包含一个对象,类/类型/元组,返回的结果为一个bool值Return whether an object is an instance of a class or of a subclass thereof.With a type as second argument, return whether that is the object's type.The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut forisinstance(x, A) or isinstance(x, B) or ... (etc.).a = 111isinstance(a, int)True

isinstance 和 type 的区别在于:

>>> class A:...     pass... >>> class B(A):...     pass... >>> isinstance(A(), A)True>>> type(A()) == AFalse>>> isinstance(B(), A)True>>> type(B()) == A False

区别就是:

type()不会认为子类是一种父类类型。isinstance()会认为子类是一种父类类型。

注意:

不可变的数据类型:字符串、元组
可变的数据类型:列表

1.6 python内建函数(BIF)

min,max,sum,zip,absint,float,str,list,tuple,bool

函数实质上是一个变量;,可以将函数赋值给变量然后通过变量来调用

In [9]: lOut[9]: [1, 2, 3, 4]In [10]: maxlist=maxIn [11]: maxlist(l)Out[11]: 4

1.7 python 函数定义以及基本用法:
函数的定义:

def 函数名([形式参数]):    函数体         # 函数要执行的程序    return 返回值  # 如果没有return返回,默认返回值为None;

调用:

函数名([实参])

注意:有返回值 的函数,必须print(fun()),可以打印出返回值;

函数的返回值

  • 在函数中,一旦遇到return关键字,函数就执行结束;
  • 函数返回值只能返回一个,如果想间接返回多个值,返回值实际是一个元组;

函数的参数传值

必选参数:形参与实参的个数必须相同,否则直接报错;默认参数:在定义函数时,给形参一个默认值;可变参数:传入的参数个数是可变的,可以是1-n个,也可以是0个;一般实参中用*args来表示可变参数;    args接收的是一个元组(tuple),例如以下:
def func(*arg):    print len(arg)    for i in arg:        print ifunc(1,2,3,4)

这里写图片描述

1.8 python 字典
字典的特性

  • 字典是可变数据类型;可使用len(d)内置函数,计算字典的长度;
  • 字典是无序的,与序列(str,list,tuple)不同的是,不支持索引,切片,连接与重复。只能通过key值获取对应的value值;
  • 字典支持异构,支持嵌套;

python字典的一些方法:

dict.clear  (清空字典)dict.get(查询是否存在某个key) dict.iteritems   dict.keys        dict.setdefault  dict.viewitems   dict.copy (拷贝字典,id会改变)  dict.has_key     dict.iterkeys   dict.pop (根据key删除值)      dict.update   (更新字典,往字典里添加元素)  dict.viewkeys    dict.fromkeys   dict.items      dict.itervalues dict.popitem (随机删除)  dict.values     dict.viewvaluesdel(dict['key'])(删除指定的key)  del(dict)(删除字典)

字典的修改
dict[‘key’]=’value’

In [52]: lst=['ha','hi','he','halo']In [53]: dict = dict.fromkeys(lst)In [54]: dictOut[54]: {'ha': None, 'halo': None, 'he': None, 'hi': None}In [55]: dict = dict.fromkeys(lst,100)In [56]: dictOut[56]: {'ha': 100, 'halo': 100, 'he': 100, 'hi': 100}In [57]: 

字典支持异构,嵌套
d = {

"172.25.254.1":    {    "user":"root",    "password":"westos",    "command":"hostname"    },"172.25.254.2":    {    "user":"westos",    "password":"westos1",    "command":"hostname"    }

}

2. 编程练习:

2.1 实现一个简单的用户管理系统,有用户的注册、登录、退出、注销、查看,并且设置一定的用户权限。

示例代码如下:

#!/usr/bin/env python#coding:utf-8'''file:userLogin.pydate:8/29/17 4:52 PMauthor:lockeyemail:lockey@123.comdesc:'''def userManage():    welcome="""        Welcome to user manage system                    menu             (A|a) :Add a user             (D|d) :Delete a user             (V|v) :View user information             (I|i) :Login             (O|o) :Logout              (Q|q) :Quit    """    print welcome    goon = True    userLogin = False    userName = ''    userDict={}#'admin':{'password':'admin','level':'admin'}}    userAttempt = 0    faileUser =''    while goon:        userInput = raw_input('Please input your operation: ')        if userInput in 'aA':            username = raw_input('Please input username: ')            if userDict.get(username):                print 'User {} exist!'.format(username)                continue            password = raw_input('Please input password: ')            userinfo={}            userinfo.setdefault('password',password)            if username == 'admin':                userinfo.setdefault('level', 'admin')            else:                userinfo.setdefault('level', 'user')            userDict.setdefault(username,userinfo)        elif userInput in 'dD':            username = raw_input('Please input username: ')            if userDict.get(username) and userDict[username]['level'] != 'admin':                userDict.pop(username)            else:                print 'User not exist or can not be deleted(admin)!'        elif userInput in 'vV':            if userLogin == True and userDict[userName]['level'] == 'admin':                print userDict            else:                print 'Only logged user with level admin can view!'        elif userInput in 'iI':            if userName != '':                print 'User {} is still logged in, please logout first!'.format(userName)                continue            username = raw_input('Please input username: ')            if userAttempt >= 3 and username == faileUser:                print 'User {} has tried 3 times, please login later!'.format(userName)                continue            if not userDict.get(username):                print 'Username not exist!'                continue            password = raw_input('Please input password: ')            if password == userDict[username]['password']:                print 'Login Success!'                userAttempt = 0                userLogin = True                userName = username            else:                userAttempt += 1                faileUser = username                print 'Username or password not correct!'        elif userInput in 'oO':            print 'User {} logged out!'.format(userName)            userLogin = False            userName = ''        elif userInput in 'qQ':            goon = False        else:            print 'Unknown opetion, try again!'    print 'System exited!'userManage()

运行结果:

/usr/bin/python2.7 /root/PycharmProjects/python-lockey/userLogin.py        Welcome to user manage system                    menu             (A|a) :Add a user             (D|d) :Delete a user             (V|v) :View user information             (I|i) :Login             (O|o) :Logout              (Q|q) :QuitPlease input your operation: aPlease input username: adminPlease input password: adminPlease input your operation: vOnly logged user with level admin can view!Please input your operation: iPlease input username: adminPlease input password: adminLogin Success!Please input your operation: v{'admin': {'password': 'admin', 'level': 'admin'}}Please input your operation: dPlease input username: adminUser not exist or can not be deleted(admin)!Please input your operation: aPlease input username: haloPlease input password: haloPlease input your operation: v{'admin': {'password': 'admin', 'level': 'admin'}, 'halo': {'password': 'halo', 'level': 'user'}}Please input your operation: dPlease input username: haloPlease input your operation: v{'admin': {'password': 'admin', 'level': 'admin'}}Please input your operation: oUser admin logged out!Please input your operation: iPlease input username: haloUsername not exist!Please input your operation: qSystem exited!Process finished with exit code 0
原创粉丝点击