Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Connexion

Functions, Docstrings/shaare/r7T2Ww

  • python
  • python

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:

  1. One-line summary
  2. Blank line
  3. Detailed description (optional)
  4. Args: section for parameters
  5. Returns: section for return values
  6. Raises: 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))
3 months ago Permalien
cluster icon
  • Functions: return vs yield : Functions: return vs yield Regular functions execute immediately, run to completion, and return a single value (or None). Generator functions retur...
  • Numbers, strings : Numbers (int and float) int: Whole numbers (e.g., 10, 1024). No overflow due to arbitrary precision. float: Numbers with decimals (e.g., 3.14159). Us...
  • Enhancing Functions: Decorators : Enhancing Functions: Decorators A decorator is a callable that takes another function, adds behaviour before and/or after it runs, and returns a new ...
  • Regex : Regex Essentials: Overview Regular expressions (regex) are a language for defining text search patterns. Python’s re module provides functions like...
  • Lambda Functions : Lambda Functions Python functions defined with def allow multiple statements, clear naming, and support for docstrings, making them ideal for complex...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli