top of page
Writer's pictureRajesh Singh

What is Function Arguments in Python

Updated: May 18, 2020


A function that takes variable number of arguments in Python.

Example:

def tkd(name,msg):

print("Hello",name + ', ' + msg)

tkd("Raj","Good morning!")

Output:

Hello Raj, Good morning!

Here, the function tkd() has two parameters or arguments name and msg.

Variable Function Arguments

There are additional ways to define a function which can take variable number of arguments in Python. Which are below:

1. Python Default Arguments

Function arguments can have default values in Python. By using the assignment operator (=), we can define a default value to an argument.

def tkd(name, msg = "Good morning!"):

print("Hello",name + ', ' + msg)

tkd("Kate")

tkd("Bruce","How do you do?")

Output:

Hello Kate, Good morning!

Hello Bruce, How do you do?

In this function, the parameter name does not have a default value and the parameter msg has a default value of "Good morning!"



2. Python Keyword Arguments

Python allows functions to be called using keyword arguments. When we call functions in this way, the order or position of the arguments can be changed. Following calls to the above function are all valid and produce the same result.

# 2 keyword arguments

tkd(name = "Bruce",msg = "How do you do?")

# 2 keyword arguments (out of order)

tkd(msg = "How do you do?",name = "Bruce")

# 1 positional, 1 keyword argument

tkd("Bruce",msg = "How do you do?")

We can see that mix positional arguments with keyword arguments during a function call. But having a positional argument after keyword arguments will result into errors.

Example

tkd(name="Bruce","How do you do?")

Output : SyntaxError: non-keyword arg after keyword arg


3. Python Arbitrary Arguments:

Python allows us to handle this kind of situation through function calls with arbitrary number of arguments. In the function definition we use an asterisk (*) before the parameter name to represent this type of argument.

Example:

def tkd(*names):

for name in names:

print("Hello",name)

tkd("Raj","Moni","Steve","John")

Output:

Hello Raj

Hello Moni

Hello Steve

Hello John



22 views0 comments

Recent Posts

See All

Files MCQ in Python

File Processing MCQ Q1. Which function writes a list of lines in File? A.      Writelines() B.      Write() C.      Tell() D.      All of...

Python List MCQ Questions

Q1. What is output of below python code? dict= {1:'1', 2:'2', 3:'3'} del dict[1] dict[1] = '10' del dict[2] print (len(dict)) A. 1 B. 2...

Python NUMPY MCQ Questions

Python NumPy Chapter MCQ: 1. What will be print? Import numpy as np a = np. array([1,2,3,5,8]) b = np. array([0,3,4,2,1]) c = a+b c = c*a...

Comments


bottom of page