python从入门到实践(七)——函数


前言

不管是什么编程语言,函数绝对是整个语言中最重要的部分。我们写代码很大一定程度上就是在写函数,没有函数也就没有了程序。


一、函数

函数就是带名字的代码块,用于完成具体的某项任务。通过使用函数,你的代码将会更加容易编辑、阅读、测试与修改。

1.定义函数

使用 def 关键字来定义一个函数,跟前面的for循环、if语句、while循环一样,要有冒号,且后面缩进的内容都是函数的结构体,代码块。函数中用三引号引起的部分叫做文档字符串的注释,用来描述函数是做什么的使用函数则比较简单,只需要将函数名写下即可。

函数的括号里是该函数接受的参数,通常来讲,括号里的成为形参,真正传递给该函数的称为实参。

2.传递实参

传递实参的方法有三种:分别是位置实参、关键字实参和默认值

位置实参:顾名思义,就是将参数与位置联系在一起的实参,因为定义函数时,可能定义了两个形参,若要向该函数传递实参,就必须按照形参的排列顺序,给实参进行位置排列,这就是位置实参。因此,在位置实参中,参数的顺序极为重要。

关键字实参:关键字实参类似于字典中的键值对,他是传递给 函数一个名称——值对,直接在实参中将形参的名与实参的值对应起来,关联起来。因此,向函数传递实参时不会出错,也就无需考虑实参的相对顺序。

默认值:给形参设置默认值,可以让我们少向形参传递一些参数,但传递实参的方式还是上面的两种,习惯上我们会将有默认值的形参放在后面,因为使用位置实参时,比较容易书写与使用。

调用函数时,我们要保证,函数中的每一个形参都有一个实参对应,这个实参可以时位置实参,也可以是关键字实参,也可以时原始的默认值。只有保证每一个形参都有值,才能避免实参的错误。

3.返回值

函数不仅可以获得实参并进行运算,他还可以返回一定的信息。
在调用有返回值的函数时,我们需要提供一个变量,用于存放函数的返回值。
函数可以返回任何类型的值,包括列表和字典

4.传递列表

定义的函数可以接受列表数据,同样可以处理列表数据,对列表进行永久性的处理,若要向对列表不进行操作可以考虑对列表的切片进行操作。

5.传递任意数量的实参

*topping之类的形参代表可以接受许多、未知数量的参数。可以结合使用位置实参
**topping之类的形参可以接受键值对数据,并把它们放在一个字典中。

6.将函数储存在模块里

导入整个模块:import XXX。引用时要加 ‘.’ 作为分割。
导入模块里的某个函数:from XXX(.py) import XXX。引用时不用加点。
用 as 给模块和函数指定别名

二、使用步骤

1.引入库

代码如下(示例):

#消息
from ctypes import LittleEndianStructure
from operator import truediv


def display_massage():
    """打印一条信息 """
    print('hello world!')
display_massage()
#喜欢的图书
def favourite_book(title):
    print('one of my favourite book is '+title)
favourite_book('Alice in Worldland')
#T恤 尺码与字样
def make_shirt(size,message):
    print('the size of the T-shirt is '+size)
    print(message)
make_shirt('small','hello world')
#大号T恤
def make_shirt(size='large',message='I love python'):
    print('the size of the T-shirt is '+size)
    print(message)
make_shirt()
make_shirt('small','hello world')
make_shirt('middle')
#城市
def describe_city(name,country="China"):
    print(name+' is in '+country)
describe_city('jinan')
describe_city('weifang')
describe_city('New York','American')
#城市名
def city_country(city,country):
    temp='"'+city+','+country+'"'
    return temp
msg=city_country('jinan','China')
print(msg)
#专辑与用户的专辑
def make_album(singer,title,song_num=''):
    albums={}
    albums[title]=singer
    if song_num:
        albums[song_num]=song_num
    return albums
active=True
while active:
    singer=input('enter singer\'s name')
    title=input('enter album\'s name')
    print(make_album(singer,title))
    repeat=input('would you like to repeat again?(yes/no)')
    if repeat=='no':
        break
#魔术师
magicians=['zhang','li','wang']
b=magicians[:]
def show_magicians(list):
    for magician in list:
        print(magician)
def make_great(list,list1=[]):
    for value in range(0,len(list)):
        list1.append('the great '+list[value])
    return list1
show_magicians(magicians)
c=make_great(magicians)
show_magicians(c)
show_magicians(magicians)
#三明治
def sandwich(*toppings):
    for topping in toppings:
        print(topping)
sandwich('ham sandwich','beef sandwich',)
#用户简介
profile={}
def user_profiles(first,last,**info):
    profile['first_name']=first
    profile['last name']=last 
    for key,value in info.items():
        profile[key]=value
    return profile
user_profile=user_profiles('zhang','san',city='jinan',country='china')
print(user_profile)
#汽车
car={}
def cars_info(brond,size,**info):
    car['brond']=brond
    car['size']=size
    if len(info)<2:
        print('请输入两个以上信息')
        car_0={}
        return car_0
    else:
        for key,value in info.items():
            car[key]=value
        return car
car_info=cars_info('QQ','small',color='blue',tow_packet=True)
print(car_info)

2.导入函数

代码如下:

def print_function(unprint_designs,finished_design):
    while len(unprint_designs):
            temp=unprint_designs.pop()
            finished_design.append(temp)
            print(temp+'打印完成')

import _8_2

def print_modal(unprint_designs,finished_design):
    _8_2.print_function(unprint_designs,finished_design)
    print('完成打印')

unprint_designs=['zhangsan','lisi','wagnwu']
finished_design=[]
print_modal(unprint_designs,finished_design)

总结

函数是一个非常重要的内容,本章主要学习了:
1.函数的定义
2.函数的参数
3.函数的返回值
4.函数的模块

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值