Funktionen
So kannst du einen Funktion definieren:
def function(parameters):
instructions
return value
Das def keyword ist das Schlüssel Wort. Ein Python Programm kann vielen Funktionen haben.
Python Crashkurs: Eine praktische, projektbasierte Programmiereinführung
Beispiel Der Funktion und parameter:
#!/usr/bin/python
def f(x):
return x*x
print f(3)
Resultat:
9
Der Funktion hat ein parameter: x. Der "return value" ist die werte die der Funktion zurueck gebt. Nicht alle funktionen habben immer ein "return value".
#!/usr/bin/python
def f(x,y):
print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y)
print 'x * y = ' + str(x*y)
f(3,2)
Resultat:
You called f(x,y) with the value x = 3 and y = 2 x * y = 6
Scope Variables konnen nur das gebiet erriechen in dem sie definiert sind, der sogenante 'scope'.
#!/usr/bin/python
def f(x,y):
z = 3
print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y)
print 'x * y = ' + str(x*y)
print z # can reach because variable z is defined in the function
f(3,2)
Funktionen in funktionen Ein funtion kann in ein funktion angerufen werden:
#!/usr/bin/python
def highFive():
return 5
def f(x,y):
z = highFive() # we get the variable contents from highFive()
return x+y+z # returns x+y+z. z is reachable becaue it is defined above
result = f(3,2)
print result
Variablen konnen nur in der scope erreicht werden, also das wird nicht funktionieren:
#!/usr/bin/python
def doA():
a = 5
def doB():
print a # does not know variable a, WILL NOT WORK!
doB()
aber das funktioniert:
#!/usr/bin/python
def doA():
a = 5
def doB(a):
print a # we pass variable as parameter, this will work
doB(3)