CodeBlanks Logo Icon CodeBlanks

Summary - Function parameters

Combine keyword and type hints to write a calculation function.

Summary - Function parameters

In this group we covered positional, keyword, keyword-only, positional-only and type hints.

  • Positional: matches by order.
  • Keyword: passed by name, order irrelevant.
  • Keyword-only: separated by *.
  • Positional-only: separated by /.
  • Type hint: type annotation, not enforced.

Now two tasks combine these concepts.

Practice Type hint and keyword together

Define a function called greet with parameters name: str and greeting: str = "Hello", return type -> None. The body does print(greeting, name). Call it with the keyword call greet(name="Ayse").

Starter code

main.py
# Define the greet function

Sample solution

main.py
def greet(name: str, greeting: str = "Hello") -> None:
    print(greeting, name)
greet(name="Ayse")

Expected output

Hello Ayse

Practice Keyword-only and type hint together

Define a function called create_user with name: str positional, then *, then role: str and active: bool keyword-only parameters, return type -> None. The body does print(name, role, active). Call it with create_user("Ayse", role="admin", active=True).

Starter code

main.py
# Define the create_user function

Sample solution

main.py
def create_user(name: str, *, role: str, active: bool) -> None:
    print(name, role, active)
create_user("Ayse", role="admin", active=True)

Expected output

Ayse admin True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which statement is correct?

  • Type hints slow the code down
  • Positional-only is separated by *
  • Keyword depends on order
  • Keyword-only is separated by * Correct answer

Explanation: Parameters after the star are keyword-only.

2 Complete the positional-only call

Question
result = compute(____, 4)
Answer
result = compute(3, 4)

Explanation: compute(3, 4) is a positional call; a=3 cannot be used.

All lessons in Beginner