On this page
Functions and Modules in Python
Defining Functions
Functions are reusable blocks of code that perform a specific task. You define a function using the def
keyword.
Syntax:
def function_name(parameters):
# code block
return value # optional
Example:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
Function Arguments and Return Values
- Arguments: Inputs to the function, specified within the parentheses when the function is called.
- Positional Arguments: Arguments passed to the function in the correct order.
- Keyword Arguments: Arguments passed with the name of the parameter.
- Default Arguments: Arguments that assume a default value if a value is not provided.
Example:
def add(a, b=5):
return a + b
print(add(3)) # Uses default value for b
print(add(3, 7)) # Overrides default value
- Return Values: The value that a function sends back to the caller using the
return
statement. If no return statement is used, the function returnsNone
by default.
Example:
def multiply(a, b):
return a * b
result = multiply(2, 3)
Lambda Functions
Lambda functions are small anonymous functions defined using the lambda
keyword. They can have any number of arguments but only one expression.
Syntax:
lambda arguments: expression
Example:
add = lambda x, y: x + y
print(add(3, 5))
Importing Modules
Modules are files containing Python code that can be imported into your script to reuse functions, variables, and classes.
- Importing a Module:
import module_name
- Importing Specific Functions:
from module_name import function_name
- Importing with an Alias:
import module_name as alias
Example:
import math
print(math.sqrt(16))
from math import pi
print(pi)
Standard Library Overview
Python’s standard library is a collection of modules and packages that come with Python, providing various functionalities out of the box.
- Common Modules:
os
: Operating system interfaces.sys
: System-specific parameters and functions.math
: Mathematical functions.datetime
: Date and time manipulation.random
: Random number generation.json
: JSON serialization and deserialization.
Example:
import datetime
today = datetime.date.today()
print("Today's date:", today)
Let me know if you need more details or specific examples!