博客
关于我
【python 2】python 进阶
阅读量:158 次
发布时间:2019-02-28

本文共 9289 字,大约阅读时间需要 30 分钟。

函数

函数是编程中最基本的逻辑单元,可以通过函数名调用执行其内部代码。函数可以接受参数,处理数据并返回结果。

函数的参数

函数定义时可以指定参数,调用时需要提供对应的实参。例如:

import randomdef generate_random(number):    for i in range(number):        ran = random.randint()        print(ran)print(generate_random)

调用时:

generate_random(3)

输出:

>>>765>>>

练习 1:封装一个用户登录函数

定义一个登陆函数,参数是 username, password,函数体:判断参数传过来的 usernamepassword 是否正确,如果正确则登陆成功,否则登陆失败。

def login(username, password):    uname = 'admin123'    pword = '112233'    for i in range(3):        if username == uname:            print('登陆成功!')            break        else:            print('用户名或密码不匹配,登陆失败!')            username = input('请输入用户名:')            password = input('请输入密码:')    else:        print('超过三次错误,用户锁定!')

调用:

username = input('请输入用户名:')password = input('请输入密码:')login(username, password)

输出:

请输入用户名: admin123请输入密码: 112233登陆成功!

练习 2:封装一个求最大值的函数

定义一个求最大值的函数。

def max(iterable):    max_val = iterable[0]    for i in iterable:        if i > max_val:            max_val = i    print('最大值是:', max_val)

调用:

list1 = [3,6,3,2,7]max(list1)

输出:

最大值是: 7

判断是不是 list、tuple 等类型:isinstance()

isinstance(list1, list)

输出:

True

练习3:模拟 enumerate

枚举序号并保存到列表中。

s = [1,3,5,7,9]for i in s:    print(i)print('-----------------')for index, value in enumerate(s):    print(index, value)print('-----------------')list1 = []index = 0for i in s:    t1 = (index, i)    list1.append(t1)    index += 1print(list1)print('-----------------')for index, value in list1:    print(index, value)

输出:

13579-----------------0 11 32 53 74 9-----------------[(0, 1), (1, 3), (2, 5), (3, 7), (4, 9)]-----------------0 11 32 53 74 9

列表可变,字符串不可变

list1 = [1,2,3,4]list2 = list1list1.remove(3)print(list2)

输出:

[1, 2, 4]
s1 = 'abc's2 = s1print(s2)

输出:

abc

可变参数的定义方式

使用 *args 定义可变参数。

def add(*args):    print(args)add(1,)add(1,2)

输出:

()(1,)(1, 2)

可变参数必须放在不可变参数的后面。

def add(name, *args):    print(name, args)add('aa', 1,2,3)

输出:

aa (1, 2, 3)

默认值

函数参数可以设置默认值。

def add(a, b=10):    result = a + b    print(result)add(3)add(4,7)

输出:

1311

打印每位同学的姓名和年龄

students = {    '001': ('王俊凯', 20),    '002': ('易烊千玺', 19),    '003': ('王源', 19)}def print_boy(person):    if isinstance(person, dict):        for name, age in person.values():            print('{}的年龄是: {}'.format(name, age))print_boy(students)

输出:

王俊凯的年龄是: 20易烊千玺的年龄是: 19王源的年龄是: 19

关键字参数

使用 **kwargs 接收关键字参数。

def func(**kwargs):    print(kwargs)func(a=1, b=2, c=3)

输出:

{'a': 1, 'b': 2, 'c': 3}

字典传入时可以拆包。

dict = {    '001': 'python',    '002': 'java',    '003': 'c++',    '004': 'go'}def func1(**kwargs):    print(kwargs)func1(**dict)

输出:

{'001': 'python', '002': 'java', '003': 'c++', '004': 'go'}

使用的时候

调用时用 **dicts 拆包。

def bb(a, b, *c, **d):    print(a, b, c, d)bb(1,2)bb(1,2,3,4)bb(1,2, x=10, y=20)bb(1,2,3, x=100)

输出:

1 2 () {  }1 2 (3, 4) {  }1 2 () { 'x': 10, 'y': 20}1 2 (3,) { 'x': 100}

函数返回值

使用 return 返回函数运算结果。

def add(a, b):    result = a + b    return resultresult = add(1,2)print(result)

输出:

3

练习 1:加入购物车

判断用户是否登录,成功则加入购物车。

