\(\renewcommand\AA{\unicode{x212B}}\)
def
is used to
mark a function and as with the other control structures the block of
code that defines the function is indenteddef sayHello():
print(' ----- HELLO !!! ----- ')
where now every call to sayHello()
will produce the same message
format and if the code requires updates then there is only one place to
change.
def printSquare(n, verbose):
if verbose == True:
print( 'The square of ' + str(n) + ' is: ' + str(n*n))
elif verbose == False:
print(str(n*n))
else:
print('Invalid verbose argument passed')
printSquare(2, True) # Produces long string
printSquare(3, False) # Produces short string
printSquare(3,5) # Produces error message
Gives the output:
The square of 2 is: 4
9
Invalid verbose argument passed
where we have combined functions and control structures to do something more useful.
printSquare(verbose = True, n = 2) # produces the same as
# printSquare(2, True)
def foo(A, B, C, D, E):
# ... Do something
return
foo(1, 2, 3, 4, 5) # Correct, no names given
foo(1, 2, 3, D=4, E=5) # Correct as the first 3 get assigned to the first
# 3 of the function and then the last two are
# specified by name
foo(C=3, 1, 2, 4, 5) # Incorrect and will fail as a name has been
# specified first but then Python doesn't know
# where to assign the rest
This kind of calling can be useful when there is a function with many arguments and some at the end have default values (see below). The one that the user wishes to pick out can simple be given by name
def printSquare(n, verbose = False):
if verbose == True:
print( 'The square of ' + str(n) + ' is: ' + str(n*n))
elif verbose == False:
print(str(n*n))
else:
print('Invalid verbose argument passed')
return
printSquare(2) # Produces short message
printSquare(2, verbose = True) # Produces long message
Gives the output:
4
The square of 2 is: 4
return
statement.def square(n):
return n*n
two_squared = square(2)
# or print it as before
print(square(2))
Gives the output:
4
def square(x,y):
return x*x, y*y
t = square(2,3)
print(t)
# Now access the tuple with usual operations
Gives the output:
(4, 9)
def square(x,y):
return x*x, y*y
xsq, ysq = square(2,3)
print(xsq) # Prints 4
print(ysq) # Prints 9
# Tuple has vanished!
Gives the output:
4
9