触目
ひとりで生き、この世を観 この世の雨の音をきき そしてまた死んで行ったとしても 何者をこの世に残さなかったとしても それだけで沢山ではないか その片鱗をかがやかせただけで 蝶はわが眼から失われて行ったではないか 百田宗治 第9章 関数 関数型プログラミング メソッド
|
Function | |
Functions are named sequences of statements that execute some task. |
We have already used functions, such as:
>>> type('GAATTC') <type 'str'> >>> len(cds) 852
For example len is a function that calculates the length of things and we asked here for the length of our DNA sequence cds.
Function call | |
Function calls are statements that execute or call a function. The Python syntax of function calls is the function name followed by a comma separated list of arguments inclosed into parentheses. Even if a function does not take any argument the parentheses are necessary. |
Differences between function calls and variables. As variable names, function names are stored in a namespace with a reference to their corresponding sequence of statements. When they are called, their name is searched in the namespace and the reference to their sequence of statements is returned. The procedure is the same as for variable names. But unlike them, the following parentheses indicate that the returned value is a sequence of statements that has to be executed. That's why they are even necessary for functions which are called without arguments.
Arguments of functions | |
Arguments are values provided to a function when the function is called. We will see more about them soon. |
.1. Defining Functions
In Section 3.5 we have learnt how to apply or call functions. So let's remember the example calculating the GC-percentage of a DNA sequence.
>>> float(count(cds, 'G') + count(cds, 'C')) / len(cds)
This calculates the gc percentage of the specific DNA sequence cds, but we can use the same formula to calculate the gc percentage of other DNA sequences. The only thing to do is to replace cds by the new DNA sequence in the formula. But it is not very convenient to remember the formula and retype it all the time. It would be much easier to type the following instead.
>>> gc('ATGCAT') 0.33333333333333331 >>> gc(cds) 0.54460093896713613
The only thing we have to remember is the name of the new function and its use.
Abstraction | |
The possibility to define such new function executing tasks specified by yourself, is an abstraction feature, provided by all high level programming languages. |
Important | |
---|---|
It is also important to notice that functions have to be defined before they are called. You can not use something that is not defined. |
Here is the syntax of such a new definition in Python:
>>> from string import * >>> def gc(seq): ... return float(count(seq, 'G') + count(seq, 'C')) / len(seq)
Let's have a closer look at this definition. Figure 8.1 illustrates the structure of a function definition.
def and return are basic instructions.
The return basic instruction is used to return the result of a function back, in our example the value of the GC percentage of the specified DNA sequence.
The def basic instruction indicates to Python that a function definition follows. It has to be followed by the new function name and a comma separated list of parameter names enclosed into parentheses.
Parameter | |
Parameters are variable names. When the function is called they are bound in the same order to the arguments given. |
The body of a function contains the piece of code needed to execute the subtask of the function. In the example above, the body contains only the return statement. Here is a more complex example that excludes ambiguous bases from the GC percentage calculation.
>>> from string import * >>> def gc(seq): ... nbases = count(seq, 'N') ... gcpercent = float(count(seq, 'G') + count(seq, 'C')) / (len(seq) - nbases) ... return gcpercent
In this example the body of the function contains three instructions (2 assignments and the return statement). The body of a function follows the definition line and is written as an indented block initiated by a colon.
Block | |
Blocks are structure elements of a program, that are used to group instructions. They are initiated by a colon and are separated from the rest of the code by the same indentation step in Python. |
In our example, the function body is written as a block to separate it from the rest of the program. The Python interpreter used it to detect where the function body starts and ends.
Important | |
---|---|
In other programming languages special words or characters are used to indicate the begin and the end of blocks and the indentation is only used to make the code readable for humans. In Python the indentation is used explicitly to do this. So in the above example of a function definition the end of the body is detected when the next line starts without any indentation step. This is also illustrated in Figure 8.2. |
1関数とは
にはあらかじめ用意されている組込関数と自分で作る関数
と2種類ある。利用の方法は全く同じである.
名前(引数)の形式で書かれる
len(x) 引数Xについて何かをする lenは組み込み関数
>>> s=[1,2,3,4,5,6]
>>> len(s)
6
関数のメリットは
1.繰り返し作業をコード化する
2.処理の内容が短縮される
3.処理の変更が容易になる。
(10)フィナボッチ級数を任意の境界値ま書きだす関数
def fib(n): <キーワードdefは関数を定義
***nまでのフィナボッチ級数を表示する*** <文字列リテラル、関数のドキュメ
ン
テーション文字列、docstring
docstringはよい習慣。
<関数本体が始まる
<本体はインデントして始まる。
a,b=0,1 <ローカル変数a,b
while b < n :
print(b,)
a,b=b,a+b
>>> fib(2000) <関数をコールするときに与えら
れる実パラメータ[引数)2000
関数を定義すると、この関数名の値(実体)の型がユーザ定義関数。この
値を別の名前に代入すればその名前も関数として使えるようになる。
>>> fib
<function fib at 0x0106B270>
>>> f=fib
>>> f(100)
1
1
2
3
5
8
13
21
34
55
89
def parr(vol,state='stiff',act='voo',type='norw'): <引数
print('this par',act,)
print('if you',vol,'volta')
print('lovely',type)
print('tts',state ,'!')
>>> parr(10) <引数 10 はvol
this par voo
if you 10 volta
lovely norw
tts stiff !
(11)メッソドと関数との用語の使い方について認識 する
(12)関数に説明文を加える
>>> def jyoto():
jyoto=input("譲渡金額>")
"譲渡金額は減価償却した後の金額です"
syutoku=input("取得金額>")
kairyohi=input("改良費>")
"改良費も償却した後の金額です"
keihi=input("経費>")
"仲介料等の経費です"
kazei=int(jyoto)-int(syutoku)-int(kairyohi)-int(keihi)
zei=int(kazei)*0.2
"税は国及び地方税の概算額です"
"資金は譲渡の結果得られる資金額です"
sikin=int(jyoto)-int(zei)
print("譲渡金額=" ,jyoto)
print("税= ",zei)
print("取得資金= ",sikin)
>>> jyoto()
譲渡金額>10000000
取得金額>5000000
改良費>500000
経費>300000
譲渡金額= 10000000
税= 840000.0
取得資金= 9160000
(13)キーワード引数
キーワードの順序に関係しない
>>> def greet(a):
"引数を設定"
print("hello" + a)
>>> greet(" taro !")
hello taro !
>>> def greet(a , b):
"引数を2個設定"
print("hello "+a+b)
>>> greet("taro !"," hanako !")
hello taro ! hanako !
>>> greet(a="python",b=" ruby !") 関数を名前付き変数で呼び出す
hello python ruby !
>>> def greet(a="python !"):
"デフォルト引数をpythonとする"
print("hello " + a)
>>> greet()
hello python !
>>> greet("ruby !") 引数rubyを指定する
hello ruby !
リストのメソッド
第8章リストを参照
ホーム 戻る