Python chapter 8 learning notes

定義一個函數

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 *

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章