Function with Parameters

The true potential of a function becomes apparent when it can receive data from the user. This data can change how the function behaves, making it more versatile and capable of adapting to different situations.

A parameter in a function is similar to a variable, but it has two important characteristics:

  • Parameters exist only within the function where they are defined. They cannot be accessed from outside the function. To define a parameter, it must be declared between the parentheses in the def statement.
  • The value of a parameter is assigned when the function is called, by providing a specific argument that corresponds to the parameter. This argument determines the initial value of the parameter inside the function.
def function(parameter):
  ###

Remember!

  • Parameters reside within functions and are designed to be used inside them. It's their natural environment.
  • On the other hand, arguments exist outside functions and carry values that are passed to the respective parameters.
  • There is a distinct boundary between these two worlds, keeping them separate and clear.

Now, let's break down the process of adding a parameter to a function and using it in our code, step by step.

Adding a Parameter to a Function

Let’s say we want to create a new function called laugh() that display laugh 'Ha!' as shown below:

def laugh():
   print(“Ha!”)

laughing emoticon

Now, we will enhance this function by adding a parameter called num. And then, we will call the function and see the output. let's run the code.

def laugh(num):
  print("Ha!")

laugh(3)

The laugh function has been defined with a parameter called num. However, in the current implementation, the num parameter is not being used within the function's body. Instead, the function simply prints "Ha!" when called.

When we call the laugh(3) statement, the function is invoked with the argument 3. Although the num parameter exists in the function definition, it is not utilized within the function's logic. As a result, the output of the code will be:

OUTPUT:

In this case, the value of num does not have any effect on the output because it is not used within the function. Thus, regardless of the value passed as an argument when calling the function, it will always print "Ha!".

In the previous example, we used the parameter, but it's important to note that we didn't assign any value to it explicitly. However, this is perfectly fine.The value for the parameter will be provided from the function's environment when it is invoked.

It's essential to remember that when defining a function, specifying one or more parameters is a requirement. And when you invoke the function, you must fulfill this requirement by providing arguments that correspond to the defined parameters.

Failing to provide the required number of arguments will result in an error. For instance:

def laugh(num):
  print("Ha!")

laugh()

The above code will resulted in error. When you attempt to call the laugh() function without providing the required argument, it will result in a TypeError. The error occurs because the function definition specifies that the num parameter is required, meaning the function depends on receiving a value for num in order to execute correctly.

Invoking the Function with Parameter

baby laughing

Now, let us enhance the function by utilizing the num value. Let's say, in this case, we want to display the number of times, maybe a baby laughs which is represented by num. Inside the function, we print the provided number of laughs along with a message. Then, using a loop, we print "Ha!" as many times as specified by the num parameter. To accomplish this, we need to modify the "def" statement. Here's the updated version:

def laugh(num):
 for i in range(num):
  print("Ha!", end=" ")

laugh(3)

Note: The parameter end= takes care of removing the newline that is added by default in print()

The laugh function is defined to take one parameter called num. When the function is invoked, it enters a loop that iterates num times. During each iteration, it prints "Ha!" to the console.

In the last line of the code, laugh(3) is called, passing the argument 3 to the laugh function. This means that the function will be executed with num set to 3. As a result, the function will iterate three times in the for loop, printing "Ha!" on each iteration.

The output of the code will be:

OUTPUT:

Since num is 3, the for loop iterates three times, printing "Ha!" on each iteration. This demonstrates how the function can be invoked and the behavior of the loop based on the value of the num parameter provided during the function call.

By passing different values to laugh, we can control the number of "Ha!" prints in the output. For example, laugh(5) would print "Ha!" five times. The num parameter allows flexibility in customizing the behavior of the laugh function.

Shadowing Variables in Function Parameters

In Python, it is important to understand the concept of shadowing variables when working with function parameters. Shadowing occurs when a variable in a function's parameter list has the same name as a variable outside the function. Let's explore this phenomenon with some examples:

def message(number):
print("Enter a number:", number)

number = 1234
message(1)
print(number)

In the code snippet above, we define a function called message with a parameter named number. Outside the function, we also have a variable named number with a value of 1234. When we invoke the message function with the argument 1, it creates a local scope for the parameter number. The parameter number inside the function is a different entity from the variable number outside the function. This behavior is known as shadowing.

As a result, the code produces the following output:

OUTPUT:

You can see that the print(number) statement outside the function refers to the variable number defined outside the function's scope, while the print("Enter a number:", number) statement inside the function refers to the parameter number defined within the function.

It's important to note that a function can have multiple parameters, each with its own name and purpose. Let's modify the message function to include two parameters:

def message(what, number):
print("Enter", what, "number", number)

Now, invoking the message function requires two arguments. The first parameter, what, is intended to carry the name of the desired value.

Here's an example of how to use the modified function:

message("telephone", 11)
message("price", 5)
message("number", "number")

When you run the code, you'll see the following output:

OUTPUT:

Feel free to modify the code, add more parameters, and observe how it affects the output. However, keep in mind that as the number of parameters increases, it becomes more challenging to remember their roles and purposes.