islogin = Falsedef add_shoppingcart(goodsName):    global islogin    if islogin:        if goodsName:            print('成功加入购物车!')        else:            print('登陆成功,没有选中任何商品!')    else:        answer = input('用户没有登陆,是否登陆?(y/n)')        if answer == 'y':            username = input('请输入用户名:')            password = input('请输入密码:')            islogin = login(username, password)        else:            print('很遗憾,不能添加任何商品!')def login(username, password):    if username == '李佳琪' and password == '123456':        return True    else:        print('用户名或密码有误,请重新输入:')        return False

调用:

username = input('请输入用户名:')password = input('请输入密码:')islogin = login(username, password)add_shoppingcart('阿玛尼唇釉')

输出:

请输入用户名: 李佳琪请输入密码: 123456用户名或密码有误,请重新输入:用户没有登陆,是否登陆?(y/n) y请输入用户名: 李佳琪请输入密码: 123456登陆成功!

验证验证码

def generate_checkcode(n):    s = '0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM'    code = ''    for i in range(n):        ran = random.randint(0, len(s)-1)        code += s[ran]    return codedef login():    username = input('输入用户名:')    password = input('请输入密码:')    code = generate_checkcode(5)    print('验证码是:', code)    code1 = input('请输入验证码:')    if code.lower() == code1.lower():        if username == 'lijiaqi' and password == '123456':            print('用户登陆成功!')        else:            print('用户名或密码有误!')    else:        print('验证码输入错误')login()

输出:

输入用户名: lijiaqi请输入密码: 123456验证码是: Wavvv请输入验证码: Wavvv用户登陆成功!

全局变量和局部变量

全局变量在函数外定义,所有函数都可以访问。局部变量只能在函数内部改变。要修改全局变量,必须在函数开头加 global 关键字。可变类型的全局变量可以直接修改,不需要 global

修改全局变量

a = 100def func():    global a    a += 10func()print(a)

输出:

110

局部变量

def func3():    p = 100    list1 = [3,1,2,4]    def inner_func():        for index in range(len(list1)):            list1[index] +=5        print(list1)    inner_func()func3()

输出:

[8, 6, 7, 9]

内部函数

内部函数可以访问外部函数的变量,但不能修改外部函数的不可变变量,除非在内部函数中加 nonlocal。要修改全局变量,内部函数也需要加 global

def func():    a = 100    list1 = [3,1,2,4]    def inner_func():        for index, value in enumerate(list1):            list1[index] = value + 5        print(list1)    inner_func()func()

输出:

[8, 6, 7, 9]

闭包

闭包是将内部函数通过 return 返回,外部函数可以调用内部函数。

def func():    a = 100    def inner_func():        b = 90        print(a, b)    return inner_funca = func()a()

输出:

100 90

匿名函数

使用 lambda 定义匿名函数。

s = lambda a, b: a + bresult = s(1,2)print(result)

输出:

3

文件操作

模式

文件操作使用 open 函数,常用模式包括 rwrbwba

读取文件

with open('file.txt', 'r') as stream:    container = stream.read()print(container)

逐行读取:

with open('file.txt', 'r') as stream:    while True:        line = stream.readline()        if not line:            break        print(line)

读取所有行:

stream = open('file.txt', 'r')lines = stream.readlines()print(lines)

读取二进制文件:

with open('image.jpg', 'rb') as stream:    container = stream.read()

写文件

with open('file.txt', 'w') as stream:    stream.write('hello xiao ming!')

写入多行:

with open('file.txt', 'w') as stream:    stream.write('hello xiao hua!\n')    stream.writelines(['hello denny!\n', 'hello xiao hong!\n'])

追加模式:

with open('file.txt', 'a') as stream:    stream.write('hello jenny!\n')

文件复制

with open('image.jpg', 'rb') as stream:    container = stream.read()with open('image1.jpg', 'wb') as wstream:    wstream.write(container)print('文件复制完成!')

os 模块

操作系统模块提供文件和目录操作函数。

路径操作

import ospath = os.path.dirname(__file__)path1 = os.path.join(path, 'image2.jpg')with open(path1, 'wb') as wstream:    with open('image.jpg', 'rb') as stream:        container = stream.read()        wstream.write(container)print('文件复制完成!')

文件操作

os.remove(r'C:\Users\man.wang\python\python\p1\image.jpg')

目录操作

os.mkdir('p3')os.rmdir('p3')os.removedirs('p3')os.chdir(r'C:\Users\man.wang\python\python\p2')print(os.getcwd())

