CodeBlanks Logo Icon CodeBlanks

Summary - Functions

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

main.py
# Define the sum_squares function

Sample solution

main.py
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

main.py
# Define the greet function

Sample solution

main.py
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

Question
result = sum_squares(____)
Answer
result = sum_squares(1, 2, 3)

Explanation: sum_squares(1, 2, 3) sends three arguments.

All lessons in Beginner