CodingNic

Functions and Reusability

Keyword Arguments

Functions and Reusability 20 min read

Keyword Arguments

Keyword Arguments

When calling a function, values are usually matched by position.

But Python also gives another way.

You can send values by name.

This is called keyword arguments.

What Are Keyword Arguments?

Keyword arguments are values passed using the parameter name.

This makes your code clearer and easier to read.

Normal Order Example

python
def user(name, age):
    print(name, age)

user("Sara", 20)

Output

text
Sara 20

Python matches:

  • "Sara" to name
  • 20 to age

Using Keyword Arguments

python
def user(name, age):
    print(name, age)

user(age=20, name="Sara")

Output

text
Sara 20

The order does not matter because the names are used.

Why Keyword Arguments Matter

They help when:

  • A function has many values
  • You want clearer code
  • You want to change the order safely

Another Example

python
def product(name, price):
    print(name, price)

product(price=10, name="Book")

Output

text
Book 10

Mixing Positional and Keyword Values

You can mix them, but positional values must come first.

python
def student(name, age):
    print(name, age)

student("Ali", age=18)

Output

text
Ali 18

Common Beginner Mistake

Wrong order:

python
student(age=18, "Ali")

This causes an error.

Code Along

python
def city(name, country):
    print(name, country)

city(country="Canada", name="Toronto")

Output

text
Toronto Canada

Mini Challenge

Build a profile function.

Steps:

  • Create a function with parameters:
    name, age
  • Print both values
  • Call the function using keyword arguments

Expected output:

text
Maya 25

Real World Use Case

Programs use keyword arguments in forms, settings, reports, and functions with many options.

Quiz

  1. What are keyword arguments?
  2. Do values need normal order when using keywords?
  3. Why are keyword arguments useful?
  4. Which values must come first when mixing types?

Assignment

Create a function called book with parameters title and price. Call it using keyword arguments.

Summary

You learned that keyword arguments send values by parameter name, making function calls clearer and more flexible.