异常

异常处理使用 tryexceptfinally

抛出异常

def register():    username = input('请输入用户名:')    if len(username) < 6:        raise Exception('用户名长度必须6位以上!')    else:        print('输入的用户名是:', username)register()

输出:

输入第一个数字: 2输入第二个数字: w必须输入数字!

异常处理

def func():    try:        n1 = int(input('输入第一个数字:'))        n2 = int(input('输入第二个数字:'))        oper = input('请输入运算符号:(+-*/)')        result = 0        if oper == '+':            result = n1 + n2        elif oper == '-':            result = n1 - n2        elif oper == '*':            result = n1 * n2        elif oper == '/':            result = n1 / n2        else:            print('符号错误!')        print('结果为:', result)    except ZeroDivisionError:        print('除数不能为0!')    except ValueError:        print('必须输入数字!')    finally:        print('执行完毕')func()

输出:

输入第一个数字: 1输入第二个数字: 0请输入运算符号:(+-*/)除数不能为 0!

推导式

列表推导式可以从旧列表推导出新列表。

列表推导式

names = ['tom', 'lily', 'jack', 'json', 'bob']result = [name for name in names if len(name) > 3]print(result)

输出:

['lily', 'jack', 'json']

集合推导式

list1 = [1,2,3,4,5,6,3,1,2,3]set1 = {x for x in list1}print(set1)set2 = {x+1 for x in list1 if x > 3}print(set2)

输出:

{1, 2, 3, 4, 5, 6}{5, 6, 7}

字典推导式

dict1 = {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'C'}new_dict = {value: key for key, value in dict1.items()}print(new_dict)

输出:

{'A': 'a', 'B': 'b', 'C': 'd'}

生成器

生成器是一边推导一边返回数据,节省内存。

生成器定义

g = (x * 3 for x in range(20))print(next(g))print(next(g))print(next(g))

输出:

036

生成器应用

def func():    n = 0    while True:        n += 1        yield ng = func()print(next(g))print(next(g))print(next(g))

输出:

123

斐波那契数列

def fib(length):    a, b = 0, 1    for _ in range(length):        yield b        a, b = b, a + bg = fib(8)print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))print(next(g))

输出:

12358132134

迭代器

迭代器是一种可以被逐次访问的对象,包括生成器和列表等。

迭代器转换

list1 = [1,2,3]iterator = iter(list1)print(next(iterator))print(next(iterator))

输出:

12

生成器也是迭代器

g = (x * 3 for x in range(20))print(isinstance(g, Iterable))print(next(g))

输出:

True0

生成器的应用

def task1(n):    for i in range(n):        print(f'正在搬第{i}块砖')        yield Nonedef task2(n):    for i in range(n):        print(f'正在听第{i}首歌')        yield Noneg1 = task1(3)g2 = task2(3)while True:    try:        g1.__next__()        g2.__next__()    except StopIteration:        break

输出:

正在搬第0块砖正在听第0首歌正在搬第1块砖正在听第1首歌正在搬第2块砖正在听第2首歌

迭代器类型

from collections import Iterableisinstance(list, Iterable)isinstance((1,2,3), Iterable)isinstance('abc', Iterable)isinstance(generator, Iterable)

输出:

TrueTrueFalseTrue

迭代器方法

iterator = iter([1,2,3])print(type(iterator))print(next(iterator))print(next(iterator))

输出:

12

转载地址:http://xpqd.baihongyu.com/

你可能感兴趣的文章
nodejs端口被占用原因及解决方案
查看>>
Nodejs简介以及Windows上安装Nodejs
查看>>
nodejs系列之express
查看>>
nodejs系列之Koa2
查看>>
Nodejs连接mysql
查看>>
nodejs连接mysql
查看>>
NodeJs连接Oracle数据库
查看>>
nodejs配置express服务器,运行自动打开浏览器
查看>>
Nodemon 深入解析与使用
查看>>
node不是内部命令时配置node环境变量
查看>>
node中fs模块之文件操作
查看>>
Node中同步与异步的方式读取文件
查看>>
Node中的Http模块和Url模块的使用
查看>>
Node中自启动工具supervisor的使用
查看>>
Node入门之创建第一个HelloNode
查看>>
node全局对象 文件系统
查看>>
Node出错导致运行崩溃的解决方案
查看>>
Node响应中文时解决乱码问题
查看>>
node基础(二)_模块以及处理乱码问题
查看>>
node安装及配置之windows版
查看>>