Python: Create and Call Functions

Python Functions Tutorial

Create and Call Functions in Python

Functions are reusable blocks of code that perform a specific task. They help organize your code, make it more readable, and avoid repetition. In Python, you define functions using the `def` keyword.

Example 1: A Simple Addition Function

Let’s create a function that takes two numbers as input and returns their sum. This is a fundamental example to illustrate the basic structure of a Python function.


def add_numbers(x, y):
    """This function adds two numbers and returns the sum."""
    sum_result = x + y
    return sum_result

# Calling the function
num1 = 10
num2 = 5
result = add_numbers(num1, num2)
print(f"The sum of {num1} and {num2} is: {result}")
    

Explanation:

  • We defined a function named `add_numbers` that takes two arguments, `x` and `y`.
  • Inside the function, we calculate the sum of `x` and `y` and store it in the variable `sum_result`.
  • We use the `return` statement to return the value of `sum_result` back to the caller.
  • We then call the function with `num1` and `num2` as arguments.
  • The returned value is stored in the `result` variable.
  • Finally, we print the result to the console.

Note the use of a docstring (`”””…”””`) to document the function. This is good practice for readability and helps others (and yourself) understand what the function does.

A common mistake is to forget the `return` statement. Without a `return` statement, the function implicitly returns `None`.


# Incorrect Example (missing return)
def subtract_numbers(a, b):
    result = a - b
    print(result)  # This will print the result, but the function doesn't return it

Output:

The sum of 10 and 5 is: 15
    

Example 2: A Function with a Return Value and String Formatting

This example demonstrates how to return a value and use string formatting (f-strings) to create a more user-friendly output. We’ll calculate the area of a rectangle.


def calculate_rectangle_area(length, width):
    """Calculates the area of a rectangle."""
    area = length  width
    return f"The area of a rectangle with length {length} and width {width} is: {area}"

# Calling the function
length = 7
width = 4
area_string = calculate_rectangle_area(length, width)
print(area_string)
    

Explanation:

  • The `calculate_rectangle_area` function takes `length` and `width` as input.
  • It calculates the area by multiplying `length` and `width`.
  • It uses an f-string to create a formatted string that includes the calculated area and the original length and width.
  • It returns the formatted string.
The area of a rectangle with length 7 and width 4 is: 28
    

Example 3: Function with Parameter Validation

This example shows how to validate input parameters to prevent errors. It calculates the factorial of a number, but only if the input is a non-negative integer.


def factorial(n):
    """Calculates the factorial of a non-negative integer."""
    if not isinstance(n, int) or n < 0:
        return "Invalid input: Please provide a non-negative integer."
    elif n == 0:
        return 1
    else:
        result = 1
        for i in range(1, n + 1):
            result = i
        return result

# Calling the function with valid and invalid inputs
print(factorial(5))
print(factorial(-2))
print(factorial(3.14))
    

Explanation:

  • We defined a function named `factorial` that takes one argument, `n`.
  • We first check if `n` is an integer and if it’s non-negative. If not, we return an error message. This is input validation.
  • If `n` is 0, we return 1 (base case for factorial).
  • Otherwise, we calculate the factorial using a loop and return the result.
120
Invalid input: Please provide a non-negative integer.
Invalid input: Please provide a non-negative integer.
    

By incorporating input validation, you make your code more robust and prevent unexpected errors. This is a crucial practice when working with user-supplied data or data from external sources.

Leave a Reply

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

We use cookies and similar technologies to enhance your experience on wobizdu.com, analyze site traffic, personalize content, and deliver relevant ads. Some cookies are essential for the site to function, while others help us improve performance and user experience. You may accept all cookies, decline optional ones, or customize your settings. Review our Privacy Policy to learn more.