In Python you declare (define) a function by using the the
def
keyword followed by function name then function parameters inside brackets () (comma separated) and then end the def statement with a colon (:) to indicate that your function will begin in the following line(s). And at the end of the function, you can have a return statement to return the value(s) to the caller so that whenever you call the function, you'll get value(s) back.Let's see an example of a function that simply adds 10 to any number we give it
Code: Select all
def add_ten(num):
return_value = num + 10
return return_value
Now, for example, if we wanted to call the add_ten function with 5 as input we'd use
add_ten(5)
Can you guess what this call will return? It'll return 15 (because 5 + 10 is 15).
Functions are good when you have piece of code that you'd like to reuse with different input parameters to get different outputs.
You can call other functions and inside a function. A function can even call itself (which would make it a recursive function). This ability to create/define new functions is what makes programming so dynamic.
What Python also allows you to do which sometimes can be really useful is the ability to set a variable to be a function such as
my_func = add_ten
Then now you can call my_func like as if you were calling add_ten like
my_func(10)
.I don't know any other languages (I am sure they exist just not all that common though) that lets you set a variable to hold a function like this.
Play with what you've learned here.
Next lesson: User Inputs in Python Previous lesson: If... Else... in Python