Python笔记-012-函数

1.12.1
定义函数格式

def greet_user():
    print("Hello")
greet_user()

1.12.2
向函数传递信息

def greet_user(username): #在greet_user()定义中,变量username是一个形参
    print("Hello,"+username.title()+"!")#Gonathan是一个实参
greet_user('Gonathan')

在 greet_user中将‘Gonathan’传递给函数greet_user(),这个值被存储在形参username中

1.12.3 位置实参-调用函数多次

def describe_pet(anmal_type,pet_name):
    print("\nI have a "+anmal_type+".")
    print("My "+anmal_type+"'s name is "+pet_name.title()+".")
describe_pet('hamster','harry')
describe_pet('dog','Wang Cai')

I have a hamster.
My hamster’s name is Harry.

I have a dog.
My dog’s name is Wang Cai.

可以调用函数任意次,只需要再次调用describe_pet()即可
形参跟实参的练习是位置相关的

使用实参的时候可以直接在函数定义中,明确指出对应的形参,如下所示,虽然顺序调动了,但是不影响结果,也就是我们可以忽略程序的实参顺序

def describe_pet(anmal_type,pet_name):
    print("\nI have a "+anmal_type+".")
    print("My "+anmal_type+"'s name is "+pet_name.title()+".")
describe_pet(pet_name='harry',anmal_type='hamster')
describe_pet('dog','Wang Cai')

1.12.4函数返回值

def get_formatted_name(first_name,last_name):# def 函数后记得一定要加冒号
    full_name=first_name+" "+last_name
    return full_name
musician=get_formatted_name('Jimi','Hendrix')
print(musician)

Jimi Hendrix
这个是一个显示全名的函数

2)让实参变成可选的

def get_formatted_name(first_name,last_name,middle_name=''):# def 函数后记得一定要加冒号
    if middle_name:
        full_name=first_name+" "+middle_name+" "+last_name
    else:
        full_name = first_name + " "+ last_name
    return full_name
musician=get_formatted_name('Jimi','Hendrix')
print(musician)
musician=get_formatted_name('Messi','leon','Niubi')
print(musician)

用一个if判断middle_name是否为空

3) 返回字典,
函数可以返回任何类型的值,包括列表和字典较复杂的数据结构。

def get_formatted_name(first_name,last_name,middle_name=''):# def 函数后记得一定要加冒号
    person = {'first': first_name, 'last': last_name, }
    if middle_name:
        person['middle_name']=middle_name
    return person
musician=get_formatted_name('Jimi','Hendrix')
print(musician)
musician=get_formatted_name('Messi','leon','Niubi')
print(musician)

{‘first’: ‘Jimi’, ‘last’: ‘Hendrix’}
{‘first’: ‘Messi’, ‘middle’: ‘Niubi’, ‘last’: ‘leon’}

4)结合使用函数和while循环

# print(musician)

def get_formatted_name(first_name,last_name,middle_name=''):# def 函数后记得一定要加冒号
        full_name=first_name+" "+last_name
        return full_name.title()
while True:
    print("\nPlease tell me your name:")
    f_name=input("First name : ")
    l_name=input("Last name : ")

    formatted_name=get_formatted_name(f_name,l_name)
    print("\nHello,"+formatted_name+"!")

Please tell me your name:
First name : Guo
Last name : Gonathan

Hello,Guo Gonathan!

5)传递列表:

def print_models(unprinted_design,completed_models):
    while  unprinted_design:
        current_design=unprinted_design.pop()
        print("Printing model:"+current_design)
        completed_models.append(current_design)
def show_model(completed_models):
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)
unprinted_design=['dodecahedron','robot pendant','iphone case']
completed_models=[]

print_models(unprinted_design,completed_models)
show_model(completed_models)

Printing model:iphone case
Printing model:robot pendant
Printing model:dodecahedron

The following models have been printed:
iphone case
robot pendant
dodecahedron

使用函数传递列表,让程序看起来更加整洁。
大部分的工作代码都转移到两个函数中,让主函数更加容易理解
6) 传递任意数量的实参

def make_pizza(*toppings):
    print(toppings)
make_pizza('pepperoni')
make_pizza('Mushrooms','green peppers ','extra cheese')

不管调用语句提供了多少实参 ,这个形参都将它统统收入囊中

1.12.5导入函数
pizza.py

def make_pizza(size,*toppings):
    print("\n Making a "+str(size)+"-inch pizza with the following toppings: ")
    for topping in toppings:
        print("-  "+topping)

自己的 .py

import pizza
pizza.make_pizza(16,'pepproni')
pizza.make_pizza(12,'mushnrooms','green peppers','extra cheese')

只需要编写一条import语句 并在其中指定模块名,就可以在程序中使用该模块的所有函数。
比如你使用了这种import语句导入了名为:module_name.py的整个模块,就可以使用下面的语法来使用其中的任何一个函数

module_name.function_name()

1.12.5导入特定的函数

from module_name import function_name
from module_name import function_0,function_1,function_2
from pizza import make_pizza
from pizza import make_pizza
make_pizza(16,'pepproni')
make_pizza(12,'mushnrooms','green peppers','extra cheese')

跟前面的相比就是少了 pizza.

1.12.6使用as给函数指定别名
1)
如果要导入的函数的名称可能与程序中现有的名称冲突,或者函数的名称太长,可以指定一个独一无二的别名,比如下面的程序给make_pizza()指定了别名mp()。

from pizza import make_pizza as mp
mp(16,'pepproni')
mp(12,'mushnrooms','green peppers','extra cheese')

上面的import语句将函数make_pizza()重名为mp()

2)
同样也可以使用as给模块指定别名

import  module_name as mn

3) 导入模块中所有的函数

from pizza import *

使用星号(*)运算符可让Python导入模块中的所有函数

import语句的星号让Python 将模块pizza中每个函数都复制到这个程序文件夹中,由于导入了每个函数,可以通过名称来调用每个函数,而无需使用句点表示法。

函数编写指南

编写函数时候,要记得的几个细节。给函数指定描述性名称,且只在其中使用小写字母和下划线。描述名称可以帮你和别人更好理解代码,养成好习惯。
每个函数都应该包含简要的阐述其功能的注释,该注释应该紧跟在函数定义后面,从用文档字符串格式。
所有的import语句都应该放在文件的开头,唯一列外的情形,在文件的开头使用了注释来描述整个程序。

猜你喜欢

转载自blog.csdn.net/qq_35989861/article/details/81839895