Python program to pass parameters to a function

Here, we will write a Python programs to understand the passing of parameters to a function. By Shivang Yadav Last updated : January 05, 2024

Functions in Python are very important as they reduce the number of lines of code.

One great feature is that they can operate on value passed as arguments, but you need to take precaution about parameters and values passed in the program.

For example, see the code –

Python program to pass parameters to a function

def show(id,name):
    print("Your id is :",id,"and your name is :",name)

show(12,"deepak")
show()
show(12)

Output

The output of the above program is:

Your id is : 12 and your name is : deepak
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    show()
TypeError: show() missing 2 required positional arguments: 'id' and 'name

Here, we have a method that accepts two parameters, but the programmer has not passed any. In such cases the program throws an error.

So, this needs to be managed by using default parameters. These are the values that come into play when the programmer does not pass an adequate number of parameters to the function.

Here is a program to illustrate default parameters.

Python program for default parameters

def show(id="<no id>",name="<no name>"):
    print("Your id is :",id,"and your name is :",name)

show(12,"deepak")
show()
show(12)

Output

The output of the above program is:

Your id is : 12 and your name is : deepak
Your id is : <no id> and your name is : <no name>
Your id is : 12 and your name is : <no name>

As we can see here, when no values are passed the program uses the default values present in the declaration.

To understand the above program, you should have the basic knowledge of the following Python topics:

Python Basic Programs »


Related Programs

Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.