23. Understanding positional and keyword arguments

Quiz: 0/5

In Python, you can pass arguments to functions in two primary ways: positional arguments and keyword arguments. Grasping the distinction between these two types of arguments is crucial for writing clear, flexible, and maintainable code.

Positional arguments

Positional arguments are the most common method for passing arguments to a function. The order in which arguments are passed matters because they are assigned to parameters based on their position in the function call.

Example:

def describe_pet(name, species):
    print(f"{name} is a {species}.")

describe_pet("Buddy", "dog")  # Output: Buddy is a dog.
describe_pet("Whiskers", "cat")  # Output: Whiskers is a cat.

Explanation:

  • In the function describe_pet(name, species), Buddy is assigned to name and dog to species based on their position.
  • Changing the order of arguments would alter the output:
    describe_pet("dog", "Buddy")  # Output: dog is a Buddy.
    
    This wouldn’t make logical sense, demonstrating the importance of positional arguments’ order.

Advantages of Positional Arguments:

  • Quick and simple for functions with fewer parameters.
  • Suitable for cases where the argument order is clear and unambiguous.

Limitations:

  • With many parameters, positional arguments can make the function call hard to read and maintain.

Keyword arguments

Keyword arguments allow you to specify the parameter name along with its value when calling a function. This means that the order of arguments doesn’t matter since each argument is explicitly matched to a parameter by name.

Example:

def describe_pet(name, species):
    print(f"{name} is a {species}.")

describe_pet(name="Buddy", species="dog")  # Output: Buddy is a dog.
describe_pet(species="cat", name="Whiskers")  # Output: Whiskers is a cat.

Explanation:

  • The function calls are the same, but the order of the arguments doesn’t matter due to the explicit parameter names.
  • This approach enhances readability and avoids confusion when there are many parameters or when the argument order might not be intuitive.

Advantages of Keyword Arguments:

  • Clearer code, especially when dealing with functions with many parameters.
  • Reduces the risk of errors from passing arguments in the wrong order.

Mixing positional and keyword arguments

You can combine positional and keyword arguments in the same function call. However, positional arguments must appear before keyword arguments.

Example:

def describe_pet(name, species, age):
    print(f"{name} is a {age}-year-old {species}.")

describe_pet("Buddy", "dog", age=5)  # Output: Buddy is a 5-year-old dog.

Explanation:

  • Buddy and dog are positional arguments assigned to name and species, respectively.
  • age=5 is a keyword argument, which explicitly assigns 5 to age.

Note: Trying to place a keyword argument before a positional argument will result in a SyntaxError:

describe_pet(name="Buddy", "dog", 5)  # SyntaxError: positional argument follows keyword argument

Default parameter values with keyword arguments

You can also specify default values for parameters in the function definition. When using keyword arguments, you can choose to override these default values.

Example:

def describe_pet(name, species="dog"):
    print(f"{name} is a {species}.")

describe_pet("Buddy")  # Output: Buddy is a dog.
describe_pet("Whiskers", species="cat")  # Output: Whiskers is a cat.

Explanation:

  • The species parameter has a default value of dog. If no value is provided, it will use this default.
  • You can override the default by specifying a keyword argument, like species="cat".

Advantages of Default Values:

  • Provides flexibility to call functions without specifying every argument.
  • Useful when some parameters are optional, and a sensible default value exists.

Summary

  • Positional arguments: Passed based on their position in the function call, meaning order matters.
  • Keyword arguments: Passed by explicitly naming the parameter, making the order irrelevant and improving readability.
  • Mixing both: You can use both positional and keyword arguments, but positional arguments must come before keyword arguments.
  • Default values: Default values for parameters allow functions to be called with fewer arguments, using keyword arguments to override defaults when necessary.

Using keyword arguments can significantly improve the readability and flexibility of your code, especially when dealing with functions that have multiple parameters or optional arguments.

Hands-On Practise

Exercise: Animal profile function

Create a function create_animal_profile() that accepts the following parameters:

  • name (positional argument): The name of the animal.
  • species (keyword argument with a default value of "dog"): The species of the animal.
  • age (keyword argument with no default value): The age of the animal.
  • color (keyword argument with a default value of "unknown"): The color of the animal.

The function should print the following sentence:

"The animal's name is {name}, it is a {age}-year-old {species} with {color} color."

Instructions:

  1. Call the create_animal_profile() function using only positional arguments for name and age, and keyword arguments for species and color.
  2. Try calling the function with different combinations of positional and keyword arguments to see how the output changes. Ensure you handle the defaults for species and color appropriately.
  3. Use at least one function call where you specify all arguments as keyword arguments.
Output:

Quizzes: 0/5

Question 1:

What is the main difference between positional and keyword arguments in Python?

  • Positional arguments are assigned based on the order, while keyword arguments are assigned based on their parameter name.
  • Positional arguments are always optional, while keyword arguments are mandatory.
  • Positional arguments are assigned based on their type, while keyword arguments are assigned based on their length.
  • Positional arguments are used only in Python 2, while keyword arguments are for Python 3.

Question 2:

What happens if you use keyword arguments after positional arguments in a function call?

  • It works without any issues.
  • It will result in a SyntaxError.
  • The keyword arguments will be ignored.
  • The positional arguments will be ignored.

Question 3:

Which of the following function calls is correct for the function 'describe_pet(name, species)'?

  • describe_pet(name='Buddy', species='dog')
  • describe_pet('Buddy', 'dog')
  • describe_pet(name='Buddy', 'dog')
  • describe_pet('Buddy', species='dog')

Question 4:

What will happen if you call a function with missing required positional arguments?

  • Python will use default values for the missing arguments.
  • Python will throw an error and stop the program.
  • The function will run, but with empty values.
  • The function will return 'None'.

Question 5:

Which function call demonstrates the correct use of default parameter values?

  • describe_pet('Buddy')
  • describe_pet('Buddy', species='cat')
  • describe_pet(name='Buddy')
  • describe_pet('Buddy', species='dog', age=5)

Feedback

Share your thoughts about this lesson

Discussion

Please log in to create a discussion.
Previous lessonCalling FunctionsNext lessonDefault parameter values