Python Function: Keyword & Positional Arguments

Updated: July 15, 2023 By: Wolf Post a comment

This concise article is about positional and keyword arguments in Python.

Positional arguments

Positional arguments are arguments that are passed to a function by their position or order in the function call. They are assigned to the parameters of the function based on the order they appear in the call. If you change the order of the arguments, you may get a different result or an error.

For example, suppose you have a function like this:

def divide(numerator, denominator):
  return numerator / denominator

Then changing the order of the arguments will give you a different result or an error:

divide(10, 5) # returns 2.0
divide(5, 10) # returns 0.5
divide(10, 0) # returns an error

Keyword arguments

Keyword arguments are arguments that are passed to a function with a name and a value. They allow you to specify the value of a parameter by its name instead of by its position. This can make the code more readable and avoid errors when there are many parameters or optional parameters.

For example, suppose you have a function that prints a greeting message:

def greet(name, message="Hello"):
  print(message + ", " + name + "!")

This function has 2 parameters: name and message. The message parameter has a default value of Hello, so it is optional. You can call this function with keyword arguments like this:

greet(name="Wolf") # Hello, Wolf!
greet(message="Good morning", name="Mr. Turtle") # Good morning, Mr. Turtle!

Notice that you can change the order of the arguments when using keyword arguments as long as you use the correct parameter names.

Mixing positional arguments with keyword arguments

You can also mix positional and keyword arguments, but you have to put the positional arguments before the keyword arguments, like this:

def print_info(name, age, job):
    print(f"Name: {name}, Age: {age}, Job: {job}")

# call function with positional arguments and keyword arguments
print_info("Wolf", 35, job= "Data Scientist")
# Name: Wolf, Age: 35, Job: Data Scientist

That’s it. Happy coding & enjoy your day!

Notify of
Inline Feedbacks
View all comments