Python Arguments with Syntax and Examples

FREE Online Courses: Your Passport to Excellence - Start Now

When we talk about functions, one of the important topics of concern would be its arguments. Python allows us to pass the inputs in different formats. In this article, we will learn Python function arguments and their different types with examples. Let us start with a brief recap of functions

Recap of Functions in Python

A function is a piece of code that works together under a name. The definition of a function starts with the keyword ‘def’ followed by the function name, arguments in parentheses, and a colon. Then the body is written by indenting by 4 spaces or a tab.

Example of Python function:

def func():
    print('Welcome to PythonGeeks')
    
func()

Output:

Welcome to PythonGeeks

Remember that we need to call the function to execute it. This is an example of a function with no parameter requirement and that does not return any value. Let us also see examples of functions that take arguments and that return a value.

Example of Python function that takes arguments:

def greet(name):
    print(f'Hello {name}. Welcome to PythonGeeks!')
    
greet('ABC')

Output:

Hello ABC. Welcome to PythonGeeks!

Example of Python function that returns a value:

def power(a,b):
    return a**b
    
print(power(4,3))

Output:

64

Python Function Arguments

Till now the arguments we passed are called the regular arguments. When we use these in a function, we need to be careful about the following two things:

1. Number of arguments passed
2. The order in which the arguments are passed

Problem with Number of Arguments Passed

When we do not pass the same number of arguments as mentioned in the function definition, we get an error. For example,

Example of getting an error on passing a different number of arguments:

def power(a,b):
    return a**b
    
power(2,5,0)

Output:

TypeError Traceback (most recent call last)
<ipython-input-5-def2634c7969> in <module>
2 return a**b
3
—-> 4 power(2,5,0)
TypeError: power() takes 2 positional arguments but 3 were given

The function power() requires only 2 arguments. But we got an error when we passed 3 arguments, which is more than 2. We come across the same error when we pass a lesser number of arguments.

Problem with Order of Arguments Passed

Also when we pass the arguments in a different order, we might get an unexpected output, or in the worse case might get an error. The below examples depict these two situations.

Example of getting an unexpected output on passing arguments in a different order:

def user(name, age):
    print(f"The age of {name} is {age}.")
    
user(30,'PRQ')

Output:

The age of 30 is PRQ.

We can see that the name and age got swapped. It looks funny but it might cause a lot of other problems in the overall program in some cases. Let us also see an example where we get an error on giving the inputs in the wrong order.

Example of getting an error on passing arguments in a different order:

def calc(a,b,c):
    print((a+b)/c)
    
calc(3,0,5)

calc(3,5,0)

Output:

0.6
ZeroDivisionError Traceback (most recent call last)
<ipython-input-9-32c43b64bfef> in <module>
3
4 calc(3,0,5)
—-> 5 calc(3,5,0)<ipython-input-9-32c43b64bfef> in calc(a, b, c)
1 def calc(a,b,c):
—-> 2 print((a+b)/c)
3
4 calc(3,0,5)
5 calc(3,5,0)ZeroDivisionError: division by zero

We can see that on the first call we got an output. But when we swapped the second and the third arguments, we got an error. So it is important to be careful about the count and the number of arguments.

We know that Python is a programmer-friendly language. It proves itself in this case too. It provides different kinds of arguments to be passed to a function that can be used to solve the problems discussed above.

Besides the regular arguments we have three more types:

1. Keyword arguments
2. Default arguments
3. Variable-length arguments

We will discuss each of these in detail in further sections.

Python Keyword Arguments

We discussed about the possible problems when the arguments are not given in the proper order. To solve this problem we can make use of the keyword arguments. Here when we are calling the function, we give the arguments by referring them to the corresponding parameter names used in the definition.

Example of a function with keyword arguments:

def membership(val,seq):
    print(val in seq)

membership(val=5,seq=range(2,6))

Output:

True

The names ‘val’ and ‘seq’ are the names used for the arguments while defining the function. Observe that we use the same names and equate them to the values while calling the function.

Using this method will not create any problem even if we give the arguments in a different order, as we use the names of the parameters. This is shown in the below example.

Example of a function with keyword arguments:

membership(seq=range(2,6),val=6)

Output:

False

Python Default Arguments

This type of argument is used to solve the problem of the number of arguments passed. While defining a function, we can assign the values to some or all the arguments of the function. When we call the function, if the arguments are passed, it takes the values given as input. Or else, if no argument passed, then the default values are considered.

Let us see an example where all the arguments are default.

Example of a function with all default arguments:

def sum(a=0,b=3,c=0):
    print(a+b+c)

sum(1,3)
sum(3,9,-2)
sum()

Output:

4
10
3

We can see above that when we passed only two arguments, 1 and 3, a is assigned to 1 and b to 3. While the default value of 0 is given to c. And then the sum =1+3+0=4 is printed.

But when we passed all the arguments, the passed arguments are considered in the second call of the function.

While in the third call, none of the arguments are passed. In this case, all the variables take the default values.

Combination of default and other arguments

Let us also see a function where we have some default and some regular arguments.

Example of a function with some default arguments:

def details(item,price,disc=0):
    print(f'The price of the {item} is {price} and the discount is {disc}%')
    
details('Ball',45)
details('Bat',100,5)
details('Cap')

Output:

