The Python Functions
In this module, we will be looking at the various Python functions programs. And as a developer who is using this programming language, it is important for you to know that in this programming language a function is basically defined as a specific block of code that can only run whenever it is called. It is also possible for a user or a developer to pass parameters which are basically just a kind of data in this programming language to functions. This will help that particular function to return a particular data as a result of this.
To Create a Function
If you wish to create a particular function in this programming language then it is suggested that you should use the def keyword. For example
def my_function( ) :
print (“Hello from a function”)
To Call a Function
If you instead wish to call a function then it is recommended that you should use the particular function name that must be followed by a parenthesis. The Python function example for this is mentioned below
def my_function ( ) :
print (“Hello from a function”)
my_function( )
The Parameters
As we mentioned above, that you can pass on any kind of information to functions with the help of parameters. Parameters are always specified inside parenthesis and after the particular function name. If you wish to add a different number of parameters then you can do that but you should remember to separate all the parameters with the help of a comma. The Python function example for this is mentioned below
def my_function (fname) :
print (fname + “ Refsnes”)
my_function (“Emil”)
my_function (“Tobias”)
my_function (“Linus”)
If the above-mentioned example, there is only a single function with a single parameter which is named fname. Whenever this function is called then we pass along the first name. This is used to print the full name inside the function itself.
The Default Parameter Value
If you call any particular function without using any kind of parameter then that function automatically uses the default parameter value.
For example
def my_function (country = “Norway”) :
print (“I am from ” + country)
my_function (“Sweden”)
my_function (“India”)
my_function ( )
my_function (“Brazil”)
To Return Values
If you want a particular function to return the value then it is suggested that you should use the return statement.
For example
def my_function ( x ) :
return 5 * x
print (my_function ( 3 ) )
print (my_function ( 5 ) )
print (my_function ( 9 ) )
With this, we finish our python functions tutorial.