Python Functions, Files, and Dictionaries3: Function

  1. Function
    1. def hello() でhelloというvariableのvalueにhello()というfunction objectをアサインしている。
    2. functionを正しく使わないと酷いことになりそう
    3. returnの役割を研究しました。
    4. returnの役割の研究結果:関数外でfunction()をアサインしたvariableでreturnを受け取る。
    5. inpterapterはdef を一度objectとして読み込む(function objectがあることを一瞥する)が、function blockは見ない。
    6. retuen statementを書くか書かないかの違い
    7.  temporary variables are local variables
  2. Globalか、localか、それが問題だ。
    1. local valueでglobal variableを使うのはOK
    2. function block内のreturn はlocal な出来事である。
    3. returnはglobalからlocal variable取得を可能にする?
  3. global statement でlocal frame でglobal variableを使用可能にする。
    1. local variableとglobal variableは同じ名前であっても別物。local variable はlocalでdefineもしくはargumentでdefineされないとerror出る。
    2. global statementの実態
    3.  functional decomposition(functionの中でfunctionを使う)
  4. functionによるside effectとは、functionによりobjectが不本意に書き変わってしまうこと
    1. Global frame内のMutableなobject、リストは、特定のperationによって関数で書き換わってしまう件
  5. optional parameter
    1. optional parameterでdefaultのargument valueを設定
    2. format()メソッドでも使えるkeyword parameter!
  6. Anonymous Functions with Lambda Expressions
    1. course_2_assessment_4

Function

ついにきたfunction

  • functions as a means of abstraction
  • local and global scope
  • side effects

 

 

  1. A header line which begins with a keyword and ends with a colon.
  2. A body consisting of one or more Python statements, each indented the same amount – 4 spaces is the Python standard – from the header line.

 

これよくわからない。

“””クォーテーション3つで囲まれるstringのことらしい”””

“””行が変わっても有効

らしい”””

def hello() でhelloというvariableのvalueにhello()というfunction objectをアサインしている。

 

 

function objectをinvoke or executeすると

valueをreturnするfunction fruitful function

valueをreturnしないfunction non-fruitful function (or procedure)

retuenを書かないと、returnのvalueはNoneになる。

print(“・・・return statementは関数から何を出力するのか決める”)
def square(x):
y = x * x
print(“return前ならyをprintもできる”)
print(type(y))
print(y)
return y
print(“return後”)# ・・・errorでないが無視される
print(type(y))#・・・errorでないが無視される
print(y)#・・・errorでないが無視される

print(“functionの外”)
toSquare = 10
result1 = square(toSquare)
print(result1)
print(str(square(toSquare)) +”  print(square(toSquare))でもOK”)
#print(y) #・・error

print(“return statementがなければNoneが出力される”)
def cube(x):
y = x * x * x
print(“・・・functionの外 かつ retuen statementなし”)
toCube = 5
result2 = cube(toCube)
print(result2)
print(cube(toCube))
print(cube(5))

functionを正しく使わないと酷いことになりそう