Understanding shadowing and working with parameters allows you to write more flexible and adaptable functions in Python

Positional Argument Passing in Python

Positional argument passing is a technique in Python that involves assigning arguments to function parameters based on their position or order. With positional argument passing, each argument is matched with the corresponding parameter based on its position. This approach is commonly referred to as using positional arguments.

Argument Vs Parameter

While Python offers additional capabilities beyond basic positional parameter passing, it's important to understand the distinction between positional arguments and positional parameters. Positional arguments are the actual values passed to a function based on their position in the function call, while positional parameters are the placeholders defined in the function's parameter list to receive those values. For instance, let’s consider the following example:

def my_function(a, b, c):
  print(a, b, c)
my_function(1, 2, 3)

In the context of the function definition, a, b, and c are parameters. Parameters are the variables defined in a function's signature that specify what values can be passed to the function.

When the function is called and values are passed to it, those values are referred to as arguments. In the function call my_function(1, 2, 3), 1, 2, and 3 are arguments.

So, to clarify:

  • a, b, and c are parameters (variables) in the function definition.
  • 1, 2, and 3 are arguments (values) passed to the function.

The arguments are assigned to the corresponding parameters based on their positions in the function call.

Python provides various capabilities beyond basic positional parameter passing. Let's explore these features in detail.

Example 1 – Illustrating Positional Argument Passing

To illustrate the concept of positional argument passing, let's consider a social convention. Typically, when introducing ourselves, we mention our first name(s) before our last name. This convention is similar to how positional arguments are used in Python.

We can implement this social custom in Python with the following function responsible for introducing someone:

def introduction(first_name, last_name):
  print("Hello, my name is", first_name, last_name)

Now, let's use the introduction function with different arguments:

introduction("Mahathir", "Mohamad")
introduction("Azman", "Hashim")
introduction("Faizal", "Hussein")

By running this code, the output will be as follows:

OUTPUT:

Example 2 – When Positional Argument Is Not Applicable

As you can see, the function in Example 2 follows the social convention of mentioning the first name before the last name. This aligns with the positional parameter passing approach.

However, imagine if the same function were to be used in China. Chinese surnames usually come first, followed by the given name. If the name for instance, Chan Mei Ling, Chan is the surname while Mei Ling is the given name. In that case, the code would be modified as follows:

introduction("Mei Ling ", "Chan")
introduction("Mu Yang", "Tan")
introduction("Zi Han", "Wang")

Executing this code would yield a different output:

OUTPUT:

To make the introduction function culture-independent and adaptable to different naming conventions, a possible solution is to use keyword arguments instead of positional arguments. By specifying the parameter names explicitly when invoking the function, we can achieve a more flexible approach that works across different cultural norms.

Python's flexibility allows us to leverage various parameter passing techniques, making our code adaptable to different scenarios and requirements.

Keyword Argument Passing in Python

Keyword argument passing is another powerful convention in Python that allows us to assign values to function parameters based on their names rather than their positions. This approach provides flexibility and clarity when working with function arguments. Let's dive into how it works.

def introduction(first_name, last_name):
   print("Hello, my name is", first_name, last_name)

introduction(first_name="Hang", last_name="Tuah")
introduction(last_name="Jebat", first_name="Hang")

OUTPUT:

In keyword argument passing, the values passed to the function parameters are preceded by the parameter names, followed by the = sign. The order of the arguments doesn't matter in this case, as each argument's value is assigned to the corresponding parameter based on its name.

By leveraging keyword argument passing, we can easily specify the intended values for each parameter, making the code more readable and self-explanatory. Running the code above will produce the expected output.

However, it's important to note that using non-existent parameter names will result in a runtime error. Python ensures that the provided parameter names are valid and match the function's parameter signature.

def introduction(first_name, last_name):
   print("Hello, my name is", first_name, last_name)

introduction(surname="Laksamana", first_name="Hang")

Executing the code snippet above will raise a TypeError with the message "introduction() got an unexpected keyword argument 'surname'". This error occurs because the function introduction() does not have a parameter named "surname".

Feel free to experiment with keyword arguments passing in your own code and explore its benefits and limitations. It offers a versatile and intuitive way to handle function arguments, enhancing code flexibility and readability.

Mixing Positional and Keyword Arguments

In Python, you have the flexibility to mix both positional and keyword arguments in function invocations. However, there is one important rule to remember: positional arguments must always come before keyword arguments.

The reason behind this rule becomes clear when you consider the way arguments are matched to function parameters.

To illustrate the concept, let's use a simple function called greet with three parameters:

def greet(name, age, message):

  print("Hello", name, "! You are", age, "years old.")
  print(message)

# Using only positional arguments
greet("Ali", 25, "Welcome to our community!")

# Using only keyword arguments
greet(name="Muthu", age=30, message="Have a great day!")

# Mixing positional and keyword arguments
greet("Ah Hock", age=35, message="Enjoy your stay!")

OUTPUT:

In this example, we have a function greet that takes three parameters: name, age, and message.

When using only positional arguments, the values are passed based on their position, where the first argument corresponds to name, the second to age, and the third to message.

