Whats the syntax for Functions in python
def Funcname(parameter1, parameter2):
code1, code 2
returnWhats the order of function manipulation to acquire variables
LEGB
Local, enclosed, global, built in
Whats the difference between argument and parameter
argument is something u call externally of the function which is then placed into the parameters to be placed into the function.
sub the value of tha argument into the paraemter
myarg=25
def myfunc(parameter):
print parametermyfunc(arg) –> #parameter = myarg =25
print(myarg)
output: 25
25
charList = ['a', 'e', 'i', 'o', 'u']
myStr = "This is a string!"
def funcA(content, target):
num = 0
for char in content:
if char in target:
num += 1
return num
result = funcA(myStr, charList)
print(result)output = 5.
Similar kind of loop:
for char in mystr:
if char in charlist:
num+=1
What does global variable do
Brings the reference ID from global into the function and link them together
def enclosing():
myVariable = 'defined by enclosing'
def enclosed():
print('scope: ' + myVariable)
enclosed()
enclosing()By following the rules of LEGB,
“myVariable” acquires its value from the enclosed function.
If happens that “myVariable” with a value exists in the global, then the function would acquire it from there.
def myFun (param):
param.append(4)
return param
myList = [1,2,3]
newList = myFun(myList)
print(myList,newList)output=[1,2,3,4],[1,2,3,4]
Both param and myList shares the same reference index, hence changing the value of one will change the other
def myFun (param):
param=[1,2,3]
param.append(4)
return param
myList = [1,2,3]
newList = myFun(myList)
print(myList,newList)output=[1,2,3], [1,2,3,4]
a new reference has been assigned to param, hence my list and param no longer share the same reference ID.
myVar = 127
def myFun (myVar):
myVar = 7
print(‘myVar: ’, myVar)
myFun(myVar)
print(‘myVar: ’, myVar)myVar: 7 (This myVar is from the function as variables called in the functions have a different ID to compared to global variable)
myVar: 127 (This variable is from the global)
myVar = 127
def myFun ():
a = myVar + 1
print(‘a: ’, a)
myFun()‘a’ = 128
myVar adopts the value from the global variable to fit, following the rule of LEGB.
myVar = 127
def myFun ():
myVar = myVar + 1
myFun()
print(myVar)Error.
the function alr has myVar, so the programm automatically takes it from the local variable instead of the global variable.
if the code happens to change to x = myVar+1
then the result of x will be 128