print(“/////////return statement書かないと2回出てきたりNoneが出てきます////”)
def constant1():
print(“variable”)
print(“・・・constant1()・・・なぜ2回出力される?”)
constant1() #これならprint(“variable”)と同じ
print(type(constant1()))
print(“・・・print(constant1())・・・2回目がNone”)
print(constant1())

print(“///////return print(variable)///////////”)
def constant3():
return print(“variable”)
constant3()
#print(constant3()) #errorおきましたSyntaxError: bad token T_OP

returnの役割を研究しました。

print(“/////////////return y/////////////”)
def constant2():
print(“variable”)
y = “constant” #これがないとNameError: name ‘y’ is not defined
return y
print(“・・・・・constant2()でfunctionだけ発動させてもreturnは表示されない”)
constant2()
print(“・・・・・print(constant2())・・・関数をprintするって何?”)
print(constant2())
#print(“・・・・・print(y)”)
#print(y)#error

print(“/////////////return y かつ function をresultにアサイン/////////////”)
def constant3():
print(“variable”)
y = “constant”
return y

result = constant3()
print(“…result…何も起こらない・・・”)
result
print(“…constant3()…だと、constant3()ないの全ての関数が動くがreturnは戻らない”)
constant3()
print(“…print(result)…これでreturnを受け取れる”)
print(result)
#print(y)error

returnの役割の研究結果:関数外でfunction()をアサインしたvariableでreturnを受け取る。

result = function_name()でfunction内でstateされたreturnのvalueをevaluateする。(関数が動くが、関数内で何かが動いても、例えばprint()があったとしても、出力されるのはreturnだけ)

def cube(x):
y = x * x * x
print(“uhmmm!!!!!”)
return y

print(“/////result = cube(10)はframeにobjectをアサインするだけだが関数動く”)
result = cube(10)
print(“/////print(cube(10)) #関数内の全てのメソッドが動く。”)
print(cube(10)) #関数内の全てのメソッドが動く。
print(“////print(result)だとreturnだけもらえる”)
print(result)

ちなみに、if statementでreturn分岐できます。

inpterapterはdef を一度objectとして読み込む(function objectがあることを一瞥する)が、function blockは見ない。

 

 

 

 

これ超重要

 

retuen statementを書くか書かないかの違い

return statementをかくと、function blockが終わる。blockはそれ以降読まれない。

def block ないの最初のreturnだけが機能する。

 temporary variables are local variables

 On the other hand, using temporary variables like y in the program above makes debugging easier. These temporary variables are referred to as local variables.

 

綺麗にできて嬉しかった。

 

Globalか、localか、それが問題だ。

結論はこうなるらしい。

つまり localで使うvariableはlocal内で定義して、globalの問題にしないこと。だ!
globalとの関わりはargumentだけにしましょう。
もしglobalからvariableを借りたいときはこうする。

Local and Global Variables - Functions and Tuples | Coursera
Video created by University of Michigan for the course "Python Functions, Files, and Dictionaries". In week three you wi...

local valueでglobal variableを使うのはOK

  • local valueにglobal variableをassignできる(global frameはいつでも使える)。
  • local namespaceでdefineされたlocal variableはglobal variableにならない。(stack frameとともにlocal variableはは消える)

def double(y):
y = 2 * y
z = 2 * x #local valueにglobal variableをassignできる(global frameはいつでも使える)。
return z + y

x = 2
y = 3

print(double(y))
print(z) #local variableはglobal variableではない。(stack frameは消える)

The variable y only exists while the function is being executed — we call this its lifetime. When the execution of the function terminates (returns), the local variables are destroyed. 
functionが(objectの認識ではなく実際に)invokeされるとlocal stack frameが作られる。

function block内のreturn はlocal な出来事である。

Local and Global Variables - Functions and Tuples | Coursera
Video created by University of Michigan for the course "Python Functions, Files, and Dictionaries". In week three you wi...

Frameの種類にはいくつかあり、Global frame以外をstack frameという?

global frame内で

variable = function(value)でfunctionをinvokeすると名前がfunctionである新しいframeがstack frameとして現れる。この時Global frameとstack frameはそれぞれ異なるyを持っている(名前は同じでも別のname spaceにいる)。

global variableのxとlocal variableのxは同じ名前であっても別物

そしてline5 を読み終えた後、stack frameは消える。

 

returnはglobalからlocal variable取得を可能にする?

y = 2
def square(x):
#y = 2 local内でdefineしないとerror出る。globalのy = 2 とは別のy
y = x * x
w = y + 1
return y

z = square(10) #この段階で初めてsquare(x) の中身をinterpretorは見る。
print(z)
#print(w) #globalからlocal variable取得ができるのはreturnのみ?
print(y) #global frameのyのvalue

global statement でlocal frame でglobal variableを使用可能にする。

local variableとglobal variableは同じ名前であっても別物。local variable はlocalでdefineもしくはargumentでdefineされないとerror出る。

local variable はlocalでdefineもしくはargumentでdefineされないとerror出る。

global variableのxとlocal variableのxは同じ名前であっても別物

y = 2
def square(x):
#y = 2 local内でdefineしないとerror出る。globalのy = 2 とは別のy
w = y + 1
y = x * x
return y

z = square(10) #この段階で初めてsquare(x) の中身をinterpretorは見る。
print(z)

global variableのxとlocal variableのxは別物

x = 9 #このglobal variableのxと
def reducing(x):#このlocal variableのxは別物。
x-=1 #このlocal variableのxは別物。
print(x)

reducing(x)

x = 9
def adding():
x += 1
print(x)

adding()

global statementの実態

def double(n):
global y #これからこのlocal namespace内で使うyはglobal frameのyだというstatement
y = 2 * n
y = 5
double(y)
print(y)

def double(n):
y = 2 * n #こちらのyはstack namespace内で使われ、消えていくy
y = 5
double(y)
print(y)

 

 functional decomposition(functionの中でfunctionを使う)

functionの中で別のfunctionをcall できる。call されるfunctionはcompositionと呼ばれる。

  • local valueにglobal variableをassignできる(global frameはいつでも使える)。
  • local namespaceでdefineされたlocal variableはglobal variableにならない。(stack frameとともにlocal variableはは消える)

def addit(x): #③x=5でaddit(x)を計算
y = x + 5
return y

def mult(x):
y = x * addit(x) #②addit(x)に飛ぶ ④addit()からreturnもらって計算
return y #⑤returnをline10に送る。

print(mult(5)) #①x=5でmult(x)を計算

print(“こっちでもいいよ”)

def addit(x):
return x + 5

def mult(x):
return x * addit(x)

print(mult(5))

functionによるside effectとは、functionによりobjectが不本意に書き変わってしまうこと

Global frame内のMutableなobject、リストは、特定のperationによって関数で書き換わってしまう件

variableにはlocal とglobalがあるが、objectにはその区別がない。

mylst = [1, 2, 3, 4]
print(id(mylst))
def changeit1(lst):
lst[0] = 5
lst[1] = 6
changeit1(mylst)
print(mylst)
def changeit2(lst):
lst += [7, 8]
changeit2(mylst)
print(mylst)
def changeit3(lst):
lst = lst + [9, 10] #これだとGlobalのmylstがmutateされない。
changeit3(mylst)
print(mylst)
def changeit4(lst):
lst = [11, 12]#これだとGlobalのmylstがmutateされない。
changeit4(mylst)
print(mylst)
def changeit5(lst):
lst.append(13)
changeit5(mylst)
print(mylst)
def changeit6(lst):
del lst[0]
changeit6(mylst)
print(mylst)

lst += [7, 8] および lst.append[7,8] および del lst

lst = lst + [9, 10]  および lst = [11, 12]

#このoperationだとGlobalのmylstがmutateされない。(stack frameが消えたらなくなる)

optional parameter

optional parameterでdefaultのargument valueを設定

Globalでargumentが入力されるまでlocalのdefault valueを使用する。

4. More Control Flow Tools
As well as the while statement just introduced, Python uses a few more that we will encounter in this chapter. if Statem...

argumentのvalueを=で指定できる。

default argumentを使ったら、その後にnon-default argumentを使えない。読み込めない。

argumentの順番を変えるだけでOK.

non-default argument follows default argument はダメな状況。interpretorが読み込めません。

 

def f(x, y, z=1):
return x + y +z
print(f(4, 2, 5))

def f(x, y=2, z=1):
return x + y +z
print(f(4, 2, 5))

initial = 7
def f(x, y=1, z=initial):
return x + y + z
print(f(4, 2, 5))
print(f(4, z=5))

def f(x, y=1, z): #これだけダメ、読み込めない。
return x + y + z
print(f(4, 2, 5))
print(f(4, z=5))

default argumentを使ったら、その後にnon-default argumentを使えない。読み込めない。

argumentの順番を変えるだけでOK.

non-default argument follows default argument はダメな状況。interpretorが読み込めません。

functionの手前でassignされたinitialが使われる。

format()メソッドでも使えるkeyword parameter!

何これ、list内のtupleをforで呼び出すと、tupleが要素としてでてくるのか・・・・

こんな使い方もある。

Anonymous Functions with Lambda Expressions

こういうことだ!

local にlambda ができるが、objectを作らない。

ほんとにオブジェクトを作らない。

variableをつけると、objectが作られる。

def last_char(s):
return s[-1]
print(last_char(“asdfg”))

print((lambda s: s[-1])(“koonmk”))

first_char = (lambda s: s[0])
print(first_char(“brrv”))

course_2_assessment_4

def test(integer, boolean=True, dict1={2:3, 4:5, 6:8}):
if boolean == True:
if integer in dict1.keys():
return dict1[integer]
else:
return False

これでもいけるらしいねびっくり。

def checkingIfIn(string, direction = True, d={‘apple’: 2, ‘pear’: 1, ‘fruit’: 19, ‘orange’: 5, ‘banana’: 3, ‘grapes’: 2, ‘watermelon’: 7}):
if direction == True:
if string in d:
return True
else:
return False
else:
if string not in d.keys():
return True
else:
return False

def checkingIfIn(a, direction = True, d = {‘apple’: 2, ‘pear’: 1, ‘fruit’: 19, ‘orange’: 5, ‘banana’: 3, ‘grapes’: 2, ‘watermelon’: 7}):
if direction == True:
if a in d:
return d[a]
else:
return False
else:
if a not in d:
return True
else:
return d[a]

# Call the function so that it returns False and assign that function call to the variable c_false
c_false = checkingIfIn(“table”, True)
# Call the fucntion so that it returns True and assign it to the variable c_true
c_true = checkingIfIn(“table”, False)
# Call the function so that the value of fruit is assigned to the variable fruit_ans
fruit_ans = checkingIfIn(“fruit”, True)
# Call the function using the first and third parameter so that the value 8 is assigned to the variable param_check
param_check = checkingIfIn(“orange”, True)+ checkingIfIn(“banana”, True)

コメント