Fundamentals 6 min read

Python Function Basics: Creation, Parameters, and Usage

This tutorial explains how to define and call Python functions, covering various parameter types—including positional, default, *args, and **kwargs—demonstrates return values, the pass statement, and provides a comprehensive example that combines all these concepts.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Function Basics: Creation, Parameters, and Usage

1. Creating a Function and Calling It

Define a simple function using def and call it to produce output.

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

greet("Alice")  # Output: Hello, Alice!

2. Parameters

Functions can accept one or more parameters, which are specified in the definition and supplied when calling the function.

def add(a, b):
    return a + b

result = add(3, 5)
print(result)  # Output: 8

3. Parameter Count

Functions may have a fixed number of parameters or support variable numbers.

def multiply(x, y):
    return x * y

result = multiply(4, 5)
print(result)  # Output: 20

4. Arbitrary Positional Arguments (*args) *args collects any number of positional arguments into a tuple.

def sum_all(*args):
    total = 0
    for num in args:
        total += num
    return total

result = sum_all(1, 2, 3, 4, 5)
print(result)  # Output: 15

5. Keyword Arguments

Keyword arguments let you pass values using name=value pairs.

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

greet(name="Alice", greeting="Hi")  # Output: Hi, Alice!
greet(name="Bob")               # Output: Hello, Bob!

6. Arbitrary Keyword Arguments (**kwargs) **kwargs gathers any number of keyword arguments into a dictionary.

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=30, city="New York")
# Output:
# name: Alice
# age: 30
# city: New York

7. Default Parameter Values

You can assign default values to parameters; they are used when the argument is omitted.

def describe_pet(pet_name, animal_type="dog"):
    print(f"I have a {animal_type} named {pet_name}.")

describe_pet("Willie")               # Output: I have a dog named Willie.
describe_pet("Harry", "hamster")  # Output: I have a hamster named Harry.

8. Passing a List as an Argument

A list can be passed to a function and iterated over.

def print_items(items):
    for item in items:
        print(item)

fruits = ["apple", "banana", "cherry"]
print_items(fruits)
# Output:
# apple
# banana
# cherry

9. Return Values

Functions can return one or multiple values using the return statement.

def get_person_info(name, age):
    return f"Name: {name}", f"Age: {age}"

person_info = get_person_info("Alice", 30)
print(person_info)  # Output: ('Name: Alice', 'Age: 30')

name, age = get_person_info("Alice", 30)
print(name)  # Output: Name: Alice
print(age)   # Output: Age: 30

10. The pass Statement pass acts as a placeholder where a statement is syntactically required but no action is needed.

def my_function():
    pass  # Placeholder for future code

my_function()  # Does nothing

11. Comprehensive Example

This example combines required arguments, *args, and **kwargs to demonstrate their joint usage.

def process_data(required_arg, *args, **kwargs):
    print(f"Required argument: {required_arg}")
    if args:
        print("Additional arguments:")
        for arg in args:
            print(arg)
    if kwargs:
        print("Keyword arguments:")
        for key, value in kwargs.items():
            print(f"{key}: {value}")

process_data("必需的参数", 1, 2, 3, name="Alice", age=30)
# Output:
# Required argument: 必需的参数
# Additional arguments:
# 1
# 2
# 3
# Keyword arguments:
# name: Alice
# age: 30
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonfunctionsprogramming basics
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.