Python Tutorial

Python Flow Control

Python Functions

Python Data Types

Python Date and Time

Python Files

Python String

Python List

Python Dictionary

Python Variable

Python Input/Output

Python Exceptions

Python Advanced

Python Functions

In this tutorial, you'll learn how to create and use functions in Python. Functions are reusable blocks of code that perform a specific task. They help to organize your code, make it more modular, and reduce repetition.

  • Defining a function:

To define a function in Python, use the def keyword, followed by the function name, a pair of parentheses containing any input parameters, and a colon. The function's body is indented, and should contain the code to be executed when the function is called.

def greet():
    print("Hello, World!")

# Call the function
greet()
  • Function with parameters:

You can pass input values to a function using parameters. Parameters are specified within the parentheses in the function definition, and you can pass arguments to the function when calling it.

def greet(name):
    print(f"Hello, {name}!")

# Call the function with an argument
greet("Alice")
  • Function with default parameter values:

You can specify default values for parameters, which are used if no argument is provided for that parameter when calling the function.

def greet(name="World"):
    print(f"Hello, {name}!")

# Call the function without an argument
greet()

# Call the function with an argument
greet("Alice")
  • Function with return values:

To return a value from a function, use the return keyword, followed by the value or expression you want to return.

def add(a, b):
    return a + b

# Call the function and store the result
result = add(5, 3)

print(result)  # Output: 8
  • Function with multiple return values:

A function can return multiple values using a tuple.

def divide(a, b):
    quotient = a // b
    remainder = a % b
    return quotient, remainder

# Call the function and store the results
quot, rem = divide(10, 3)

print(f"Quotient: {quot}, Remainder: {rem}")
  • Docstrings:

A docstring is a brief description of a function's purpose and usage. It is placed as the first statement within the function body, enclosed in triple quotes.

def greet(name):
    """
    This function greets the person passed as a parameter.
    :param name: The name of the person to greet
    """
    print(f"Hello, {name}!")

# Call the function with an argument
greet("Alice")

In this tutorial, you learned how to create and use functions in Python. Functions are an essential part of programming, allowing you to write reusable, modular code that is easy to maintain and understand.

  1. How to define a function in Python:

    • Description: Create a basic function in Python.
    • Code:
      def greet(name):
          print(f"Hello, {name}!")
      
      # Call the function
      greet("Alice")
      
  2. Function arguments and parameters in Python:

    • Description: Understand and use function parameters and arguments.
    • Code:
      def add_numbers(a, b):
          return a + b
      
      result = add_numbers(3, 4)
      print(result)
      
  3. Python function return statement:

    • Description: Return values from a function.
    • Code:
      def square(x):
          return x ** 2
      
      result = square(5)
      print(result)
      
  4. Default arguments in Python functions:

    • Description: Set default values for function parameters.
    • Code:
      def power(x, exponent=2):
          return x ** exponent
      
      result1 = power(3)
      result2 = power(3, 3)
      print(result1, result2)
      
  5. Keyword arguments in Python functions:

    • Description: Use keyword arguments for clarity.
    • Code:
      def greet_person(name, greeting="Hello"):
          print(f"{greeting}, {name}!")
      
      greet_person(name="Alice")
      
  6. Python lambda functions:

    • Description: Create anonymous functions using lambda.
    • Code:
      square = lambda x: x ** 2
      result = square(4)
      print(result)
      
  7. Recursive functions in Python:

    • Description: Define functions that call themselves.
    • Code:
      def factorial(n):
          if n == 0 or n == 1:
              return 1
          else:
              return n * factorial(n-1)
      
      result = factorial(5)
      print(result)
      
  8. Variable scope in Python functions:

    • Description: Understand local and global variable scopes.
    • Code:
      global_variable = 10
      
      def my_function():
          local_variable = 5
          print(global_variable, local_variable)
      
      my_function()
      
  9. First-class functions in Python:

    • Description: Treat functions as first-class citizens.
    • Code:
      def square(x):
          return x ** 2
      
      # Assign function to a variable
      my_function = square
      
      result = my_function(3)
      print(result)
      
  10. Anonymous functions in Python:

    • Description: Use anonymous functions with lambda.
    • Code:
      add = lambda x, y: x + y
      result = add(3, 4)
      print(result)
      
  11. Python function decorators:

    • Description: Apply decorators to functions.
    • Code:
      def my_decorator(func):
          def wrapper():
              print("Something is happening before the function is called.")
              func()
              print("Something is happening after the function is called.")
      
          return wrapper
      
      @my_decorator
      def say_hello():
          print("Hello!")
      
      say_hello()
      
  12. Built-in functions in Python:

    • Description: Explore commonly used built-in functions.
    • Code:
      result = len([1, 2, 3])
      print(result)
      
  13. Python map() and filter() functions:

    • Description: Use map() and filter() for iterable transformations.
    • Code:
      numbers = [1, 2, 3, 4, 5]
      squared_numbers = map(lambda x: x ** 2, numbers)
      filtered_numbers = filter(lambda x: x % 2 == 0, numbers)
      
      print(list(squared_numbers))
      print(list(filtered_numbers))
      
  14. Function chaining in Python:

    • Description: Chain multiple function calls together.
    • Code:
      def square(x):
          return x ** 2
      
      def add_one(x):
          return x + 1
      
      result = add_one(square(3))
      print(result)
      
  15. Function closures in Python:

    • Description: Define closures with nested functions.
    • Code:
      def outer_function(message):
          def inner_function():
              print(message)
          return inner_function
      
      my_closure = outer_function("Hello, closure!")
      my_closure()
      
  16. Function annotations in Python:

    • Description: Add annotations to function parameters and return values.
    • Code:
      def add_numbers(a: int, b: int) -> int:
          return a + b
      
      result = add_numbers(3, 4)
      print(result)