PYTHON

Python Parameters: Syntax, Usage, and Examples

Python parameters allow functions to receive values from a function call. Within the function, parameters become available as variables. Parameters can be of any type, including integers, floats, strings, lists, dictionaries, and even functions.

How to Use Parameters in Python

Parameters in Python go within the parentheses of a function definition. From within the function, parameters are accessible just like variables. Here's the basic syntax for defining a function with parameters:

def function_name(parameter1, parameter2):
	# Function body using parameter1 and parameter2
  • def: The keyword to define a function.
  • function_name: A unique identifier to name your function, following Python's naming conventions.
  • parameter1, parameter2: Variables that represent the inputs the function can accept.

Python Optional Parameters and Default Values

Python allows you to define optional parameters with default values. If the caller does not provide a value, the function uses the default.

def greet(name, message="Hello"):
	print(f"{message}, {name}!")

# Example usage:
greet("Alice")  # Uses the default message "Hello"
greet("Bob", "Goodbye")  # Overrides the default message with "Goodbye"

When to Use Parameters in Python

Parameters make functions more versatile. They are particularly useful in scenarios where the function's behavior needs to vary based on external input.

Handling Different Data

Parameters enable functions to process various data inputs, making them easier to reuse. For example, a function might calculate the square of a number. By using a parameter, the same function can work with any numeric value.

def square(number):
	return number ** 2

# Using the function with different arguments
print(square(4))  # Outputs: 16
print(square(10))  # Outputs: 100

Configuration and Custom Behavior

Parameters allow users to customize the function's behavior without altering the function's code. As an example, consider a function that formats and prints a title, with an optional emphasis parameter:

def print_title(title, underline_char='='):
    print(title)
    print(underline_char * len(title))

# Default underline
print_title("Chapter 1")

# Customized underline
print_title("Conclusion", "-")

Interacting with User Input

Parameters are especially useful in functions that interact with user input, enabling dynamic responses based on the input provided.

def process_user_choice(choice):
    if choice == 1:
        return "You've selected option 1: View Account Balance."
    elif choice == 2:
        return "You've selected option 2: Deposit Funds."
    elif choice == 3:
        return "You've selected option 3: Withdraw Funds."
    else:
        return "Invalid selection. Please choose a valid option."

# Responding to different user choices
print(process_user_choice(1))
print(process_user_choice(4))

Helping With Complex Operations

Parameters can also facilitate more complex operations, such as data handling or processing. Parameters can receive entire data structures (like lists or dictionaries) or control flags that influence the function's execution path.

def analyze_data(data, detailed=False):
	if detailed:
		return {"average": sum(data) / len(data), "max": max(data), "min": min(data)}
	else:
		return sum(data) / len(data)

# Basic analysis
print(analyze_data([10, 20, 30]))

# Detailed analysis
print(analyze_data([10, 20, 30], detailed=True))

Examples of Python Parameters

Data Analysis Functions

In data science, functions might take datasets as parameters to perform computations like averages or sums.

def calculate_average(values):
	return sum(values) / len(values)

# Passing a list as a parameter
average = calculate_average([1, 2, 3, 4, 5])

Web Development with Parameters

In web development, view functions often accept parameters to generate dynamic content based on user input or request details.

def user_profile(request, username):
	# Logic to display the user's profile using the username parameter

Command-Line Tools

When developing command-line tools, parameters allow you to specify options and arguments that control the tool's behavior.

import sys

def process_command(args):
	for arg in args:
		print(f"Processing {arg}")

# Using command-line arguments as parameters
process_command(sys.argv[1:])

Learn More About Python Parameters

Parameters vs. Arguments

In Python, the terms "parameters" and "arguments" are related but distinct. Parameters refer to the variables as defined in the function definition. They represent the data that the function expects when it executes. Arguments are the actual values or data you pass to the function when you call it.

def print_message(message):  # 'message' is a parameter
	print(message)

print_message("Hello, World!")  # "Hello, World!" is an argument

Using args for Variable-Length Arguments

The *args parameter allows a function to accept an arbitrary number of positional arguments. These arguments become accessible as a tuple called args within the function.

def add_numbers(*args):
	return sum(args)  # 'args' is a tuple of all passed arguments

# Example usage:
total = add_numbers(1, 2, 3, 4)
print(total)  # Outputs: 10

Leveraging kwargs for Arbitrary Keyword Arguments

Similarly, **kwargs allows a function to accept an arbitrary number of keyword arguments. Instead of a tuple, however, these arguments become accessible as a dictionary called kwargs within the function.

def print_pet_names(**kwargs):
	for pet, name in kwargs.items():
		print(f"{pet}: {name}")

# Example usage:
print_pet_names(dog="Buddy", cat="Whiskers", fish="Nemo")

Type Hints for Clarity

Type hints in Python provide a syntax for adding type annotations to function parameters and return values. While Python never enforces type hints at runtime, using them can significantly improve code readability, maintainability, and IDE support.

The following type hints clarify that the function expects string and integer parameters and returns a string:

def greet(name: str, age: int) -> str:
    return f"Hello, {name}. You are {age} years old."

Using Complex Data Structures as Parameters

Python can accept complex data structures such as lists, tuples, dictionaries, and custom objects as function parameters. This capability allows you to construct versatile functions capable of handling a wide variety of data types.

def process_data(data: list):
	for item in data:
		print(item)

# Passing a list as an argument
process_data([1, 2, 3, 4])

When using complex data structures as parameters, it’s a good idea to use type hints to clarify the expected structure of the parameters. Also, try to document such functions, explaining the purpose and structure of each parameter.

Learn to Code in Python for Free
Start learning now
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2023 Mimo GmbH