When using only keyword arguments, the values are explicitly assigned to the parameters using their names. This allows you to provide the arguments in any order, as long as the parameter names are specified.

Lastly, you can mix positional and keyword arguments. In this case, you provide some arguments by their position and others using keywords. As long as the positional arguments come first, you can use keywords for the remaining arguments.

Mixing positional and keyword arguments gives you flexibility in how you provide values to function parameters. It allows you to specify certain values explicitly while relying on the default order for others.

However, take care to avoid mistakes. If you attempt to pass multiple values to a single argument, you will encounter a runtime error. For example:

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

# Valid function invocation
greet("Siti", 25, "Welcome to the course!")

# Invalid function invocation - passing multiple values to 'name'
greet("Siti", "Abu", 25, "Welcome to the course!")

In the example above, we have a function greet that takes three arguments: name, age, and message. When the function is invoked correctly with three arguments (greet("Siti", 25, "Welcome to the course!")), it will print a greeting message.

However, in the second function invocation (greet("Siti", "Abu", 25, "Welcome to the course!")), we pass four arguments instead of three. Here, we are providing multiple values for the name parameter, which is not allowed.

When you run this code, you will encounter a TypeError with a message similar to the following:

TypeError: greet() takes 3 positional arguments but 4 were given

The error indicates that the function greet expects only three positional arguments, but we provided four. It highlights the importance of passing the correct number of arguments to function parameters to avoid runtime errors.

In a different case, if we ran the following code, what would happen?

greet("Dolah", 18, message = "You are lucky today!")

While this code is technically correct and will execute without any errors, it may seem odd or unconventional because we are using keyword argument syntax for only one parameter while using positional arguments for the rest.

In most cases, when using a mixture of positional and keyword arguments, it's more common to use keyword arguments for all the parameters after the positional ones. This helps maintain consistency and makes the code more readable.

If the situation permits and makes sense in the context of your code, it's generally better to either use positional arguments for all parameters or use keyword arguments for all parameters to ensure clarity and avoid confusion.

Enhancing Functions with Default Parameter Values

In certain situations, some parameters in a function may have values that are commonly used more often than others. To streamline the function invocation process, you can assign default values to these parameters, which are automatically used when their corresponding arguments are omitted.

Let's consider an interesting example by incorporating the popularity of the name among Malaysian; "Mohamad". Setting default parameter values is straightforward using a simple syntax:

def introduction(first_name, second_name="Mohamad"):
   print("Hello, my name is", first_name, second_name)

By appending the = sign followed by the default value to the parameter's name, you can define the default value for that parameter.

Now, let's invoke the function in the usual way:

introduction("Azman", "Hashim")

Can you anticipate the output of the program? Run it to verify if your prediction is correct.

As expected, the output remains the same. However, if we invoke the function in a seemingly peculiar manner, such as:

introduction("Mahathir")
                            introduction(first_name="Ismail")

there will be no errors, and both invocations will succeed. The console will display the following output:

OUTPUT:

Feel free to test it yourself.

You can take it a step further by assigning default values to both parameters:

def introduction(first_name="Ali", last_name="Mohamad"):
   print("Hello, my name is", first_name, last_name)

This allows for the following invocation to be perfectly valid:

introduction()

The expected output is:

OUTPUT:

Even when using a single keyword argument, the remaining parameter will use its default value:

introduction(last_name="Dolah")

The output will be:

OUTPUT:

Feel free to test these scenarios.

Congratulations! You have now learned some fundamental techniques for interacting with functions. These concepts will greatly enhance your ability to leverage the power of functions in your code.

Summary

In summary, functions in Python allow you to pass information through parameters, and you can have as many parameters as needed. Whether it's a one-parameter, two-parameter, or three-parameter function, you have the flexibility to define the structure based on your requirements.

When passing arguments to functions, there are several techniques at your disposal. The first is positional argument passing, where the order of the arguments matters. For example, in the function subtract(a, b), subtract(5, 2) will output 3, while subtract(2, 5) will output -3.

Alternatively, you can utilize keyword argument passing, where the order of the arguments becomes irrelevant. By specifying the argument names explicitly, you can pass them in any order. For instance, in the function subtract(a, b), subtract(a=5, b=2) and subtract(b=2, a=5) will both output 3.

Moreover, you have the flexibility to mix positional and keyword argument passing. This allows you to combine the advantages of both techniques. For example, in the function subtract(a, b), subtract(5, b=2), and subtract(5, 2) will both output 3.

It's worth noting that when using a mix of positional and keyword arguments, positional arguments should always precede keyword arguments. Attempting to place a positional argument after a keyword argument will result in a SyntaxError.

Additionally, you can leverage the keyword argument-passing technique to assign default values to specific arguments. By providing a default value during parameter declaration, you allow the argument to take on that default value unless explicitly provided. For example, in the function name(first_name, last_name="Mohamad"), calling name("Ali") will output "Ali Mohamad", while name("Beto", "Kusyairi") will output "Beto Kusyairi", replacing the default value with "Mohamad".

By understanding these techniques, you can effectively pass arguments to functions, enhance flexibility, and streamline your code's readability and usability.

End Of Article

End Of Article