Python: Create and Call Functions

Python Functions Tutorial

Python Functions Tutorial

This tutorial will guide you through creating and calling functions in Python. Functions are reusable blocks of code that perform specific tasks. They’re a fundamental building block of well-structured programs.

What are Functions?

Functions are defined using the `def` keyword. They can take inputs (arguments) and return a value. This makes code more modular and easier to understand and maintain.

Example 1: Simple Addition Function

Let’s create a function that adds two numbers.


def add_numbers(x, y):
  """This function takes two numbers as input and returns their sum."""
  sum_result = x + y
  return sum_result

# Calling the function
result = add_numbers(5, 3)
print(result)

Explanation:

  • We define a function called `add_numbers` that accepts 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 send the value of `sum_result` back to the caller.
  • We then call the function with the arguments 5 and 3. The function calculates 5 + 3 = 8.
  • The `return` statement sends the value 8 back to the line where the function was called.
  • Finally, `print(result)` displays the returned value (8) on the console.

Common Beginner Mistake: Forgetting to `return` a value. If you don’t explicitly return a value, the function implicitly returns `None`. This can cause unexpected behavior if you’re expecting a specific result.


def my_function():
  print("Hello")
  # No return statement here - returns None by default

Output:


Hello

Example 2: Function with a Return Value and String Formatting

Now, let’s create a function that calculates the area of a rectangle and returns a formatted string:


def calculate_rectangle_area(length, width):
  """
  Calculates the area of a rectangle and returns a formatted string.
  """
  area = length  width
  return f"The area of the rectangle is: {area}"  # Using f-strings

# Calling the function
area_string = calculate_rectangle_area(10, 5)
print(area_string)

Explanation:

  • The function `calculate_rectangle_area` takes `length` and `width` as arguments.
  • It calculates the area by multiplying `length` and `width`.
  • It uses an f-string (formatted string literal) to create a string that includes the calculated area. F-strings are a concise way to embed variables directly into strings.
  • The `return` statement returns the formatted string.
  • We call the function with length 10 and width 5. The area is 50.
  • The f-string creates the string “The area of the rectangle is: 50”.
  • This string is returned and assigned to the variable `area_string`.
  • Finally, `print(area_string)` displays the formatted string on the console.

The area of the rectangle is: 50

Example 3: Function with Input Validation

Let’s create a function that takes a number as input and returns its square. We’ll add some basic input validation to ensure the input is a number:


def square_number(number):
  """
  Calculates the square of a number.
  Includes basic input validation.
  """
  if not isinstance(number, (int, float)):
    return "Invalid input: Please enter a number."
  return number  number

# Calling the function
result1 = square_number(5)
print(result1)

result2 = square_number("hello")
print(result2)

Explanation:

  • The function `square_number` takes a single argument, `number`.
  • We use `isinstance()` to check if the input is an integer or a float.
  • If the input is not a number, we return an error message.
  • If the input is a number, we calculate its square by multiplying the number by itself.
  • We use the `return` statement to return the square of the number.
  • We call the function with the argument 5. The square is 25.
  • We then call the function with the argument “hello”. The `isinstance` check will fail, and the function will return the error message.

25
Invalid input: Please enter a number.

Best Practices: Input validation is crucial for robust code. It prevents unexpected errors and ensures that your functions handle different types of input gracefully.

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.