Summary - Functions
- Python course
- Beginner
- Lesson 76/116
- 5 min
Combine default, *args and docstring to write a math helper.
Summary - Functions
In this group we covered def, return, docstring, default parameters and *args/**kwargs.
- def defines a function.
- return sends a value; otherwise None.
- Docstring on the first line with triple quotes.
- Default parameters go on the right.
- *args collects tuple, **kwargs collects dict.
Now two tasks combine these concepts.
Practice Sum of squares function
Define a function called sum_squares that takes *nums and returns sum(n * n for n in nums). Assign sum_squares(1, 2, 3) to result. Then print print(result).
Starter code
# Define the sum_squares functionSample solution
def sum_squares(*nums):
return sum(n * n for n in nums)
result = sum_squares(1, 2, 3)
print(result)Expected output
14
Practice Default and docstring together
Define a function called greet with name and greeting (default "Hello") parameters. Put a docstring """Print a greeting message.""" on the first line of the body. Make it print(greeting, name). Call it with greet("Ayse").
Starter code
# Define the greet functionSample solution
def greet(name, greeting="Hello"):
"""Print a greeting message."""
print(greeting, name)
greet("Ayse")Expected output
Hello Ayse
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which statement is correct?
- Without return the function returns True
- *args collects as a tuple Correct answer
- Default parameters go on the left
- Docstring goes after return
Explanation: *args collects variable arguments as a tuple.
2 Complete the function call
result = sum_squares(____)
result = sum_squares(1, 2, 3)
Explanation: sum_squares(1, 2, 3) sends three arguments.