This lesson will teach you about creating; calling a function in Python functions, including what a return declaration in the function is, with examples.
Our program can be divided up into smaller, modular portions with the use of functions. In Python, a function is a collection of connected statements that work together to complete a certain goal. Functions enable our program to become more streamlined and controllable as it expands; Additionally, it keeps the code reusable and prevents repetition.
In Python, a function is defined by utilizing the def keyword:
def myFirstFunction(): print("Python Function")
The function definition above consists of the following elements.
Use the function name in parenthesis to invoke the function. After defining a function, we can use it to call other functions, programs, or even the Python prompt. Simple typing of the function name and the compiler will invoke the function.
def myFirstFunction(): print("Python Function") myFirstFunction()
myFirstFunction() def myFirstFunction(): print("Python Function")
Traceback (most recent call last): File "<string>", line 1, in <module> NameError: name 'myFirstFunction' is not defined
Use the return statement to allow a function to return a value. To leave a function and return to where it was called, utilize the return statement.
The value is returned once the expression in this statement has been evaluated. The function will return the no object if there is no expression in the statement or if the return statement itself is missing from a function.
def myFirstFunction(x): sum =2 + x return sum print(myFirstFunction(3))
Here, 5 is the returned value since myFirstFunction() return the sum and prints it while calling.