python学习总结篇(2)——函数

如其他语言一样,除了基本知识外,另外一个重要的板块就是函数了,python中也有函数。

在python中,函数的定义方式为:

                                                   def   函数名( ):     

下面通过几个简单的例子,看看python中的函数的使用方法:

  • 一般函数
 1 def make_album(name,album_name,song_nums = 1):
 2     dict_album =  {name:[album_name]}
 3     if int(song_nums) > 1:
 4         dict_album[name].append(song_nums)
 5     return dict_album
 6 
 7 first = make_album('Avril','Fly')
 8 print(str(first)+"\n")
 9 second = make_album('Jay Zhou','Jay Chou\'s bedside story',10)
10 print(str(second)+"\n")
11 third = make_album('Tall swift','welcome to New York',12)
12 print(str(third)+"\n")

       上一段代码中,使用 def make_album():定义了函数。在这个函数中,有三个参数,其中最后一个参数有默认形参值,因此,在传入参数的时候,针对有默认形参的情况,也可以传入两个参数。即,python也可以声明有默认参数的函数,对于有默认参数的函数,传入的实参个数可以少于形参个数

  • 形参个数不定,但是实际上都存放在元组这种数据结构中
1 def make_pizza(size,*toppings):
2     print("\nmaking a "+str(size)+" size pizza with following toppings:")
3     for topping in toppings:
4         print("-"+topping)
5 
6 make_pizza(12,'apple')
7 make_pizza(25,"banana","mango","beaf","tomato")

       上一段代码中,def make_pizza(size,*toppings): 所定义的函数,除了接收一个size,还另外可以接收了不定个数的参数,这些参数组成元组存放在元组变量toppings中注意,采用*标识的变量名即为元组

  • 形参个数不定,但是实际上都存放在字典这种数据结构中
 1 def build_profile(first_name,last_name,**user_info):
 2     profile = {}
 3     profile['first'] = first_name
 4     profile['last'] = last_name
 5     for key,value in user_info.items():
 6         profile[key] = value
 7     return profile
 8 
 9 message = build_profile('albert','einstein',nation='American',filed='physics',year = 12)
10 print(message)

       上一段代码中,def build_profile(first_name,last_name,**user_info): 所定义的函数,除了接收两个参数"first_name"和“last_name”外, 还另外可以接收了不定个数的参数,这些参数组成字典存放在字典变量user_info中,注意采用**标识的变量名即为字典变量名。因此第9行代码中,nation='American',filed='physics',year = 12实际上标识三个参数,其中: nation, field, year表示字典中的键,'American','physics',12表示对应的键所对应的取值。

 

       进一步的,可以参考:https://www.jb51.net/article/58010.htm,这篇博客中对python的函数用法也有说明。

 

posted @ 2021-03-08 21:39  少年π  阅读(121)  评论(0编辑  收藏  举报