The price of the Ball is 45 and the discount is 0%
The price of the Bat is 100 and the discount is 5%
TypeError Traceback (most recent call last)
<ipython-input-17-c0bb6b8c3a7c> in <module>
4 details(‘Ball’,45)
5 details(‘Bat’,100,5)
—-> 6 details(‘Cap’)
TypeError: details() missing 1 required positional argument: ‘price’

From the above example, we can see that when we pass the value to all the arguments, the passed values are taken. While when we do not pass the values, then the corresponding default values are considered.But also observe that if we skip giving the values of the regular arguments, then we get an error.

Placement of the Keyword Argumets

Another think to note is that all the regular arguments are placed before the keyword arguments in the definition of the function. This is because it is a must to give the values for the regular arguments and we know that the values will be assigned based on the position.

So, when we place any regular argument after the keyword argument, we get an error as shown below.

Example of getting an error on placing the regular arguments after the keyword arguments:

def calc(a,b=5,c,d=0):
    print(a+b-c+d)
    
calc(1,3,4)

Output:

File “<ipython-input-16-a49542323799>”, line 1
def calc(a,b=5,c,d=0):
^
SyntaxError: non-default argument follows default argument

From the above example, we can see that enve though we passed all the required arguments, we got an error that tells about the position of the default and regular arguments.

Variable length arguments

These arguments are also used when we have a problem of number of arguments. To be specific, these arguments are used when we do not know number of arguments are needed to be passed to the function. These are also called arbitrary arguments.

In this case we use the the asterisk (*) before the parameter name in the definition of the function. For example,

Example of a function with variable length arguments:

def sum(*nos):
    total=0
    for i in nos:
        total=total+i
    print(total)
    
sum()
sum(-3,4,5)
sum(1,2,3,4,5)

Output:

0
6
15

Observe that the ‘nos’ is a sequence of values and that we can pass any number of arguments to the function. Also see that we did not pass any list, we passed values separated by commas as we did with the other arguments.

Combination of variable length and other types of arguments

We can also use other types of arguments along with the variable length arguments. For example,

Example of a function with different kinds of arguments:

def func(name,attempts=0,*scores):
    print(f'The person {name} attempted the exam {attempts} times and the socres are:')
    for i in scores:
        print(i)
    
func('ABC',3,46,70,53)

Output:

The person ABC attempted the exam 3 times and the socres are:
46
70
53

Here, the ‘name’ is regular argument, ‘attempt’ is default argument and ‘scores’ is variable length arguments.

Placement of the variable length arguments

Again here also we should place the variable length argumets after the required arguments as the required arguments will be considered as a part of variable length ones. Anng we get an error showing that some arguments are missing as shown below.

Example of getting an error on passing keyword arguments before required ones:

def func(*names,n):
    print(f'He has {n} frieds and their names are:',)
    for i in names:
        print(i)
    
func('abc','pqr',2)

Output:

TypeError Traceback (most recent call last)
<ipython-input-28-120b3c591394> in <module>
4 print(i)
5
—-> 6 func(‘abc’,’pqr’,2)
TypeError: func() missing 1 required keyword-only argument: ‘n’

We can solve this posblem by replacing the regular argument with the keyword argument. For example,
Example of using keyword arguments before keyword ones:

def func(*names,n):
    print(f'He has {n} frieds and their names are:',)
    for i in names:
        print(i)
    
func('abc','pqr',n=2)

Output:

He has 2 frieds and their names are:
abc
pqr

Interview Questions on Python Arguments

Q1. Write a function to checks if the number is divisible by the second number or not.
Ans. We can use the conditional statements inside the function.

Example of function that checks if the number is divisible by the second number or not.

def divisibility(n,m):
    if(n%m==0):
        print('Divisible')
    else:
        print('Not divisible')
    
divisibility(10,4)

Output:

Not divisible

Q2. Write a program to take the marks of the students and find the percentake. All the scores should have the value zero by default.

Ans. We can use the default arguments

Example of function with default arguments:

def perc( m1=0,m2=0,m3=0,m4=0,m5=0):
    print("%.2f"%((m1+m2+m3+m4+m5)/500*100))
    
perc(45,68,80,79)

Output:

54.40

Q3. Take the amount and rate, which are given in any order. Find the interest over a year.
Ans. We can use the keyword arguments

Example of function with keyword arguments:

def interest(amt,rate):
    print(amt*rate*1/100)
    
interest(rate=15000,amt=4)

Output:

600.0

4. Given arbitrary number of values, find the number of values are even and return the count.
Ans. We can use variable-length arguments

Example of function with variable length arguments:

def count(*vals):
    c=0
    for i in vals:
        if (i%2==0):
            c=c+1
    return c
    
count(3,4,2,9,8,14)

Output:

4

Q5. Write a function that takes the name, and initial salary, and the increment(s) over the last few years. Find the current salary.
Ans. We can take name and salary as required arguments and increments as variable-length arguments.

Example of function with different types of arguments:

def sal(name, init,*inc):
    for i in inc:
        init=init+i
    print('Salalry of ',name,'is: ',init)
    
sal('ABC',50000,3000,5000,7000)

Output:

Salalry of ABC is: 65000

Quiz on Python Function Arguments

Conclusion

Hoping that you understood the concepts discussed in this article. This includes functions, arguments, different types of arguments. We discussed all these in detail and with examples. Finally, we saw some coding questions for practice. Happy learning.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google | Facebook


3 Responses

  1. Socretas says:

    Typo:
    socres->scores

    Great tutorial!

  2. James says:

    Great tutorial

  3. Paul Nockolds says:

    Very Useful – Thanks

Leave a Reply

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