Certainly, let’s break down functions, function parameters, and built-in functions in Python.
1. Functions
-
Concept: In essence, a function is a reusable block of code designed to perform a specific task. They promote code organization, reusability, and modularity.
-
Structure:
1def function_name(parameter1, parameter2, ...): # Function definition (header)
2 """Docstring (optional): Briefly describe the function."""
3 # Code block to execute (body)
4 # ...
5 return some_value # Optional: Returns a result
- Example:
1def greet(name):
2 """This function greets the person passed in as a parameter."""
3 print(f"Hello, {name}!")
4
5greet("Alice") # Function call
- Key Points:
- Functions are defined using the
def
keyword. - They can accept zero or more parameters (inputs).
- The
return
statement (optional) sends a value back from the function.
- Functions are defined using the
2. Function Parameters (Arguments)
-
Purpose: Parameters act as placeholders for values you want to pass into a function when calling it. They make functions more flexible.
-
Types:
- Positional Parameters: Must be passed in the exact order defined in the function definition.
- Keyword Arguments: Passed with names, allowing you to specify which parameter each value corresponds to.
- Default Parameters: Have predefined values, making them optional during the function call.
-
Example:
1def describe_pet(pet_name, animal_type="dog"):
2 """This function describes a pet."""
3 print(f"I have a {animal_type}.")
4 print(f"My {animal_type}'s name is {pet_name.title()}.")
5
6describe_pet("buddy") # Uses the default 'dog'
7describe_pet("whiskers", "cat") # Keyword argument
3. Built-in Functions
- Definition: Python comes equipped with a set of pre-written, ready-to-use functions that provide common operations.
Basic Functions:
print()
: Displays output on the console.input()
: Takes input from the user.len()
: Returns the length of a sequence (string, list, tuple, etc.).type()
: Returns the type of an object.id()
: Returns the unique identity of an object.help()
: Provides documentation and usage information about Python objects.
Type Conversion Functions:
int()
: Converts a value to an integer.float()
: Converts a value to a floating-point number.str()
: Converts a value to a string.bool()
: Converts a value to a Boolean (True or False).list()
: Converts a sequence to a list.tuple()
: Converts a sequence to a tuple.set()
: Creates a set from a sequence.dict()
: Creates a dictionary from key-value pairs.
Mathematical Functions:
abs()
: Returns the absolute value of a number.round()
: Rounds a number to a specified number of digits.pow()
: Raises a number to a given power.max()
: Returns the largest item in an iterable.min()
: Returns the smallest item in an iterable.sum()
: Returns the sum of all items in an iterable.divmod()
: Returns the quotient and remainder of a division.
Sequence Operations:
sorted()
: Returns a new sorted list from the given iterable.reversed()
: Returns a reverse iterator of a sequence.enumerate()
: Returns an iterator of tuples (index, value) from a sequence.zip()
: Combines elements from multiple iterables into tuples.all()
: Returns True if all elements in an iterable are True.any()
: Returns True if any element in an iterable is True.
File Handling (requires open()
function):
open()
: Opens a file and returns a file object.read()
: Reads the content of a file.write()
: Writes data to a file.close()
: Closes an open file.
Other Important Built-in Functions:
range()
: Generates a sequence of numbers.isinstance()
: Checks if an object is an instance of a specified class.issubclass()
: Checks if a class is a subclass of another class.eval()
: Executes a string as a Python expression.exec()
: Executes a string as Python code.globals()
: Returns a dictionary of the current global symbol table.locals()
: Returns a dictionary of the current local symbol table.
Notes
- Functions encapsulate code for reusability and clarity.
- Parameters provide inputs to functions, enhancing their flexibility.
- Built-in functions offer convenient tools for common tasks, saving you from writing repetitive code.