Python Function Fundamentals Explained with Code Examples

Python Function Fundamentals Explained with Code Examples

Python Function Fundamentals Explained with Code Examples

In this tutorial, I will explain all the fundamentals you should know about Python functions along with syntax and coding examples. 

Just like in any other programming, a function in Python is a block of code that performs a specific task or set of tasks. 

Here’s a basic overview of Python functions:

Defining a Function in Python:

To define a function in Python, use the def keyword followed by the function name and a pair of parentheses. 

Block of the code inside the function is represented using indentation.

Let’s take a simple example of the Python function:

def say_hello():
    print(f"Hello, world!")

You can also pass the argument/s as an input to the function by including the argument variable/s inside the parentheses.

def greet_by_name(name):
    print(f"Hello, {name}!")

Here name is an argument variable.

Having arguments to the function is optional.

The function definition is just a code block and it will not be executed unless the function is called. If you execute the above code examples, you will not see any output.

Let’s see how to call a function in Python.

Calling a Function

To execute the code inside the function, it is required to call that function.

To call a function, mention the function name followed by parenthesis.

# function definition
def say_hello():
    print(f"Hello, world!")

# calling function
say_hello()

Output:

“Hello, world!”

Let’s see the code snippet to call a function that has an argument.

# function definition
def greet_by_name(name):
    print(f"Hello, {name}!")

# calling function
greet_by_name("Anirudh!")

Output:

Hello, Anirudh!

I tried to keep this tutorial simple. I hope you understood it well.

Return Value/s from Function

The function can also return value to use it outside the function. Use return statement to return value from the function.

Let’s modify the above code to return a “Hello, world” message instead of printing it inside the function.

Two changes, you have to consider.

  • Use the return keyword to return function output inside the function block.
  • Assign function output to the variable (say var) in the call function. 

Here is the modified Python program.

def say_hello():
    return "Hello, world!"

var = say_hello()
print(var)

Output:

“Hello, world!”

Let’s take another example.

Write a function that takes two numeric arguments and return the sum of these two numbers.

def add_two_numbers(num_a, num_b):
    val_sum = num_a + num_b
    return val_sum

sum = add_two_numbers(10, 30)
print(f"Sum of two number: {sum}")

Output:

Sum of two number: 40

Python Function to Return Multiple Values

In the previous program, we are returning a single value. The function can also return multiple values.

Write a function that takes two numbers as the function parameters and returns a sum and average of two numbers.

def perform_math_operation(num_a, num_b):
    val_sum = num_a + num_b
    val_avg = (num_a + num_b)/2
    return val_sum, val_avg

sum, avg = perform_math_operation(10, 30)
print(f"Sum of two number: {sum}")
print(f"Average of two number: {avg}")

Output:

Sum of two number: 40
Average of two number: 20

Default Parameters in Function

In function, you can also set the default value to the function parameters.

def greet_by_name(name="Geek"):
    print(f"Hello, {name}!")

print("Output when parameter value is passed.")
greet_by_name("Anirudh!")

print("Output when parameter value is not passed.")
greet_by_name()

Output:

Output when the parameter value is passed.
Hello, Anirudh!

Output when the parameter value is not passed.
Hello, Geek!

Scope of the Function

The scope of the variable or object you use inside the function is limited to the function.

It means that variables inside the function have local scope and they cannot be used outside the function.

Unlikely, the variables defined outside the function have a global scope.

Let’s understand with a simple example.

def sample_function():
    x = 10  # Local variable
    print(f"Local variable value: {x}")

x = 20  # Global variable
sample_function()
print(f"Global variable value: {x}")

Output:

Local variable value: 10

Global variable value: 20

Benefits of Python function

There are several advantages of writing Python function.

  • As functions in any other programming language, Python functions are essential for writing reusable lines of code.
  • It is a very important concept in programming because it allows you to break down your code into smaller and more manageable pieces. 
  • It makes your code more organized, readable, and maintainable.

Standard Naming Convention for Function

  • It’s good practice to name a function that describes the verb or action.
  • The Name can be separated by an underscore (_).

Some good examples of function names are calculate_interest, set_timer, log_message, etc.

These standards are optional and it’s a good practice to follow.

Finally,

In this tutorial, I explained all the fundamental concepts of Python functions. They are very useful in structuring your Python programs and making your code more reusable and modular.

Any doubt? Write me in the comment box below.

Happy Pythoning!

Leave a Reply

Your email address will not be published. Required fields are marked *