Functions are defined using the keyword def followed by the function name
def functionName(arguments list)
unlike java and c# ,in python functions don’t specify return type in the function definition. Every function in Python returns a value.If you don’t return a value then a null value will be returned.
docstring is used for documenting the purpose of function
remember that to use functions defined in another module you need to use import it using the import module
for example if you have defined a function hello_world in a module called first_module then to use it in another
module you need to import the first_module module using the import statement.
import first_module
then you can access the public members in the first_module using the syntax ,first_module.membername.For example
to access the function hello_world in another module you use the following code
hello_world.first_module()
Its important to remember that in Python even functions are treated as objects and all functions have attribute __doc__.
You define function using the keyword def followed by function name followed by colon : .To define function body
you use identation and unidentation.Unlike other languages curly braces are not required in Python.
def print_hello(message): if print(message) else print('hello')
in the above function we didn’t give any default value to the message argument.If required we can provide default value to the function using the optional argument as:
def print_hello(message='hello'):
Following are the main points about functions in Python:
- You right indent the statements in function.you can use any number of spaces.
- You use colon after the function name.The function name must be followed by braces ( “(” and “)” ).
- If the function returns a value the place the value to return after the return statement.
- To call the function just use the function name followed by the curly braces ( and ).If the function expects any arguments place them inside the braces.
def test1(): print('hello python')