python-backend
/

Python Functions – Writing Reusable & Modular Code

Last Sync: Today

On this page

6
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

python-backend

Python Functions – Writing Reusable & Modular Code

What is a Function?

A function 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. In Python, you define a function using the def keyword.

Defining and Calling Functions

Python uses indentation to define the body of a function. You can pass data, known as parameters, into a function, and it can return data as a result.

PythonRead-only
1
def greet_user(username):
    """Displays a simple greeting."""
    return f"Hello, {username}!"

# Calling the function
message = greet_user("Kishore")
print(message) # Output: Hello, Kishore!

Function Parameters & Arguments

Python offers flexible ways to pass arguments. You can use positional arguments, keyword arguments, and even default values.

  • Default Arguments: Assign a value in the definition if none is provided during the call.
  • Keyword Arguments: Identify arguments by name so order doesn't matter.
  • Arbitrary Arguments (*args): Pass a non-keyworded, variable-length argument list.
  • **Keyworded Arbitrary Arguments (kwargs): Pass a keyworded, variable-length argument list.
PythonRead-only
1
def create_profile(name, role="Developer", **extra_info):
    profile = {"name": name, "role": role}
    profile.update(extra_info)
    return profile

user = create_profile("Kishore", location="Chennai", tech="Flutter")
# Output: {'name': 'Kishore', 'role': 'Developer', 'location': 'Chennai', 'tech': 'Flutter'}

Type Hinting (Modern Python)

Since you are familiar with Dart's static typing, you'll appreciate Python's type hinting. While not enforced by the interpreter, it makes code significantly more maintainable and helps IDEs catch bugs.

PythonRead-only
1
def add_numbers(a: int, b: int) -> int:
    return a + b

Lambda Functions (Anonymous)

Small anonymous functions can be created with the lambda keyword. They are restricted to a single expression.

PythonRead-only
1
square = lambda x: x * x
print(square(5)) # Output: 25

Argument Types Comparison

TypeSyntaxUse Case
Positionaldef func(a, b)Basic, ordered inputs
Defaultdef func(a=1)Optional parameters
*argsdef func(*args)Passing a variable list of items
**kwargsdef func(**kwargs)Passing variable named settings/configs

Try it yourself

def calculate_discount(price, discount_percent=10):
    """Calculates the final price after discount."""
    savings = price * (discount_percent / 100)
    return price - savings

# Try changing the arguments!
initial_price = 1000
final = calculate_discount(initial_price, 25)

print(f"Initial: {initial_price}")
print(f"Final: {final}")

# Lambda example
multiply = lambda a, b: a * b
print(f"5 x 6 = {multiply(5, 6)}")

Test Your Knowledge

Q1
of 3

Which keyword is used to create a function in Python?

A
function
B
def
C
func
D
define
Q2
of 3

What does *args allow you to do?

A
Return multiple values
B
Pass a variable number of positional arguments
C
Force a function to be async
D
Define a private function
Q3
of 3

How do you define a default value for a parameter?

A
def my_func(x? = 10):
B
def my_func(x : 10):
C
def my_func(x = 10):
D
def my_func(default x = 10):

Frequently Asked Questions

What is 'pass' in a function?

If you want to define a function but haven't written the logic yet, you use the 'pass' keyword as a placeholder to avoid syntax errors.

Can a Python function return multiple values?

Yes! You can return a tuple (e.g., return x, y) and then destructure them when calling: a, b = my_func().

What is a docstring?

A docstring is a string literal that occurs as the first statement in a function. It's used to document what the function does and is accessible via help() or doc.

Previous

python control flow

Next

python oop

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.