Python function arguments [With Easy Examples]

Filed Under: Python

Dear learners, today we’re going to learn about the Python function arguments including default arguments, arbitrary arguments, and keyword arguments.

In our previous article, we talked about Python loops and how to use them. Without any further delay, let’s get started here.

Understanding Python Functions and Function Arguments

A Python function is used to accomplish a specific task. When software becomes larger and more obscure, it becomes an absolute necessity to ensure we split up tasks into smaller chunks.

This can be done with the use of Python functions or with the use of object-oriented programming.

def function_name( arguments ) :
        #define tasks here

You can have a function that accepts multiple arguments separated by commas.

For example, if you want to calculate the variable result were, result = x * ( y + z ). Then,

  • Let, p = y + x
  • So, result = x * p

In this case, we first calculate the value of p and then multiply the same with the variable x.

Basics implementation of Python function arguments

Let’s convert the above expression into a Python function and pass these variables as arguments to the function.

'''
create a function for adding two variables. It will be needed to calculate p=y+z
'''
def calculateP( y , z ) :
        return int( y ) + int( z )

'''
create a function for multiplying two variables. It will be needed to calculate p=y+z
'''
def calculateResult( x, p ) :
        return int( x ) * int( p )

#Now this is the beginning of main program
x = input('x: ')
y = input('y: ')
z = input('z: ')

#Now Calculate p
p = calculateP ( y , z )

#Now calculate the result;
result = calculateResult( x , p )

#Print the result
print(result)

The output of the following code will be

================== RESTART: /home/imtiaz/Desktop/pyDef.py ==================
x: 2
y: 2
z: 3
10

Passing an arbitrary number of arguments to Python functions

We’ve looked at passing a static number of variables to a function. But what if we want to pass an arbitrary number of arguments to the function. Or we do not want to limit the number of arguments the function can work with.

In this case, we work with the asterisk (*) symbol as shown in the below example.

def varFunc(name,*args):
        print("This is the first argument "+str(name))
        #This print will make you understand that the args is a list
        print(args)
        for item in args:
                print(item)

print("First time:")
varFunc("of 1st function call",2, 3, 4, 5)

print("Second time:")
varFunc("of 2nd function call","asd","Bcd")

print("Third time:")
varFunc("and only argument of 3rd function call")

The Output will be:
python function, python function arguments, python function variable arguments example

Passing with Key-Value Pairs as Function Arguments

Using the double-asterisk(**) sign, you can send over an arbitrary number of function arguments, and also pass them in any order. The .get() function is used to pull the variable values by specifying the keys. Let’s take a look at a demonstration here to understand this concept better.

def varFunc(name, roll, **option):
        print("Name: "+name)
        print("Roll: "+str(roll))
        if "age" in option :
                print("Age: "+ str(option.get("age")))
        if "gender" in option:
                print("Gender: "+ str(option.get("gender")))

print("First Person")
varFunc("Alice", 234, age=18, gender="female")

print("\nSecond Person")
#See, the order of argument age and gender is different now
varFunc("Bob", 204, gender="male", age=21)

print("\nThird Person")
#We will not pass age as and argument
varFunc("Trudy", 204, gender="male")

Output will be

================== RESTART: /home/imtiaz/Desktop/key_value_arg.py ==================
First Person
Name: Alice
Roll: 234
Age: 18
Gender: female

Second Person
Name: Bob
Roll: 204
Age: 21
Gender: male

Third Person
Name: Trudy
Roll: 204
Gender: male
>>>

Conclusion

That’s all for the article today! I hope you have learned about Python function arguments in a much more practical manner. Keep learning Python with our upcoming Python tutorials here.

Reference: Official Documentation

Comments

  1. Soff says:

    Another way of doing this using two lines of code also in Python

    comp = lambda x, y, z : x * (y + z) # Using Lambda Arguments : Expression (Syntax)
    print(comp(4, 4, 4))

  2. Marcio Mendonca says:

    Congrats for the interesting tutorial.
    May I suggest to include the use of __return__ when an output of the function is needed as a variable?

  3. Keshava Reddy says:

    Tanks for the details explanation of the functions concept…..it would be great if you add Passing function as argument in details….if posible

  4. kamna says:

    This is great to see this amazing article. i wanna appreciate your hard work and give full importance towards it.

  5. rolling sky says:

    Thanks for the lesson, it is very detailed, I know more about Python Function and Arguments.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages