Course
Positional-Only Arguments
Python Tutorial
This Python tutorial has been written for the beginners to help them understand the basic to advanced concepts of Python Programming Language. After completing this tutorial, you will find yourself at a great level of expertise in Python, from where you can take yourself to the next levels to become a world class Software Engineer.
Positional-Only Arguments
It is possible in Python to define a function in which one or more arguments can not accept their value with keywords. Such arguments may be called positional-only arguments.
Python's built-in
input()
function is an example of positional-only arguments. The syntax of input function isinput(prompt = "")
Prompt is an explanatory string for the benefit of the user. For example
name = input("enter your name ")
However, you cannot use the prompt keyword inside the parantheses.
name = input (prompt="Enter your name ") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^TypeError: input() takes no keyword arguments
To make an argument positional-only, use the "
/
" symbol. All the arguments before this symbol will be treated as position-only.Example
We make both the arguments of
intr()
function as positional-only by putting "/
" at the end.def intr(amt, rate, /): val = amt*rate/100 return val
If we try to use the arguments as keywords, Python raises following error message
interest = intr(amt=1000, rate=10) ^^^^^^^^^^^^^^^^^^^^^^^TypeError: intr() got some positional-only arguments passed as keyword arguments: 'amt, rate'
A function may be defined in such a way that it has some keyword-only and some positional-only arguments.
def myfunction(x, /, y, *, z): print (x, y, z)
In this function, x is a required positional-only argument, y is a regular positional argument (you can use it as keyword if you want), and z is a keyword-only argument.
The following function calls are valid
myfunction(10, y=20, z=30)myfunction(10, 20, z=30)
However, these calls raise errors
myfunction(x=10, y=20, z=30)TypeError: myfunction() got some positional-only arguments passed as keyword arguments: 'x'
myfunction(10, 20, 30)TypeError: myfunction() takes 2 positional arguments but 3 were given
Practice with Online Editor
Note: This Python online Editor is a Python interpreter written in Rust, RustPython may not fully support all Python standard libraries and third-party libraries yet.
Remember to save code(Ctrl
+S
Or
Command
+S
) before run it.