Java技术分享

傻瓜式学Python3——函数

2017-09-03  本文已影响425人  张少林同学
来自网络.jpg

前言:大周末的闲来无事,继续 Python3 的傻瓜式学习——函数。

函数,每个编程语言都有自己特定的函数表示方式,说直白点,就是把代码封装成一个方法,以做到整洁,方便重复调用的效果,这也是写程序中最经常干的事情。

基本定义

def+方法名: 方法体以四格缩进为准

def greet_user():
    """神奇的Hello World"""
    print('Hello World!')
greet_user()

结果自然是打印神奇的Hello World!

函数传参

def greet_user(userName):
    """打印参数"""
    print(userName)
greet_user('张少林')

结果:张少林

通过位置传递实际参数

调用函数时,按照参数的顺序传入实参,这和一般的函数调用一样,一旦顺序搞错,结果将会出错。

def describe_pet(animal_type,pet_name):
    print('\nI have a ' + animal_type + '.')
    print('My '+ animal_type + ' name is '+ pet_name.title()+ '.')

describe_pet('hamster','harry')

结果:

I have a hamster.
My hamster name is Harry.

通过关键字传递参数

当我们使用传统的按参数位置传递实参的时,需要注意传递的顺序,否则会出现不是我们所期待的结果,那么可以使用关键字传实参,指定传递的实参是存储在哪个形参中。

def describe_pet(animal_type,pet_name):
    print('\nI have a ' + animal_type + '.')
    print('My '+ animal_type + ' name is '+ pet_name.title()+ '.')

describe_pet(animal_type='hamster',pet_name='harry')

结果还是一样。

函数形参默认值

可以给函数形参赋予默认值,假如传入实参,则使用实参值,否则,使用默认值。注意:没有默认值的形参必须放在有默认值的形参前面,python会按照位置解读传递的参数值

def describe_pet(pet_name,animal_type = 'dog'):
    print('\nI have a ' + animal_type + '.')
    print('My '+ animal_type + ' name is '+ pet_name.title()+ '.')

describe_pet(pet_name='willie')

结果:

I have a dog.
My dog name is Willie.

显式传入实参:describe_pet(pet_name='harry',animal_type='hamster')
结果:

I have a hamster.
My hamster name is Harry.

函数返回值

用 return 关键字返回函数处理完逻辑返回的结果

def get_formatted_name(first_name,last_name):
    """返回姓名"""
    full_name = first_name+ ''+last_name
    return full_name

musician = get_formatted_name('jimi','hendrix')
print(musician)

结果为: jimihendrix

函数返回字典类型数据

def build_person(first_name,last_name):
    """返回包含人信息的字典数据"""
    person = {'first_name':first_name,'last_name':last_name}
    return person

person = build_person('张','少林')
print(person)

结果:{'first_name': '张', 'last_name': '少林'}

结合 while 循环使用函数

def get_formatted_name(first_name,last_name):
    """返回姓名"""
    full_name = first_name+ ''+last_name
    return full_name.title()

while True:
    print('\nPlease tell me your name:')
    print('(enter q at any time to quit)')
    
    f_name = input('First name: ')
    if f_name == 'q':
        break
        
    l_name = input('Last name: ')
    if l_name == 'q':
        break
    
    formatted_name = get_formatted_name(f_name,l_name)
    print('\nHello,' + formatted_name + '!')

传递列表参数

def greet_user(names):
    """传递列表"""
    for name in names:
        msg = 'Hello, '+ name.title()+'!'
        print(msg)

userNames = ['hannah','ty','margot']
greet_user(userNames)

传递任意数量实参

def 函数名(*形参) 使用*形参的形式,在调用函数的时,可以传入任意数量的实参,python 会自动处理实参,并生成一个元组。

def make_pizza(*toppings):
    """传递任意数量实参"""
    print(toppings)
    for topping in toppings:
        print(topping)

#传递一个参数
make_pizza('pepperoni')
#传递三个参数
make_pizza('mushrooms','green peppers','extra cheese')

结果:

('pepperoni',)
pepperoni
('mushrooms', 'green peppers', 'extra cheese')
mushrooms
green peppers
extra cheese

传递任意数量的 key-value

有时候我们不清楚传入的任意实参包含哪些信息,可以使用格式def 函数名(**形参) python 会自动生成一个空的字典存储任意数量的实参

def build_profile(first,last,**user_info):
    """创建一个字典,其中包含我们知道的有关用户的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key,value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_profile('albert','einstein',locaion = 'princeton',field = 'physics')

print(user_profile)

结果:{'locaion': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}

使用 import+文件名.py导入 python 文件

函数的存在就是为了封装性,开发中难免会用到各种各样的开源库,这个时候需要导入对应的文件才可以使用封装好的函数。
在 greet_user.py 文件中编写函数

def build_profile(first,last,**user_info):
    """创建一个字段,其中包含我们知道的有关用户的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key,value in user_info.items():
        profile[key] = value
    return profile

在 S.py文件中导入 greet_user.py 并使用该函数

import greet_user

user_profile = greet_user.build_profile('albert','einstein',locaion = 'princeton',field = 'physics')
print(user_profile)

结果还是一样。注意:可以使用导入的文件名调用该文件中的任意函数

显式导入指定的函数

语法:from 文件名 import 函数名1,函数名2,函数名3.......... 显示指定导入该文件中的哪些函数,调用时,直接指定函数名即可。
在 greet_user.py 文件中编写函数


def build_profile(first,last,**user_info):
    """创建一个字段,其中包含我们知道的有关用户的一切"""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key,value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_profile('albert','einstein',locaion = 'princeton',field = 'physics')

print(user_profile)


def function_1():
    print('i am function1')

def function_2():
    print('i am function2')

def function_3():
    print('i am function3')

在 S.py文件中导入指定函数from greet_user import build_profile,function_1,function_2

from greet_user import build_profile,function_1,function_2

user_profile = build_profile('albert','einstein',locaion = 'princeton',field = 'physics')
print(user_profile)

function_1()

function_2()

导入函数时使用别名

在导入函数时,由于函数名可能存在冲突或者函数名太长,可以使用as指定别名,调用时 直接使用别名即可

from greet_user import build_profile as bp

user_profile = bp('albert','einstein',locaion = 'princeton',field = 'physics')
print(user_profile)

导入文件时指定别名

在导入文件时也可以使用自定义别名,供调用时使用

import greet_user as gu

user_profile = gu.build_profile('albert','einstein',locaion = 'princeton',field = 'physics')
print(user_profile)

使用 * 导入文件中所有函数

直接指定函数名调用即可

from greet_user import *

user_profile = build_profile('albert','einstein',locaion = 'princeton',field = 'physics')
print(user_profile)

最后的思考:
总结编写 python 函数时需要注意的点:

最后的最后

傻瓜式学 python 第三篇总结写完了,仅仅是一种记录,如果有不妥之处,麻烦评论区指出。

更多原创文章会在公众号第一时间推送,欢迎扫码关注 张少林同学

张少林同学.jpg
上一篇 下一篇

猜你喜欢

热点阅读