How to Fix SyntaxError: positional argument follows keyword argument in Python
A SyntaxError indicates that the Python interpreter has found code that does not conform to the correct syntax of the language. One common form is:
SyntaxError: positional argument follows keyword argument
This error typically occurs during a function call when a positional argument is placed after a keyword argument, which is not allowed in Python. Example:
# function definition
def fun(a, b, c=5):
print(a, b, c)
# invalid call
fun(a=1, 2, c=3)
Output
File "main.py", line 6
fun(a=1, 2, c=3)
^
SyntaxError: positional argument follows keyword argument
Explanation: Here, a=1 is a keyword argument, but 2 is a positional argument that comes after it. Python does not allow positional arguments after keyword arguments in a function call.
How to fix It
Move all positional arguments before keyword arguments in the function call:
fun(1, 2, c=3)
Keyword and Positional Arguments in Python
In Python, function arguments can be passed in two ways:
- Positional Arguments: Identified by their position in the function definition.
- Keyword Arguments: Identified by the name of the parameter (i.e., key=value pairs).
Example 1 : Valid Function calls
def fun(a, b, c=10):
print(f"a={a}, b={b}, c={c}")
# all positional
fun(2, 3, 8)
# Positional with default
fun(2, 3)
# ALl keyword arguments
fun(a=2, c=3, b=10)
Output
a=2, b=3, c=8 a=2, b=3, c=10 a=2, b=10, c=3
Explanation:
- fun takes three parameters a, b and an optional c with a default value of 10. It prints their values using f-string
- fun(2, 3, 8) Values are assigned by order: a=2, b=3, c=8.
- fun(2, 3) Since c isn’t provided, it defaults to 10: a=2, b=3, c=10.
- fun(a=2, c=3, b=10) Order doesn’t matter as each value is tied to a parameter: a=2, b=10, c=3.
Example 2: Invalid function calls
# Function definition
def fun(a, b, c=10):
print('a =', a)
print('b =', b)
print('c =', c)
# Invalid function call
print("Call 4")
fun(a=2, c=3, 9)
Output
Hangup (SIGHUP)
File "Solution.py", line 9
fun(a=2, c=3, 9)
SyntaxError: non-keyword arg after keyword arg
Explanation: fun(a=2, c=3, 9), a=2 and c=3 are keyword arguments, but 9 is a positional argument placed after them. Python disallows this because positional arguments must come before any keyword arguments for reliable parameter matching.
To fix it, place all positional arguments first:
