Let us look at an example
Let us say we want to find the volume of a cube so we write
def volume(side):
return side*side*side
print(f"The volume of a cube is {volume(3)} cubic cm")
//The volume of a cube is 27 cubic cm
- Here we say that we want to define a function with the keyword
def
which stands fordefine
in python. volume
is a name given to that function.- In parenthesis,
()
we are passing an argument which is of type number. - And we end the
()
with:
so that the indentation (4 spaces) will begin from the next line. - return the result with the
return
keyword. - We are calling this method inside a
print
statement where we interpolate the value returned by the function.
Quick gotchas when you are defining a function
- The function name cannot start with numbers or any special characters.