w3resource

How do you define a function in Python? Give an example.

Defining Python functions: Syntax and naming rules

In Python, you can define a function using the "def" keyword followed by the function name, parentheses containing optional parameters, and a colon. Function bodies, which contain the code to be executed when the function is called, are indented under their definitions. Here's the syntax for defining a function in Python:

def function_name(parameter1, parameter2, ...):
    # Function body (code block)
    # Indented code executed when the function is called
    # Optionally, return a value using the return statement

Python function example: Multiply two numbers and returns the result

Code:

def multiply_numbers(x, y):
    sum_result = x * y
    return sum_result
# Calling the function and storing the result in a variable
result = multiply_numbers(10, 12)
# Printing the result
print(result)   

Output:

120

In the above example, we defined a function named "multiply_numbers" that takes two parameters 'x' and 'y'. Inside the function, we calculated the product of 'x' and 'y' and returned the result using the return statement. When we called the function with arguments 10 and 12, it returned the product 120, which we printed to the console.

Function name and the rules for naming function in Python

Function names in Python are significant as they serve as identifiers for defined functions. A function's name is used to invoke the code within its body when it is called. In order to make your code more readable and maintainable, you need to choose meaningful and descriptive names for your functions.

Rules for naming Python functions:

  • Valid Characters: Function names may contain letters (a-z, A-Z), digits (0-9), and underscores (_).
  • Start with a Letter or Underscore: Function names must begin with a letter (a-z, A-Z) or an underscore (_).
  • Spaces and special characters are not allowed in function names, such as !, @, #, $, etc.
  • Case Sensitivity: Python uses case-sensitive names, so function names with different cases (e.g., my_function, my_function, my_function) are treated differently.
  • Avoid Using Reserved Keywords: Avoid using Python's reserved keywords (e.g., def, if, else, for, while, etc.).
  • Descriptive and Readable: Choose meaningful and descriptive names that indicate the function's purpose. For better readability, use lowercase letters for function names, and separate multiple words with underscores (e.g., calculate_average, process_data, get_user_input, etc.).

Examples of valid function names:

def find_odds(nums):
    # Function body
    pass
def print_message(message):
    # Function body
    pass
def get_user_input():
    # Function body
    pass
find_odds([1,2,3,4,5])
print_message("Hello")
get_user_input()

Examples of invalid function names:

Code:

# Starts with a digit (invalid)
def 123_sum_numbers(x, y):
    pass

File <unknown>:2
    def 123_sum_numbers(x, y):
           ^
SyntaxError: invalid decimal literal

Code:

# Contains a space (invalid)
def check data(input_data):
    pass
File <unknown>:5
    def check data(input_data):
              ^
SyntaxError: invalid syntax

Code:

# Contains a special character (invalid)
def @calculate_average(numbers_list):
    pass

  File <unknown>:2
    def @calculate_average(numbers_list):
        ^
SyntaxError: invalid syntax

Code:

# Using a reserved keyword (invalid)
def def(x, y):
    pass

  File <unknown>:2
    def def(x, y):
        ^
SyntaxError: invalid syntax


Follow us on Facebook and Twitter for latest update.