Python Function
Hello Learners… In this session, you’ll learn about functions, what a function is, the syntax, components, and types of functions. Also, you’ll learn to create a function in Python.
What is a function in Python?
In Python, a function is a group of related statements that performs a specific task.
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
A function can return data as a result.
How to create a Function?
In Python a function is defined using the def keyword:
1 2 | def my_function(): print ( "Hello Learners" ) |
Keyword def
that marks the start of the function header.
A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a function. They are optional.
A colon (:) to mark the end of the function header.
An optional return
statement to return a value from the function.
How to call a Function?
To call a function, use the function name followed by parenthesis:
1 2 3 4 | def my_function(): print ( "Hello Learners" ) my_function() |
How to return ?
The return
statement is used to exit a function and go back to the place from where it was called.
1 2 3 4 5 6 7 8 9 10 11 12 13 | def absolute_value(num): """This function returns the absolute value of the entered number""" if num > = 0 : return num else : return - num print (absolute_value( 2 )) print (absolute_value( - 4 ))
|
No comments:
Post a Comment