In this tutorial, we are going to see how to create a function in python.

Python functions:

Being able to write code that we can call multiple times without repeating ourselves is one of the most powerful things that we can do when programming. That is where we implement basic code reusability that can be achieved by implementing the functions.

Let’s learn how to define functions in Python.

Python Function Definition:

We can create functions in Python using the following:

  1. The def keyword
  2. The function name – lowercase starting with a letter or underscore (_)
  3. Left parenthesis (
  4. 0 or more parameter names
  5. Right parenthesis )
  6. A colon :
  7. An indented function body

function without parameters:

Here’s an example without any parameters:

>>> def hello_world():
... print("Hello, World!")
...
>>> hello_world()
Hello, World!
>>>

function with parameters:

If we want to define a parameter, we will put the variable name we want it to have within the parentheses:

>>> def print_name(name):
... print(f"Name is {name}")
...
>>> print_name("Chandra")
Name is Chandra

Let’s try to assign the value from print_name to a variable called output:

>>> output = print_name("Chandra")
Name is Chandra
>>> output
>>>

Neither of these examples has a return value, but we will usually want to have a return value unless the function is our “main” function or carries out a “side-effect” like printing. If we don’t explicitly declare a return value, then the result will be None (as you saw when our body used print).

We can declare what we’re returning from a function using the return keyword:

>>> def add_two(num):
... return num + 2
...
>>> result = add_two(2)
>>> result
4

function with multiple parameters:

When we have a function that takes multiple parameters, we need to separate them using commas and give them unique names:

>>> def add(num1, num2):
... return num1 + num2
...
>>> result = add(1, 5)
>>> result
6

References:

Happy Learning 🙂

Leave A Comment