We are thrilled to inform you that Lancecourse is becoming INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Positional and Keyword Arguments

In this lesson, you'll learn two ways of passing arguments into functions in Python:

  • Positional arguments – where the order matters
  • Keyword arguments – where the name matters

Understanding this makes your functions more flexible and your code easier to read.


Positional Arguments

These are the most common. The values are passed to the function in the same order the parameters are defined.

Example:

def greet(name, age):
    print(f"Hello {name}, you are {age} years old.")

greet("Alice", 25)  # name = "Alice", age = 25

If you switch the order:

greet(25, "Alice")  # name = 25, age = "Alice"

The function still runs, but now the meaning of the values is incorrect.

Keyword Arguments

With keyword arguments, you explicitly mention the parameter name in the function call.

Example:

greet(age=25, name="Alice")
  • The order doesn't matter now because you're specifying what each value is for.

This can be useful when:

  • You have many parameters.
  • You want your code to be more readable.
  • You want to skip certain default parameters.

Mixing Positional and Keyword Arguments

You can combine both, but the positional arguments must come first.

Valid

greet("Alice", age=25)

Invalid

greet(name="Alice", 25)  # ? SyntaxError

Real-Life Example

Let’s say you have a function to create a profile:

def create_profile(name, age, country="Ghana"):
    print(f"{name} is {age} years old and lives in {country}.")

You could call it like:

create_profile("Ahmed", 30)
create_profile("Nana", 28, "USA")
create_profile(age=45, name="Kwame", country="Canada")

Common Mistakes

  • Mixing keyword and positional in the wrong order.
  • Forgetting which parameter comes first in positional arguments.
  • Typos in keyword names.

Exercise: Try It Yourself!

Create a function order_food(item, quantity, price) that prints the total cost:

# Sample call:
order_food("Pizza", 2, 5)               # Positional
order_food(quantity=3, item="Rice", price=4)  # Keyword

Add another version where price has a default value of 10, and try:

order_food("Burger", 2)                # Uses default price

Summary

Concept Description
Positional Arguments Order matters.
Keyword Arguments Specify parameter names, order doesn’t matter.
Mixing Rules Positional must come before keyword arguments.