Functions

What Are Functions?

  • Functions are blocks of code that perform specific tasks. They can take inputs (arguments) and return outputs.

Why Use Functions?

  • They help organize code, making it reusable and easier to understand.

Basic Function Syntax:

  • Defining a function:

    python
    def function_name(parameters):
        # code to execute
        return value
    

Examples and Exercises:

  1. Introduction to Functions:
    • How to define and call a function:

      python
      def greet(name):
         return (('Hello, ' + name) + "!")
      
      print(greet("Alice"))  
      •  Output: Hello, Alice!
  2. Passing Multiple Arguments (*args):
  3. Keyword Arguments (**kwargs):
  4. Returning Values from a Function:
    • Using the return statement:

      python
      def square(x):
          return x * x
      
      print(square(4))  
      • Output: 16
  5. Returning a Function from Another Function:
    • Higher-order functions:

      python
      def outer_function(msg):
          def inner_function():
              return msg
          return inner_function
      
      my_function = outer_function("Hello")
      print(my_function())  
      • Output: Hello
  6. Recursive Functions:
    • Functions that call themselves:

      python
      def factorial(n):
          if n == 1:
              return 1
          else:
              return n * factorial(n - 1)
      
      print(factorial(5))  
      • Output: 120

Summary:

  • Functions are essential in Python for organizing and reusing code. Understanding how to define, call, and use various types of functions will help you write more efficient and manageable programs. Practice these examples and exercises to become comfortable with functions!