Python学习笔记 4

1. 学习笔记

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

这里写图片描述

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

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

zip Found at: builtins
zip(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 for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
a = 111
isinstance(a, int)
True

isinstance 和 type 的区别在于:

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

区别就是:

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

注意:

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

1.6 python内建函数(BIF)

min,max,sum,zip,abs
int,float,str,list,tuple,bool

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

In [9]: l
Out[9]: [1, 2, 3, 4]

In [10]: maxlist=max

In [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 i
func(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.viewvalues
del(dict['key'])(删除指定的key)  
del(dict)(删除字典)

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

In [52]: lst=['ha','hi','he','halo']

In [53]: dict = dict.fromkeys(lst)

In [54]: dict
Out[54]: {'ha': None, 'halo': None, 'he': None, 'hi': None}

In [55]: dict = dict.fromkeys(lst,100)

In [56]: dict
Out[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.py
date:8/29/17 4:52 PM
author:lockey
email:lockey@123.com
desc:

'''

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) :Quit

Please input your operation: a
Please input username: admin
Please input password: admin
Please input your operation: v
Only logged user with level admin can view!
Please input your operation: i
Please input username: admin
Please input password: admin
Login Success!
Please input your operation: v
{'admin': {'password': 'admin', 'level': 'admin'}}
Please input your operation: d
Please input username: admin
User not exist or can not be deleted(admin)!
Please input your operation: a
Please input username: halo
Please input password: halo
Please input your operation: v
{'admin': {'password': 'admin', 'level': 'admin'}, 'halo': {'password': 'halo', 'level': 'user'}}
Please input your operation: d
Please input username: halo
Please input your operation: v
{'admin': {'password': 'admin', 'level': 'admin'}}
Please input your operation: o
User admin logged out!
Please input your operation: i
Please input username: halo
Username not exist!
Please input your operation: q
System exited!

Process finished with exit code 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值