定义一个函数
For example,
def greet_user():#定义函数
print("Hello!")
Now, we just need to input greet_user() and Hello! will be shown on the screen.
o 向函数传递信息
其实这一点和C语言基本是一致的。这个函数其实就是一个子函数,可以通过括号中的参数向子函数传递信息。
例子:
# -*-coding: utf-8 -*-
def greet_user(username):
print("Hello!" + username.title())
name = input("Please input your name.\n")
greet_user(name)
在这里面,形参就是指子函数def greet_user(username)括号里面的,实参就是最后一行里面的name所代表的。
o 关键字实参
def describe_pets(animal_type, pet_name):
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pets(animal_type = 'cat', pet_name = 'hurry')#关键字实参
关键字实参的顺序无关紧要。但是普通的顺序必然非常重要。
o 默认值
def describe_pets(pet_name, animal_type = 'dog'):#默认值设置
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
#typ = input("Please input the type of your pet.\n")
#name = input("Please input its name.\n")
#describe_pets(typ,name)
describe_pets(pet_name = 'hurry')#关键字实参
设置了默认值之后,默认值项得在形参括号中的最后。设置默认值之后,如果该参数不再修改,那么这个参数就自动为默认值,但是如果后面对其进行了传递,则使用传递的值而不再是默认值。设置了默认值之后,实参可以少一个(本例中,实参只剩1个)
· 返回值
o 返回简单值。此处返回值与C语言中类似。
o 让实参变成可选。可以利用指定一个默认值,即为空值即可。用到就在后面实参里写上,用不着就直接用默认的空。
o 返回字典。例如,
def build_person(first_name, last_name):
person = {'first': first_name,'last': last_name}
return person
musician = build_person('jimi', 'hendrix')
print(musician)
· 传递列表
o 在函数中修改列表
For example,
def print_models(unprinted_designs, completed_models):
while unprinted_designs:
current_design = unprinted_designs.pop()
print("Printing model: " + current_design)
completed_models.append(current_design)
Finally, unprinted_designs will not have any element. But, what if we want to retain these elements? The answer is as followed:
Use slice. function_name(list_name[:]).
For example, when we call function print_models(unprinted_designs, completed_models),we need to change it to print_models(unprinted_designs[:], completed_models).
· Pass lots of actual parameter
o Using *name as a formal parameter, this is just like a list.. For example,
def make_pizza(*toppings):
print(toppings)
make_pizza('mushrooms', 'green peppers', 'extra cheese')
o Using **name as a formal parameter, this is just like a dict.
· Import functions()
o Import whole function
For example,
import pizza #There is a function file called pizza.py
pizza.make_pizza(16, 'pepperoni') # We need to point out the function from which file
o Import specific function
from module_name import function_name
If we use this, we do not need to point out the function from which file.
· Using as to specifying aliases for functions(用as为函数指定别名)/using as to specifying aliases for module(用as为模块指定别名)/import all functions from module.
o from pizza import make_pizza as mp
o import pizza as p
o from pizza import *