Browse Courses

Functions

This document explains Python functions, including built-in and user-defined functions, their syntax, scope, parameters, and practical use cases for code reuse and data processing.

This document explores Python functions, covering built-in and user-defined functions, their syntax, parameters, scope, and practical examples for code reuse and data processing. Readers will learn how to define, call, and document functions, and understand variable scope and common function patterns.


Introduction to Functions

Functions are reusable blocks of code that perform specific tasks. Python provides many built-in functions, and users can define their own to organize and simplify code.


Built-in Functions

Python includes built-in functions such as len, sum, and sorted:

FunctionPurpose
lenReturns the length of a sequence or collection
sumReturns the total of all elements in an iterable
sortedReturns a new sorted list or tuple

Example:

1numbers = [10, 20, 5, 35]
2l = len(numbers)      # l = 4
3s = sum(numbers)      # s = 70
4sorted_numbers = sorted(numbers)  # [5, 10, 20, 35]

Methods vs Functions

  • Functions operate independently and return new results.
  • Methods are called on objects and may modify the object in place.

Example:

1album_ratings = [7, 8, 9, 6]
2sorted_ratings = sorted(album_ratings)  # Returns a new sorted list
3album_ratings.sort()                    # Modifies the original list

Defining User Functions

User-defined functions are created using the def keyword. Functions can accept parameters and return values.

Example:

1def add_one(a):
2    """Returns the input value plus one."""
3    b = a + 1
4    return b
5
6result = add_one(5)  # result = 6

Functions can have multiple parameters:

1def mult(x, y):
2    return x * y
3
4mult(2, 3)        # 6
5mult(10, 3.14)    # 31.4
6mult(2, "Hi")     # "HiHi"

Function Return Values

  • If a function does not have a return statement, it returns None by default.
  • The pass keyword is used for functions with no action.

Example:

1def no_work():
2    pass
3
4print(no_work())  # None

Function Documentation

Document functions using triple quotes at the start of the function body. The help() function displays this documentation.

Example:

1def add_one(a):
2    """Returns the input value plus one."""
3    return a + 1
4
5help(add_one)

Loops in Functions

Functions can include loops for processing data.

Example:

1def print_values(stuff):
2    for i, s in enumerate(stuff):
3        print(i, s)
4
5album_ratings = [7, 8, 9, 6]
6print_values(album_ratings)

Variadic Parameters

Functions can accept a variable number of arguments using *args.

Example:

1def print_names(*names):
2    for name in names:
3        print(name)
4
5print_names("Alice", "Bob", "Charlie")

Variable Scope

  • Global variables are accessible throughout the program.
  • Local variables exist only within the function scope.
  • The global keyword can be used to modify global variables inside functions.

Example:

1date = 2017  # Global variable
2def thriller():
3    date = 1982  # Local variable
4    return date
5
6print(thriller())  # 1982
7print(date)        # 2017

Conclusion

Functions are essential for code reuse, organization, and data processing in Python. Understanding built-in and user-defined functions, parameters, return values, documentation, and scope enables efficient and maintainable programming.


FAQ

  1. To store data permanently
  2. To perform a reusable task with given inputs and produce an output
  3. To display graphics
  4. To manage file operations
  1. Functions are reusable blocks of code that perform specific tasks and can accept inputs to produce outputs.

The function will return the special None object by default, indicating no value is returned.

  1. Methods are called on objects and may modify them
  2. Functions always modify the original object
  3. Functions can operate independently
  4. Methods are similar to functions but are associated with objects
  1. Functions do not always modify the original object; they often return new results.

TermDescription
A. Parameter1. Value returned by a function
B. Return value2. Variable defined in the function header
C. Scope3. Area where a variable is accessible
A-2, B-1, C-3.

The global keyword allows a function to modify a variable defined outside its local scope.

True. The global keyword enables modification of global variables within a function.

Ensure that the parameter names are descriptive and the function’s documentation clearly explains their purpose and expected types.

Variadic parameters allow functions to accept a variable number of arguments, making them flexible for different input scenarios.

The sorted() function returns a new sorted list, while the sort() method modifies the original list in place.

The enumerate() function is most useful for obtaining both the index and value during iteration in a function.

The local variable will shadow the global variable within the function scope, and changes to the local variable will not affect the global variable.