JIYIK CN >

Current Location:Home > Learning > PROGRAM > Python >

Optional parameters in Python

Author:JIYIK Last Updated:2025/05/05 Views:

In Python, there is something called default arguments. It is also called optional parameters or optional arguments in python. Parameters refer to the inputs of a function.


Functions with multiple optional parameters in Python

Whenever you call a function, you have to pass some arguments to that function, it depends on whether the function accepts any arguments or not. Passing arguments to a function is not mandatory, a function can accept no arguments or any number of arguments (depending on how the function is used). A function can accept no arguments or any number of arguments (depending on how the function is defined). We can pass multiple arguments in two ways.

Use *args(non-keyword arguments)

# Function Defination
def myfunction(first_name, last_name, *args):
    print(first_name)
    print(last_name)
    for argument in args:
        print(argument)


# Calling the Function
myfunction("Tim", "White", 999888999, 30)

Output:

Tim
White
999888999
30

Use **kargs(keyword arguments)

def myFunction(**kwargs):
    # printing all values which are passed in as an argument
    for key, value in kwargs.items():
        print("%s = %s" % (key, value))


# Calling the Function
myFunction(first_name="Tim", last_name="White", mob=99999999, age="30")

Output:

first_name = Tim
last_name = White
mob = 99999999
age = 30

*argsBoth **kargsare variable-length parameters, used to pass a variable number of arguments to a function.

When you create a function, you have to define how many parameters or arguments it will accept as input. These are called formal parameters. And whenever you call the function, you have to pass some values ​​to the function, which are called actual parameters.


Making parameters optional in Python

Let's say you have a function that takes three parameters name, numberand ageas input.

# Function Defination
def personalDetails(name, number, age):
    print("This function takes 3 parameters as input")

If you want to call a function personalDetails, you must pass these 3 parameters as input to the function.

def personalDetails(name, number, age):
    print("This function takes 3 parameters as input")
    print("Name: ", name)
    print("Number: ", number)
    print("Age: ", age)


# Calling the function
personalDetails("Adam", 987654321, 18)

Output:

This function takes 3 parameters as input
Name: Adam
Number: 987654321
Age: 18

Here, when calling a function, if you omit or forget to pass any of the parameters, you will get an error ( TypeError: personalDetails missing a required positional argument).

If you don't want to pass your age as a parameter to the above function, you can use something called optional parameters. In Python, you can make any number of parameters or arguments optional. To make a parameter optional, you have to assign some default value to that parameter.

Here, to make agethe parameter optional, you can ageadd a default value to the parameter in the function definition to make it optional. In this case, let's 0initialize it with or any other value you want. Now, Python will treat this parameter as an optional parameter. So, even if you don't agepass any value to the parameter, the function will work and it will use the default value, which in this case is 0.

def personalDetails(name, number, age=0):
    print("Age is now an optional argument.")
    print("Age is: ", age)


# Calling the function
personalDetails("Sam", 123456789)

Output:

Age is now an optional argument.
Age is: 0

Even if you want to personalDetailsspecify agethe value of the parameter when calling the function, you can do so. Now it will consider the new value you specified instead of the default value.

def personalDetails(name, number, age=0):
    print("Age is now an optional argument.")
    print("Age is: ", age)


# Calling the function
personalDetails("Sam", 123456789, 25)

Output:

Age is now an optional argument.
Age is: 25

in conclusion

Whenever you initialize any parameter with a default value, it is called a default parameter. This ultimately makes the parameter optional as well because now it is not mandatory to pass a value to that parameter while calling the function. This is called optional parameter or optional argument in Python.

But if you pass some value to the optional parameter when calling the function, then the function will take this new value instead of the default value.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Read the first line of a file in Python

Publish Date:2025/05/05 Views:192 Category:Python

In Python, we have built-in functions to handle different file operations. A text file contains a sequence of strings where each line \n is terminated by a newline character. In this tutorial, we will learn how to read the first line of a t

Writing floating point numbers to a file in Python

Publish Date:2025/05/05 Views:91 Category:Python

Python makes writing data to a file a seamless task. The data is written to the file in the form of strings. In this article, you will learn how to write float values ​​to a file in Python. Writing floating point numbers to a file in Py

How to read specific lines from a file in Python

Publish Date:2025/05/05 Views:181 Category:Python

A common way to read files in Python is to read the file completely and then process specific lines. Reading files in Python is fast, for example, it takes about 0.67 seconds to write a 100MiB file. However, if the file size exceeds 100MB,

Calculating the arithmetic mean in Python

Publish Date:2025/05/05 Views:190 Category:Python

The term arithmetic mean is the average of the numbers. The mathematical formula to determine the arithmetic mean is to divide the sum of the numbers by the count. It is determined in Python in the following way. Use mathematical formulas.

Cosine Similarity in Python

Publish Date:2025/05/05 Views:81 Category:Python

Cosine similarity measures the similarity between two lists of vectors by calculating the cosine angle between them. If you consider the cosine function, it has a value of 1 at 0 degrees and -1 at 180 degrees. This means that for two overla

Exponential and Logarithmic Curve Fitting in Python

Publish Date:2025/05/05 Views:79 Category:Python

Curve fitting is a very effective tool that is widely used in analysis. Curve fitting method studies the relationship between independent variables (also called predictor variables) and dependent variable (called response variable). This me

Calculating Slope in Python

Publish Date:2025/05/05 Views:60 Category:Python

In mathematics, the slope of a given line is the value at which its steepness is calculated. It also helps to characterize the direction of a given line. The extent of a line can also be calculated using Python programming language. This ar

How to Randomly Select Elements from a List in Python

Publish Date:2025/05/05 Views:68 Category:Python

This tutorial showed you how to randomly select an element from a list in Python. There are multiple simple ways to achieve this goal, all of which involve importing Python modules. This tutorial will cover solutions that require the random

How to Replace an Element in a Python List

Publish Date:2025/05/05 Views:109 Category:Python

We can replace elements in Python lists in many ways. We can use Python list element indexing, for loops, map functions, and list comprehensions. This article will discuss the above methods to find and replace elements in Python lists. Sear

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial