Member-only story

A function in Python

Elshad Karimov
2 min readApr 6, 2024
Photo by Jae Park on Unsplash

A function in Python is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. They are defined using the def keyword, can take parameters, and can return values.

Example 1: Defining and Calling a Simple Function

Let’s define a simple function that takes two numbers as arguments and returns their sum:

def add_numbers(num1, num2):
return num1 + num2

# Calling the function
result = add_numbers(10, 15)
print(result) # Output: 25

In this example, add_numbers is a function that:

  1. Is defined using the def keyword followed by the function name and parameters in parentheses.
  2. Takes two parameters, num1 and num2.
  3. Returns the sum of the parameters using the return statement.

When add_numbers(10, 15) is called, the function is executed with num1 as 10 and num2 as 15, and the function's return value is assigned to the variable result.

Example 2: Function with Default Parameters

Functions in Python can also have default parameter values. These are used if no argument value is passed during the function call.

--

--

Elshad Karimov
Elshad Karimov

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet