Python Keyword-Only Arguments: Fine-Tuning Function Parameters

thumb_up 1  ·  sell Python keyword-only arguments, Restricting parameter usage with keywords in Python, Customizing function arguments in Python

You can use the variables in formal argument list as keywords to pass value. Use of keyword arguments is optional. But, you can force the function be given arguments by keyword only. You should put an astreisk (*) before the keyword-only arguments list.

Let us say we have a function with three arguments, out of which we want second and third arguments to be keyword-only. For that, put * after the first argument.

The built-in print() function is an example of keyword-only arguments. You can give list of expressions to be printed in the parentheses. The printed values are separated by a white space by default. You can specify any other separation character instead with sep argument.

 
print ("Hello", "World", sep="-")

It will print −

Hello-World

The sep argument is keyword-only. Try using it as non-keyword argument.

 
print ("Hello", "World", "-")

You'll get different output – not as desired.

Hello World -

Example

In the following user defined function intr() with two arguments, amt and rate. To make the rate argument keyword-only, put "*" before it.

def intr(amt,*, rate): val = amt*rate/100 return val

To call this function, the value for rate must be passed by keyword.

interest = intr(1000, rate=10)

However, if you try to use the default positional way of calling the function, you get an error.

interest = intr(1000, 10)
               ^^^^^^^^^^^^^^
TypeError: intr() takes 1 positional argument but 2 were given


The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was this answer helpful?

Related Articles

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Back