Python Arguments with example

Python arguments are values that are passed into a function when it’s called. There are different types of arguments in Python, including positional arguments, keyword arguments, default arguments, and variable-length arguments. Let’s take a look at each type with an example.

  1. Positional Arguments: Positional arguments are the most common type of argument. They are values that are passed into a function in the order in which they appear in the function definition. Here’s an example:
def greet(name, message):
    print(message + ", " + name + ". How are you?")

greet("John", "Hello")

In this example, the greet function takes two positional arguments: name and message. When we call the function with greet("John", "Hello"), the value “John” is assigned to name and “Hello” is assigned to message. The function then prints the message “Hello, John. How are you?” to the console.

  1. Keyword Arguments: Keyword arguments are values that are passed into a function by specifying the parameter name followed by an equal sign and the value. Keyword arguments can be passed in any order. Here’s an example:
def greet(name, message):
    print(message + ", " + name + ". How are you?")

greet(message="Hello", name="John")

In this example, we’re calling the greet function with two keyword arguments: message="Hello" and name="John". The order doesn’t matter because we’re specifying the parameter names. The function then prints the same message as in the previous example.

  1. Default Arguments: Default arguments are values that are automatically assigned to a parameter if no value is provided when the function is called. Here’s an example:
def greet(name, message="Hello"):
    print(message + ", " + name + ". How are you?")

greet("John")

In this example, we have a default argument message="Hello". This means that if we call the greet function without specifying the message argument, it will automatically use “Hello” as the default value. When we call the function with greet("John"), the output will be the same as in the previous examples.

  1. Variable-length Arguments: Variable-length arguments are used when you don’t know how many arguments will be passed into a function. There are two types of variable-length arguments: *args and **kwargs. Here’s an example:
def greet(*names):
    for name in names:
        print("Hello, " + name + ". How are you?")

greet("John", "Jane", "Bob")

In this example, we’re using the *args syntax to define a variable-length argument names. This means that we can pass in any number of arguments, which will be collected into a tuple inside the function. We’re then using a loop to iterate over the tuple and print a greeting message to each name.

I hope this helps you understand the different types of Python arguments!

Leave a Reply