Introducing functions in Python
Functions are one of the most important concepts in programming that allow us to organize and manage our code. In this session, we will learn the basics of functions in Python and learn how to define and use our own functions.
Why functions?
You help us to:
Defining a function in Python
To define functions in Python, we use the def keyword. The general structure of a function definition is as follows:
Example
Let’s define a simple function called greet that takes a name as input and prints a welcome message:
Now we can use this function by calling it and giving it a name as input:
The output will look like this:
Parameters and arguments
Functions can have parameters that are given as input to the function. In the example above, name is a parameter. When we call the function, the values we pass to the parameters are called arguments.
Default parameters
We can define default values for parameters. If no argument is given for those parameters, the default value is used:
Now if we call the function with no arguments, the default value is used:
Return values from functions
Functions can return values as results. For this, we use the return keyword:
The answer will be as follows:
Recursive functions
Recursive functions are functions that call themselves. These types of functions are useful for solving recursive problems such as calculating factorials or the Fibonacci sequence.
Example:
Factorial Let’s define a return function to calculate the factorial:
The answer will be as follows:
conclusion
In this session, we learned about the basics of functions in Python. We learned how to define functions, handle parameters and arguments, return values, and write recursive functions.