Curriculum
In this lesson, you will be learning about functions in python, its use cases with some examples.
Topics covered:
Functions in python are a block or set of code or related statements that are used to perform a specific task or to reuse a specific code multiple times. Functions are both user-defined and built-in. You can pass arguments or parameters into a function. It helps to keep the program code organised and easily manageable.
Syntax:
def function_name(parameters): statement(s) return expression
To create a function in python, you need to use the def keyword followed by the function name. The function names are user-defined, so you can give any name (other than reserved words and keywords) to the function. If you’re using multiple words as a function name, then the words should be separated using an underscore (_).
Example:
def simple_function():
The function needs to be called to return the result. Call the function by using the function name followed by parenthesis along with the arguments.
Example:
def simple_function(): “statements” simple_function(): #calling the function
Arguments or parameters are values that are passed to a function. A function can have multiple arguments in it separated by a comma (,). You need to specify the arguments in the function by mentioning them inside the parenthesis. If you do not know the solid count of arguments, you can add a ‘*’ before the arguments.
Example:
def simple_function( x, y): if x>y: print(‘X is greater the Y) else: print(“ Y is greater than X)
To return values from a function, you need to use the return keyword. The return statement can consist of a variable, an expression, or a constant. If none of the above is present with the return statement a None object is returned.
Syntax:
return [expression_list]
Example:
def simple_function(a): return 57+a print(simple_function(67)) print(simple_function(75)) print (simple_function(76))
Now, let us write some programs to understand more about function in python
Sample program using functions in pythonInput:
Input:
def simple_function(first, last): print(first +" "+last) simple_function("Developer_Publish", "Academy")
Output:
Developer_Publish Academy
Sample program using functions in python
Input
def simple_function(x, y): if x>y: print("X is greater the Y") else: print("Y is greater than X") return(x,y) simple_function(7,5)
Output:
X is greater the Y