-
Python Functions
A function is a block of code which only runs when it is invoked. The idea is to put some commonly or repeatedly done tasks together and make a function.
You can pass data, known as parameters, into a function. A function can return data as a result.Creating a Function
In Python a function is defined using the def keyword:
Example:
def my_function():
print(“Hello world”)Calling a Function
To call a function, use the function name followed by parenthesis:
Example:
def my_function():
print(“Hello world”)
my_function()Passing parameter to a function
The below function print_name(x), takes x as a parameter and uses it inside the functiondef print_name(x):
print(x)
print_name(“John”)The print_name function is called by passing “John” as a parameter. The print function prints John
Returning data from a function
The add number function below adds two numbers and return
def add(num1, num2):
num3 = num1 + num2
return num3num1 = 4;
num2 = 8;
result = add(num1, num2)
print(f”The addition of {num1} and {num2} results {result}.”)