A function can 'return' a value, for example:
print a + " " + b
if(a > b):
The ouput will be: 45 is greater than 30
def display_message(message, truncate_after=4):
mess
display_message("message", 6)
message
(5, 2, 'omega')
make_dictionary(max_length=2, key1=5, key2=7, key3=9)
{'key3': 9, 'key2': 7}
Passed objects of mutable types such as lists and dictionaries can be changed by the called function and the changes are visible to the calling function. Passed objects of immutable types such as integers and strings cannot be changed by the called function; the calling function can be certain that the called function will not change them. For mutability, see also Data Types chapter.
ilist.extend(newcontentlist) # Modification visible to the caller ilist = [5, 6] # No outside effect; lets the local ilist point to a new list object, # losing the reference to the list object passed as an argument
# losing the reference to the int object passed as an argument
print "iint inside:",iint # 4 if iint was 3 on function entry
appendItem(list1, 3)
print list1 # [1, 2, 3]
replaceItems(list1, [3, 4])
print list1 # [3, 4]
set1 = set([1, 2])
clearSet(set1 )
print set1 # set([])
int1 = 3
tryToTouchAnInteger(int1)
print int1 # 3
foo()
square(3)
bar(5, x)
A function's return value can be used by assigning it to a variable, like so:
x = foo()
y = bar(5,x)
As shown above, when calling a function you can specify the parameters by name and you can do so in any order
def display_message(message, start=0, end=4):
This above is valid and start will have the default value of 0. A restriction placed on this is after the first named argument then all arguments after it must also be named. The following is not valid
display_message(end=5, start=1, "my message")
because the third argument ("my message") is an unnamed argument.