Understanding Python Functions and Libraries: Definitions, Syntax, Parameters, and Usage
This article explains Python functions and libraries, covering their definitions, syntax, parameter types, docstrings, examples, as well as how to install, import, and use both standard and third‑party libraries with practical code snippets.
Functions are reusable blocks of code in Python defined with the def keyword; they improve code organization, readability, and reusability.
The basic syntax is:
def function_name(parameters):
"""docstring"""
# function body
return [expression]function_name is the identifier, parameters is the optional argument list, and a docstring (optional but recommended) describes the function’s purpose. The return statement provides a result, otherwise the function returns None .
Parameter types include positional parameters, keyword parameters, default values, and variable arguments ( *args and **kwargs ).
Example of a simple greeting function:
def greet(name, greeting="Hello"):
"""Print a greeting message"""
print(f"{greeting}, {name}!")
greet("Alice") # Output: Hello, Alice!
greet("Bob", "Hi") # Output: Hi, Bob!Functions can also return values:
def add(a, b):
return a + b
result = add(3, 5)
print(f"The result is: {result}")Docstrings provide inline documentation and can be accessed via function.__doc__ :
def multiply(x, y):
"""Multiply two numbers and return the result.
:param x: First number.
:param y: Second number.
:return: Product of x and y.
"""
return x * y
print(multiply.__doc__)Variables defined inside a function are local; to modify a global variable, use the global keyword:
x = 10 # global variable
def update_x():
global x
x = 20
update_x()
print(f"Updated global x: {x}")Anonymous functions can be created with lambda for simple, one‑off operations:
add = lambda a, b: a + b
print(add(4, 6)) # Output: 10Libraries (modules) are reusable Python files that can be imported. The standard library includes modules such as os , sys , datetime , and math . Third‑party libraries like numpy , pandas , matplotlib , and requests are installed via pip .
Common import patterns:
# Import entire module
import math
print(math.sqrt(16))
# Import specific name
from datetime import datetime
now = datetime.now()
print(now)
# Alias import
import pandas as pd
# Import all (not recommended)
from math import *Examples of using libraries:
Math module – square root and π:
import math
result = math.sqrt(16)
print(f"Square root of 16 is: {result}")
print(f"Value of pi is: {math.pi}")Datetime module – current date and time:
from datetime import datetime
now = datetime.now()
print(f"Current date and time: {now}")
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(f"Formatted: {formatted}")Requests library – HTTP GET and POST:
import requests
response = requests.get('https://api.github.com')
print(f"Status Code: {response.status_code}")
print(f"Response Content: {response.json()}")
url = 'https://httpbin.org/post'
data = {'key': 'value'}
post_resp = requests.post(url, data=data)
print(f"POST Response: {post_resp.json()}")Pandas – creating, filtering, sorting, and describing a DataFrame:
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
print(df)
filtered = df[df['Age'] > 28]
print(f"Filtered DataFrame:\n{filtered}")
sorted_df = df.sort_values(by='Age', ascending=False)
print(f"Sorted DataFrame:\n{sorted_df}")
stats = df.describe()
print(f"Statistics:\n{stats}")Matplotlib – simple line and bar charts:
import matplotlib.pyplot as plt
# Line plot
x = [1, 2, 3, 4, 5]
y = [2, 3, 5, 7, 11]
plt.plot(x, y, marker='o')
plt.title('Simple Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True)
plt.show()
# Bar chart
labels = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]
plt.bar(labels, values)
plt.title('Bar Chart')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()In summary, defining and using functions involves specifying a name, parameters, an optional docstring, and a body that may return a value; libraries extend Python’s capabilities, and they are installed with pip , imported with import statements, and used through their provided functions and classes.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.