Next in our series of Python lessons, we will introduce functions. This is a topic that will help you get even more enthusiastic about programming! As you witness how easy Python is, you will be increasingly motivated to pursue a career in software development, data science, or game development.
Functions are an important concept in programming, and Python is no exception. They allow you to divide your code into smaller blocks that can be executed whenever you call them.
Functions help you create code that is ordered optimized. They also save time and space in memory as the variables defined inside functions are all loaded in memory only when the function is called rather than existing all the time.
Functions have enabled code modularity, allowing programmers to share code easily by sharing a single function that can do a certain job. The beauty is that the person using the function has no need to look at or understand the code within its body. In other words, functions can be shared and then treated as black boxes.
When a function is called, you can pass data into it through parameters, which are variables that accept data from outside the function to be used inside the function. The function may or may not return data.
Functions in Python are defined using the def keyword:
def fun():
function body
When you want to call a function to be executed in Python, you use the function name, followed by a pair of parentheses like this:
fun()
A function’s parameters are defined inside the parentheses after the function’s name. When you call a function, you pass the values that should be loaded into these parameters. You can define any number of parameters inside the parenthesis as long as they are separated with commas. For instance:
def add(x, y):
z = x+y
When you call this function, you will write:
add(3,4)
Your answer will be 7, but that value will not be sent back, or returned, by the function since you have not specified a return statement. A return statement tells a function to return a value back to the code:
def add(x,y):
z=x+y
return z
The value of z is returned to your spot in the code.
Functions can save you from having repetition in your code. They can make your code more readable and better organized.
Want to try writing some functions and see if you can solve challenges? Try out RoboGarden’s missions now. Register for free.