Skip to Content
👆 We offer 1-on-1 classes as well check now
PythonFunctionsFunction Basics

Function Basics

Functions are a crucial concept in Python programming, allowing you to organize and reuse code. In this section, we will cover the basics of functions, including their syntax, usage, and best practices.

Introduction to Functions

A function is a block of code that can be called multiple times from different parts of your program. It takes in arguments, performs some operations, and returns a value. Functions help to:

  • Reduce code duplication
  • Improve code readability
  • Enhance code maintainability
  • Increase code reusability

Basic Function Syntax

Here’s a simple example of a Python function:

def greet(name: str) -> None: """Prints a personalized greeting message""" print(f"Hello, {name}!") # Call the function greet("John")

In this example, greet is the function name, name is the argument, and str is the type hint for the argument. The -> None syntax indicates that the function doesn’t return any value.

Function Arguments

Functions can take in multiple arguments, which can be positional or keyword-based.

Positional Arguments

Positional arguments are passed in the order they are defined in the function signature.

def add(a: int, b: int) -> int: """Returns the sum of two numbers""" return a + b # Call the function with positional arguments result = add(2, 3) print(result) # Output: 5

Keyword Arguments

Keyword arguments are passed using the argument name.

def greet(name: str, age: int) -> None: """Prints a personalized greeting message with age""" print(f"Hello, {name}! You are {age} years old.") # Call the function with keyword arguments greet(age=30, name="Jane")

Default Argument Values

You can assign default values to arguments using the = syntax.

def greet(name: str, age: int = 25) -> None: """Prints a personalized greeting message with age""" print(f"Hello, {name}! You are {age} years old.") # Call the function with default argument value greet("John")

In this example, if the age argument is not provided, it defaults to 25.

Return Values

Functions can return values using the return statement.

Returning Single Values

def square(x: int) -> int: """Returns the square of a number""" return x ** 2 # Call the function and print the result result = square(4) print(result) # Output: 16

Returning Multiple Values

You can return multiple values using tuples, lists, or dictionaries.

def calculate_stats(numbers: list[int]) -> tuple[float, float]: """Returns the mean and median of a list of numbers""" mean = sum(numbers) / len(numbers) median = sorted(numbers)[len(numbers) // 2] return mean, median # Call the function and print the results numbers = [1, 2, 3, 4, 5] mean, median = calculate_stats(numbers) print(f"Mean: {mean}, Median: {median}")

Best Practices and Tips

  • Use descriptive and concise function names.
  • Use type hints for function arguments and return types.
  • Keep functions short and focused on a single task.
  • Use docstrings to document function behavior and usage.
  • Test functions thoroughly to ensure they work as expected.

Real-World Example

Suppose you’re building a simple banking system, and you want to calculate the interest on a savings account. You can create a function to calculate the interest based on the principal amount, interest rate, and time period.

def calculate_interest(principal: float, rate: float, time: float) -> float: """Returns the interest on a savings account""" interest = principal * rate * time return interest # Call the function with sample values principal = 1000.0 rate = 0.05 time = 2.0 interest = calculate_interest(principal, rate, time) print(f"Interest: {interest}")

In this example, the calculate_interest function takes in the principal amount, interest rate, and time period as arguments and returns the calculated interest. You can call this function with different values to calculate the interest for different scenarios.

Last updated on