- def functionname( parameters ):
"function_docstring"
function_suite
return [expression]Example
def printme( str ):
"This prints a passed string into this function"
print str
return
#!/usr/bin/python
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print str;
return;
# Now you can call printme function
printme("I'm first call to user defined function!");
printme("Again second call to the same function"); Output
I'm first call to user defined function!
Again second call to the same functionPass by reference vs value:
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylistOutput
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]- There is one more example where argument is being passed by reference but inside the function, but the reference is being over-written.
#!/usr/bin/python
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist Output
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Auto AdSense
Saturday, 24 January 2015
Python Functions
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment