Master Python’s Variable and Keyword Arguments: Simplify Your Functions
Learn how Python’s flexible function parameters—default, variable (*args), and keyword (**kwargs) arguments—enable you to create versatile functions, with clear examples showing how to define, call, and simplify code using lists, tuples, and dictionaries for more powerful and concise programming.
1. Introduction
Python function definitions are simple yet extremely flexible. Besides required positional parameters, you can use default parameters, variable arguments, and keyword arguments, allowing functions to handle complex inputs while keeping call sites concise.
2. Variable Arguments
Variable arguments allow a function to accept any number of positional arguments, including zero. Example: calculating a² + b² + c² + ….
One way is to pass a list or tuple:
def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sumCalling the function requires assembling a list or tuple:
print(calc([1, 2, 3])) # result: 14
print(calc((1, 3, 5, 7))) # result: 84Using *args simplifies the call:
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sumNow the function can be called with any number of arguments, even none:
print(calc(1, 2)) # result: 5
print(calc()) # result: 0If you already have a list or tuple, you can unpack it with *:
nums = [1, 2, 3]
calc(*nums)3. Keyword Arguments
Keyword arguments (**kw) let a function accept any number of named parameters, which are collected into a dictionary.
def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)Calling with only required arguments:
person('Michael', 30)Calling with additional keyword arguments:
extra = {'city': 'Beijing', 'job': 'Engineer'}
person('Jack', 24, **extra)Keyword arguments are useful for extending function capabilities, such as handling optional fields in a user registration function.
4. Summary
This article, based on Python fundamentals, introduced the flexible parameter types of Python functions, including variable arguments and keyword arguments, and demonstrated their usage through practical examples. Understanding these concepts helps write more adaptable and concise code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
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.
