Functions, Docstrings/shaare/r7T2Ww
Functions
Functions package reusable code into named blocks, improving modularity, readability, and testability. They prevent duplication (DRY) and make scripts easier to maintain.
Defining a Function (def)
Use def name(params): followed by an indented block. An optional """docstring""" explains purpose, parameters, and return value.
def greet_user(name):
"""Greets the user by name.
Args:
name (str): The user to greet
"""
print(f"Hello, {name}!")
greet_user("Alice")
Calling a Function
Invoke via name(args). Control jumps into the function body and (optionally) returns a value back.
import random
def random_number(min_val, max_val):
"""Generates an integer between min_val and max_val
Args:
min_val (int): The lower boundary of the interval
max_val (int): The upper boundary of the interval
Returns:
int: The generated random number
"""
return random.randint(min_val, max_val)
generated_number = random_number(0, 10)
print(f"Generated number: {generated_number}")
Parameters vs Arguments
Summary: Parameters are named in the def signature; arguments are the actual values passed when calling.
generated_number = random_number(-1, 100)
Positional vs Keyword Arguments
Positional args match by order; keyword args match by name and can be out of order. Positional arguments must come first.
def check_service_status(service_name, expected_status):
print(f"Checking {service_name} for {expected_status}...")
return True
check_service_status("nginx", "running")
check_service_status("running", "nginx")
check_service_status(service_name="nginx", expected_status="running")
check_service_status(expected_status="running", service_name="nginx")
# Positional arguments must come before keyword arguments
# check_service_status(service_name="nginx", "running") # Uncommenting raises a SyntaxError
Default Parameter Values
It's possible to give parameters default values in the signature (param=default), making them optional.
def connect(host, port=22, timeout=30):
print(f"Connect to host {host} on port {port} (timeout {timeout})")
connect("web01")
connect("web02", 443, 60)
# When wanting to set the value of timeout but use the default value of port
# We need to use keyword arguments, since positional arguments would be
# incorrectly mapped
# Bad exaple - see how port is set to 60 and timeout remains 30
connect("web03", 60)
# Good example - both values are set as we expect
connect("web03", timeout=60)
Docstrings – Documenting Functions
The first string in a function is its docstring, explaining purpose, Args: and Returns:. Used by help() and IDEs. Observing the following conventions is considered good practice:
- One-line summary
- Blank line
- Detailed description (optional)
Args:section for parametersReturns:section for return valuesRaises:section for exceptions
import socket
def check_port(host, port, timeout=5):
"""Checks if a TCP port is open on a given host.
Args:
host (str): Hostname or IP address.
port (int): TCP port number.
timeout (int, option): Connection timeout in seconds. Defaults to 5.
Returns:
bool: True if the port is open, False otherwise.
"""
try:
with socket.create_connection((host, port), timeout):
return True
except Exception:
return False
print(check_port("www.google.com", 443))
# Port 22 is not open, should return False
print(check_port("www.google.com", 22))
# Host does not exist, should return False
print(check_port("www.afbdoaubfdoabdfoubaf.com", 22))
(97)