Functions

In this class, we’ll delve into functions, which are reusable blocks of code that can be called from other parts of the program.

Advantages of using functions Link to heading

  • They allow the code to be divided into smaller, more manageable parts.
  • They make the code more readable and easier to understand.
  • They allow code to be reused in different parts of the program.
  • They help avoid code duplication.

Definition of a function Link to heading

def function_name(parameters):
    """Function documentation"""

    code block

Example: Link to heading

def greet(name):
    """Function that prints a personalized greeting."""

    print(f"Hello {name}!")

greet("Ana")
greet("John")

Exit: Link to heading

Hello Ana!
Hello John!

In this example:

  • A function called greet is defined that receives a parameter called name.
  • The function prints a custom greeting using the name passed to it as a parameter.
  • The function is called twice with different names as arguments.

Arguments and default values Link to heading

  • Functions can have arguments, which are variables that are passed to the function when it is called.
  • Arguments can have default values, which are used if they are not passed a value when calling the function.

Example: Link to heading

def greet(name="Guest"):
    """Function that prints a personalized greeting."""

    print(f"Hello {name}!")

greet()
greet("Ana")

Exit: Link to heading

Hello Guest!
Hello Ana!

In this example:

  • The greet function has an argument called name with a default value of “Guest”.
  • If a value is not passed when calling the function, the default value is used.
  • If a value is passed when calling the function, that value is used instead of the default value.

Return values Link to heading

Functions can return values ​​using the return keyword.

Example: Link to heading

def add(a, b):
    """Function that adds two numbers and returns the result."""

    return a + b

result = add(1, 2)

print(result)

Exit: Link to heading

3

In this example:

  • The add function receives two arguments and returns the sum of the two numbers.
  • The result of the function is saved in the variable result.
  • The variable result is printed to show the value returned by the function.

Exercise Link to heading

Write a function that determines if a number is prime.

<< Loops Classes and Objects >>