The *args
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 42 of 64.
The *args parameter allows a method to accept any number of positional arguments. The asterisk collects all extra positional arguments into a tuple.
Here is an example of a method using *args:
class Calculator:
def add_numbers(self, *args):
return sum(args)
def show_numbers(self, *args):
for i, num in enumerate(args):
print(f"Number {i+1}: {num}")Call the method with different numbers of arguments:
calc = Calculator()
result1 = calc.add_numbers(1, 2, 3)
result2 = calc.add_numbers(10, 20, 30, 40, 50)
print(result1) # 6
print(result2) # 150The *args collects all arguments into a tuple:
calc.show_numbers(5, 10, 15, 20)Output:
Number 1: 5
Number 2: 10
Number 3: 15
Number 4: 20Combine regular parameters with *args:
class Logger:
def log_message(self, level, *messages):
print(f"[{level}]", end=" ")
for message in messages:
print(message, end=" ")
print() # New line
logger = Logger()
logger.log_message("INFO", "User", "logged", "in")
logger.log_message("ERROR", "Connection", "failed")Use *args in constructor methods:
class Team:
def __init__(self, team_name, *players):
self.team_name = team_name
self.players = list(players)
def show_team(self):
print(f"Team: {self.team_name}")
for player in self.players:
print(f"- {player}")
team = Team("Warriors", "Alice", "Bob", "Charlie", "Diana")
team.show_team()Output:
6
150
Number 1: 5
Number 2: 10
Number 3: 15
Number 4: 20
[INFO] User logged in
[ERROR] Connection failed
Team: Warriors
- Alice
- Bob
- Charlie
- DianaYou can also unpack arguments when calling methods:
numbers = [1, 2, 3, 4, 5]
result = calc.add_numbers(*numbers) # Unpacks the list
print(result) # 15Key Point: *args collects any number of positional arguments into a tuple. Use it when you don't know how many arguments will be passed to a method. The name args is conventional - you could use any name after the asterisk, but args is the standard.
Challenge
EasyIn this challenge, you'll implement a flexible number utility function.
Edit the number_utils.py file to implement the sum_all_numbers function that accepts any number of numeric arguments and returns their sum. The function should:
- Return 0 if no arguments are provided
- Print "Error: All arguments must be numbers" and return None if any non-numeric arguments are provided
The number_utils.py file contains detailed TODO comments to guide your implementation. Follow these comments carefully to ensure your solution meets all requirements.
Cheat sheet
The *args parameter allows a method to accept any number of positional arguments. The asterisk collects all extra positional arguments into a tuple.
Basic usage of *args:
class Calculator:
def add_numbers(self, *args):
return sum(args)
calc = Calculator()
result1 = calc.add_numbers(1, 2, 3) # 6
result2 = calc.add_numbers(10, 20, 30, 40, 50) # 150Combine regular parameters with *args:
class Logger:
def log_message(self, level, *messages):
print(f"[{level}]", end=" ")
for message in messages:
print(message, end=" ")
print()
logger = Logger()
logger.log_message("INFO", "User", "logged", "in")Use *args in constructor methods:
class Team:
def __init__(self, team_name, *players):
self.team_name = team_name
self.players = list(players)
team = Team("Warriors", "Alice", "Bob", "Charlie")Unpack arguments when calling methods:
numbers = [1, 2, 3, 4, 5]
result = calc.add_numbers(*numbers) # Unpacks the listKey Point: *args collects any number of positional arguments into a tuple. The name args is conventional but you can use any name after the asterisk.
Try it yourself
from number_utils import sum_all_numbers
# Comprehensive test case handler
test_case = input()
if test_case == "basic_test":
# Test basic functionality with positive integers
print(sum_all_numbers(1, 2, 3)) # Should return 6
print(sum_all_numbers()) # Should return 0
print(sum_all_numbers(10, 20, 30, 40)) # Should return 100
print(sum_all_numbers(1, 2, "three")) # Should print error and return None
elif test_case == "float_test":
# Test with floating point numbers
print(sum_all_numbers(1.1, 2.2, 3.3)) # Should return 6.6
print(sum_all_numbers(5.5, 5.0)) # Should return 10.5
elif test_case == "mixed_numbers_test":
# Test with a mix of integers and floats
print(sum_all_numbers(5, 5.5)) # Should return 10.5
print(sum_all_numbers(10, 20.5, 30, 40)) # Should return 100.5
elif test_case == "zero_values_test":
# Test with zero values
print(sum_all_numbers(0, 0, 0)) # Should return 0
print(sum_all_numbers(0)) # Should return 0
print(sum_all_numbers()) # Should return 0
elif test_case == "negative_values_test":
# Test with negative values
print(sum_all_numbers(-1, -2, -3)) # Should return -6
print(sum_all_numbers(-5, -5)) # Should return -10
print(sum_all_numbers(-5, 5)) # Should return 0
elif test_case == "large_values_test":
# Test with very large values
print(sum_all_numbers(1000000000, 1000000000)) # Should return 2000000000
print(sum_all_numbers(1000000000, 2000000000.5)) # Should return 3000000000.5
elif test_case == "single_value_test":
# Test with a single value
print(sum_all_numbers(5)) # Should return 5
print(sum_all_numbers(-10)) # Should return -10
print(sum_all_numbers(3.5)) # Should return 3.5
elif test_case == "error_handling_test":
# Test with various non-numeric values
print(sum_all_numbers("string")) # Should print error and return None
print(sum_all_numbers([1, 2, 3])) # Should print error and return None
print(sum_all_numbers({"key": "value"})) # Should print error and return None
print(sum_all_numbers(True)) # Should print error and return None
print(sum_all_numbers(None)) # Should print error and return None
elif test_case == "mixed_valid_invalid_test":
# Test with a mix of valid and invalid values
print(sum_all_numbers(1, 2, "three")) # Should print error and return None
print(sum_all_numbers(1, [2, 3], 4)) # Should print error and return None
print(sum_all_numbers(1.5, "two", 3)) # Should print error and return None
elif test_case == "empty_args_test":
# Test with no arguments
print(sum_all_numbers()) # Should return 0This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes