PYTHON Tutorial

Python Functions

Defining a Function:

  • Use the def keyword followed by the function name and parentheses.
  • Example: def add_numbers(num1, num2):

Function Parameters:

  • Parameters are placeholders that receive values when the function is called.
  • Can be specified within the parentheses in the function definition.
  • Example: num1 and num2 are parameters in add_numbers().

Return Values:

  • Functions can return a value using the return keyword.
  • Return type is not explicitly specified.
  • Example: return num1 + num2 returns the sum of the two parameters.

Scope:

  • Variables defined within a function are local to that function.
  • Local variables cannot be accessed outside the function.
  • Global variables can be accessed from within a function.

Example:

def add_numbers(num1, num2):
    """Adds two numbers and returns the sum."""
    sum = num1 + num2
    return sum

result = add_numbers(3, 5)
print(result)  # Output: 8

Key Points:

  • Functions allow you to break down code into reusable modules.
  • Functions can be used to perform specific tasks and return values.
  • Scope rules govern the visibility and accessibility of variables within functions.
  • Understanding functions is essential for effective Python programming.