Skip to content

Commands/Functions

We have already seen a built-in Python commands: print(), str(), list(), set(). We now look at two ways to define our own commands.

Defining Commands

The syntax for defining a command, which in this template we have called function_name, is:

def function_name( <parameters> ):
         :
    <statement>
    <statement>
         :
    return <expression>

Here are some examples.

def f(x):
     return x*x

f(7)   # here we test the command f      
Output:
49
def is_divisible_by_three(x):
     if x%3==0:      # check if remainder is 0 when divided by 3
         return True
     else:
         return False        # this ends the definition

print(is_divisible_by_three(6))    # here we test the command
print(is_divisible_by_three(6))   
Output:
True
False

Commands can take more than one parameter.

# function capitalizes x then concatenates with itself n times
def repeat_word(x,n):
    return x.capitalize()*n

repeat_word("limabean",3)  
Output:
'LimabeanLimabeanLimabean'

Lambda Functions

Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) using a construct called lambda. This is a very powerful concept that's well integrated into Python and is often used in conjunction with typical functional concepts like filter() and map().

Using the lambda function we can create a function like f above.

f = lambda x: x*x
f(7)
Output:
49

A lambda function can take more than one argument.

concat = lambda x,y: x+y
concat("super","man")
Output:
superman

Also note that you can put a lambda definition anywhere a function is expected, and you don't have to assign it to a variable at all. Here we use a lambda function along with filter() to pick out all elements of a list which are divisible by 3.

print(filter(lambda x: x%3==0,range(1,50)))
Output:
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]