0
0
Pythonprogramming~20 mins

Variable-length arguments (*args) in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
๐ŸŽ–๏ธ
Variable-length Arguments Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
โ“ Predict Output
intermediate
2:00remaining
Output of function using *args with sum
What is the output of this Python code?
Python
def add_all(*args):
    return sum(args)

result = add_all(1, 2, 3, 4)
print(result)
A10
B1234
CTypeError
DNone
Attempts:
2 left
๐Ÿ’ก Hint
Remember that *args collects all arguments into a tuple and sum adds them up.
โ“ Predict Output
intermediate
2:00remaining
Output when *args is empty
What will this code print?
Python
def greet(*args):
    if args:
        print('Hello, ' + args[0])
    else:
        print('Hello, stranger')

greet()
ATypeError
BHello,
CIndexError
DHello, stranger
Attempts:
2 left
๐Ÿ’ก Hint
Check what happens when no arguments are passed and how the if condition works.
โ“ Predict Output
advanced
2:00remaining
Output of function with *args and unpacking
What is the output of this code?
Python
def multiply(*args):
    result = 1
    for num in args:
        result *= num
    return result

numbers = [2, 3, 4]
print(multiply(*numbers))
A24
B[2, 3, 4]
C9
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
The * operator unpacks the list into separate arguments.
โ“ Predict Output
advanced
2:00remaining
Output when mixing *args with normal parameters
What does this code print?
Python
def describe(name, *args):
    print(f'Name: {name}')
    print(f'Other info: {args}')

describe('Alice', 25, 'Engineer')
A
Name: Alice
Other info: 25, Engineer
B
Name: Alice
Other info: (25, 'Engineer')
C
Name: Alice
Other info: [25, 'Engineer']
DTypeError
Attempts:
2 left
๐Ÿ’ก Hint
Check how *args collects extra arguments as a tuple.
๐Ÿง  Conceptual
expert
2:00remaining
Why use *args in function definitions?
Which of these best explains why *args is used in Python functions?
ATo make the function return multiple values.
BTo force the function to accept exactly one argument.
CTo allow the function to accept any number of positional arguments as a tuple.
DTo collect keyword arguments into a dictionary.
Attempts:
2 left
๐Ÿ’ก Hint
Think about how *args collects arguments.