Syntaxerror positional argument follows keyword argument ошибка

In this article, we will discuss how to fix the syntax error that is positional argument follows keyword argument in Python

An argument is a value provided to a function when you call that function. For example, look at the below program –

Python

def calculate_square(num):

    return num * num

result = calculate_square(10)

print(result)

The calculate_square() function takes in an argument num which is an integer or decimal input, calculates the square of the number and returns the value.

Keyword and Positional Arguments in Python

There are two kind of arguments, namely, keyword and positional. As the name suggests, the keyword argument is identified by a function based on some key whereas the positional argument is identified based on its position in the function definition. Let us have a look at this with an example.

Python

def foo(a, b, c=10):

    print('a =', a)

    print('b =', b)

    print('c =', c)

print("Function Call 1")

foo(2, 3, 8)

print("Function Call 2")

foo(2, 3)

print("Function Call 3")

foo(a=2, c=3, b=10)

Output:

Function Call 1
a = 2
b = 3
c = 8
Function Call 2
a = 2
b = 3
c = 10
Function Call 3
a = 2
b = 10
c = 3

Explanation:

  1. During the first function call, we provided 3 arguments with any keyword. Python interpreted in order of how they have been defined in the function that is considering position of these keywords.
  2. In the second function call, we provided 2 arguments, but still the output is shown because of we provided 2 positional argument and the function has a default value for the final argument c. So, it takes the default value into account for the final argument.
  3. In the third function call, three keyword arguments are provided. The benefit of providing this keyword argument is that you need not remember the positions but just the keywords that are required for the function call. These keywords can be provided in any order but function will take these as key-value pairs and not in the order which they are being passed.

SyntaxError: positional argument follows keyword argument

In the above 3 cases, we have seen how python can interpret the argument values that are being passed during a function call. Now, let us consider the below example which leads to a SyntaxError.

Python

def foo(a, b, c=10):

    print('a =', a)

    print('b =', b)

    print('c =', c)

print("Function Call 4")

foo(a=2, c=3, 9)

Output:

File "<ipython-input-40-982df054f26b>", line 7
    foo(a=2, c=3, 9)
                 ^
SyntaxError: positional argument follows keyword argument

Explanation:

In this example, the error occurred because of the way we have passed the arguments during the function call. The error positional argument follows keyword argument means that the if any keyword argument is used in the function call then it should always be followed by keyword arguments. Positional arguments can be written in the beginning before any keyword argument is passed. Here, a=2 and c=3 are keyword argument. The 3rd argument 9 is a positional argument. This can not be interpreted by the python as to which key holds what value. The way python works in this regards is that, it will first map the positional argument and then any keyword argument if present.

How to avoid the error – Conclusion

Last Updated :
28 Nov, 2021

Like Article

Save Article

Table of Contents
Hide
  1. What is SyntaxError: positional argument follows keyword argument?
  2. How to fix SyntaxError: positional argument follows keyword argument?
    1. Scenario 1 – Use only Positional Arguments.
    2. Scenario 2 – Use only Keyword Arguments.
    3. Scenario 3 – Use Positional arguments first, followed by Keyword Arguments.
  3. Conclusion

If you provide the keyword argument first followed by a positional argument, the Python interpreter will raise SyntaxError: positional argument follows keyword argument.

In this tutorial, we will learn what SyntaxError: positional argument follows keyword argument means and how to resolve this error with examples.

An argument is a variable, value, or object passed to a method or function as an input. We have two types of arguments in Python, and we can pass these arguments while calling the methods.

Positional Argument -The positional arguments are the one that does not have any keyword in front of them.

Example

result = add_numbers(10, 20, 30)

Keyword Argument -The Keyword arguments are the one that has a keyword in front of them.

Example

result = add_numbers(a=10, b=20, c=30)

Every programming language has its own set of rules. These rules are referred to as the syntax that needs to be followed while programming.

The positional and keyword arguments must appear in a specific order; otherwise, the Python interpreter will throw a Syntax error.

The Python rule says positional arguments must appear first, followed by the keyword arguments if we are using it together to call the method.

The SyntaxError: positional argument follows keyword argument means we have failed to follow the rules of Python while writing a code.

Let us take a simple example to demonstrate this error.

# Method that takes 3 arguments and returns sum of it
def add_numbers(a, b, c):
    return a+b+c

# call the method by passing the arguments
result = add_numbers(a=10, 20, 30)

# print the output
print("Addition of numbers is", result)

Output

  File "c:PersonalIJSCodemain.py", line 8
    result = add_numbers(a=10, 20, 30)
                                     ^
SyntaxError: positional argument follows keyword argument

We have passed the Keyword argument first in the above code and then followed by the Positional argument which breaks the rule and hence we get the SyntaxError.

How to fix SyntaxError: positional argument follows keyword argument?

There are several ways to fix the error. Let us look at all the correct ways to call the methods in Python.

Scenario 1 – Use only Positional Arguments.

The easier way to fix the issue is to use only Positional arguments while calling the method in Python.

Let us fix our example by passing only positional arguments and see what happens when we run the code.

# Method that takes 3 arguments and returns sum of it
def add_numbers(a, b, c):
    return a+b+c

# call the method by passing only positional arguments
result = add_numbers(10, 20, 30)

# print the output
print("Addition of numbers is", result)

Output

Addition of numbers is 60

The code runs without any error as Python knows which values to use for each argument in the function.

Scenario 2 – Use only Keyword Arguments.

Another way to resolve the error is to use only the Keyword arguments while calling the method in Python.

# Method that takes 3 arguments and returns sum of it
def add_numbers(a, b, c):
    return a+b+c


# call the method by passing only keyword arguments
result = add_numbers(a=10, b=20, c=30)

# print the output
print("Addition of numbers is", result)

Output

Addition of numbers is 60

The code runs without any error as Python knows which values to use for each argument in the function.

Scenario 3 – Use Positional arguments first, followed by Keyword Arguments.

If you need to use both positional and keyword arguments, you need to abide by the rules of Python.

The Positional arguments should always appear first, followed by the keyword arguments.

In the below example, we have fixed the issue by passing the two positional arguments first and then a keyword argument.

# Method that takes 3 arguments and returns sum of it
def add_numbers(a, b, c):
    return a+b+c


# pass all positional arguments first and then keyword arguments
result = add_numbers(10, 20, c=30)

# print the output
print("Addition of numbers is", result)

Output

Addition of numbers is 60

Conclusion

In Python, the SyntaxError: positional argument follows keyword argument occurs if you pass keyword arguments before the positional arguments. Since Python interprets positional arguments in the order in which they appear first and then followed by the keyword arguments as next.

We can resolve the SyntaxError by providing all the positional arguments first, followed by the keyword arguments at last.

  • Редакция Кодкампа

17 авг. 2022 г.
читать 1 мин


Одна ошибка, с которой вы можете столкнуться в Python:

SyntaxError : positional argument follows keyword argument

Эта ошибка возникает, когда вы используете позиционный аргумент в функции после использования аргумента ключевого слова .

Вот разница между ними:

Позиционные аргументы — это аргументы, перед которыми нет «ключевого слова».

  • Пример: my_function (2, 2)

Аргументы ключевых слов — это аргументы , перед которыми стоит «ключевое слово».

  • Пример: my_function(a=2, b=2)

Если вы используете позиционный аргумент после аргумента ключевого слова, Python выдаст ошибку.

  • Пример: my_function(a=2, 2)

В следующем примере показано, как эта ошибка может возникнуть на практике.

Пример: Аргумент позиции следует за аргументом ключевого слова

Предположим, у нас есть следующая функция в Python, которая умножает два значения, а затем делит на третье:

def do_stuff (a, b):
 return a * b / c

В следующих примерах показаны допустимые и недопустимые способы использования этой функции:

Правильный способ №1: все позиционные аргументы

Следующий код показывает, как использовать нашу функцию со всеми позиционными аргументами:

do_stuff( 4 , 10 , 5 )

8.0

Никакой ошибки не возникает, потому что Python точно знает, какие значения использовать для каждого аргумента в функции.

Верный способ № 2: все аргументы ключевых слов

Следующий код показывает, как использовать нашу функцию со всеми аргументами ключевого слова:

do_stuff(a= 4 , b= 10 , c= 5 )

8.0

И снова ошибка не возникает, потому что Python точно знает, какие значения использовать для каждого аргумента в функции.

Действенный способ № 3: позиционные аргументы перед ключевыми аргументами

Следующий код показывает, как использовать нашу функцию с позиционными аргументами, используемыми перед аргументами ключевого слова:

do_stuff(4, b=10, c=5)

8.0

Никакой ошибки не возникает, потому что Python знает, что аргументу a должно быть присвоено значение 4 .

Неверный способ: позиционные аргументы после аргументов ключевого слова

Следующий код показывает, как мы можем попытаться использовать функцию с позиционными аргументами, используемыми после аргументов ключевого слова:

do_stuff(a= 4, 10, 5)

SyntaxError : positional argument follows keyword argument

Возникает ошибка, потому что мы использовали позиционные аргументы после аргументов ключевого слова.

В частности, Python не знает, следует ли присваивать значения 10 и 5 аргументам b или c , поэтому он не может выполнить функцию.

Дополнительные ресурсы

В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:

Как исправить KeyError в Pandas
Как исправить: ValueError: невозможно преобразовать число с плавающей запятой NaN в целое число
Как исправить: ValueError: операнды не могли транслироваться вместе с фигурами

Just for completeness, taken from the early comment

Remove board =

Thus, you can just drop the «board =» and pass the value directly, with all parameters as positional arguments:

is_valid_move(
    [[2, 2, 0, 2, 2, 2, 2], 
    [1, 2, 2, 2, 2, 2, 2], 
    [1, 1, 2, 2, 1, 2, 1], 
    [1, 1, 2, 2, 1, 2, 1], 
    [1, 1, 2, 2, 1, 2, 1], 
    [1, 1, 2, 2, 1, 2, 1]],
    
    2
)

Or use keyword + positional arguments for all parameters:

is_valid_move(board=[[2, 2, 0, 2, 2, 2, 2], [1, 2, 2, 2, 2, 2, 2], [1, 1, 2, 2, 1, 2, 1], [1, 1, 2, 2, 1, 2, 1], [1, 1, 2, 2, 1, 2, 1], [1, 1, 2, 2, 1, 2, 1]], 
              column=2)

Image of How to Fix: Positional Argument Follows Keyword Argument in Python

Table of Contents

  • Introduction
  • Positional and Keyword Arguments in Python
  • What is SyntaxError: positional argument follows keyword argument?
  • How to Fix SyntaxError: positional argument follows keyword argument?
  • Using Only Positional Arguments
  • *args and **kwargs Parameters in Python
  • Summary
  • Next Steps
  • References

Introduction

Arguments (or parameters) are a fundamental concept in Python programming. They allow you to provide inputs to your programs and functions that result in a varying output return value or varying set of steps performed by your program.

In Python, you might have encountered the error SyntaxError: Positional Argument Follows Keyword Argument when working with positional and keywords arguments together in one function. To resolve this error you must understand how arguments fundamentally work in Python.

In this article, you will learn how to fix the «SyntaxError: Positional Argument Follows Keyword Argument» in Python by understanding what positional and keyword arguments are and how they work, which will help you prevent this error from occurring in the future.

Positional and Keyword Arguments in Python

Arguments allow developers and users to provide input values to a program or function that returns a varying output based on the arguments supplied. In Python, arguments are most commonly used when calling functions and class methods — a class method is just a function defined as a part of a class. If you are familiar with the Linux command line, you likely have already used arguments with some Linux commands.

The terms «parameter» and «argument» are often used interchangeably. As a refresher, let’s quickly mention the difference these two terms:

  • A parameter is a scoped variable defined in the function header.
  • An argument is the value passed as input via a function call, which is mapped to a parameter.

Python has two important types of arguments, positional arguments and keyword arguments.

You are probably most familiar with positional arguments, since they are the default type in Python.

Positional arguments are simply an ordered list of inputs in a Python function call that correspond to the order of the parameters defined in the function header.

>>> def func(num1, num2):
...     print(f"Num 1: {num1}, Num 2: {num2}")
... 
>>> func(1, 2)
Num 1: 1, Num 2: 2
>>>
>>> func(2, 1)
Num 1: 2, Num 2: 1

In this example, we have defined a the function func with parameters num1, and num2. When calling the function, the argument order matters. Python uses the position of the arguments to determine the parameter to map each input value to.

On the other hand, a keyword argument is supplied with both a parameter name AND its corresponding value.

>>> def func(num1, num2):
...     print(f"Num 1: {num1}, Num 2: {num2}")
...
>>> func(num1=1, num2=2)
Num 1: 1, Num 2: 2
>>>
>>> func(num2=2, num1=1)
Num 1: 1, Num 2: 2

Here, you can see how keyword arguments are used, and how changing the order of the arguments doesn’t matter because you specify exactly which parameter refers to which value.

What is SyntaxError: positional argument follows keyword argument?

The Python SyntaxError: positional argument follows keyword argument occurs when you try to specify a positional argument after a keyword argument in a function call.

>>> def func(num1, num2):
...     print(f"Num 1: {num1}, Num 2: {num2}")
... 
>>> func(num1=1, 2)
  File "<stdin>", line 1
    func(num1=1, 2)
                  ^
SyntaxError: positional argument follows keyword argument

Here, the SyntaxError occurred because the keyword argument num1=1 is followed by the positional argument 2.

The logic behind why the SyntaxError occurs is that in order for Python to consistently map all supplied argument values to named parameters, all positional arguments must be specified before any keyword arguments.

How to Fix SyntaxError: positional argument follows keyword argument?

There are multiple ways to fix the Python exception SyntaxError: positional argument follows keyword and each method has its pros and cons.

Using Positional Arguments Followed by Keyword Arguments

One method is to simply do what the error states and specify all positional arguments before our keyword arguments!

>>> func(1, num2=2)
Num 1: 1, Num 2: 2

Here, we use the positional argument 1 followed by the keyword argument num2=2 which fixes the error. However, you might have noticed that in the previous example we used a keyword argument for the num1 parameter instead of the num2 parameter. If you want to use both positional and keyword arguments, all the positional arguments must come before the keyword arguments.

In Python, optional arguments can be implemented by specifying a default value for a parameter in the function header. This can be done using syntax like «def func(num1, num2=10):». This makes the num2 parameter totally optional. If it’s not specified in the function call, num2 will assume the default value of 10.

This method of using arguments is great when working with functions that have some required arguments, which you can use as positional arguments, and any additional optional arguments can be keyword arguments. This makes it clear which of the arguments passed were optional and which were required. Many times there can be a large number of optional arguments, and it would be impractical to refer to them without using keyword arguments.

Using Only Positional Arguments

Another way to resolve this error is to exclusively use positional arguments in your function call:

>>> func(1, 2)
Num 1: 1, Num 2: 2

This can be great when you have a few arguments and you want to keep things simple. However, this could make the code harder to understand as other developers don’t know what each argument means right away. They would have to look at the function definition or the function documentation. And it’s even worse as the number of arguments increases. It is also impossible to use this method with optional arguments, without passing the default values again in the function call. This is a bit redundant and prone to errors when specifying default values repeatedly in the function calls.

Using Only Keyword Arguments

Finally, you can fix the error by using only keyword arguments:

>>> func(num1=1, num2=2)
Num 1: 1, Num 2: 2
>>>
>>> func(num2=2, num1=1)
Num 1: 1, Num 2: 2

Using this method, you can explicitly state which parameter equals which value, and the order of the arguments doesn’t matter since Python knows which parameter name to map each value to. It also makes the code easier for other developers to understand since there is less ambiguity.

This method also easily works with optional arguments. The only downside of this method is that it can be pretty verbose, and you would need to know the name of every parameter when writing a function call.

*args and **kwargs Parameters in Python

Two more ways to define and pass arguments in Python are *args and **kwargs. Using the single asterisk * or double asterisk ** syntax before a parameter name in a function header allows you to pass a varying number of non-keyword or keyword arguments in a function call. Note that *args stands for «arguments» and **kwargs stands for «keyword arguments».

*args accepts any number of positional arguments which are ingested as a tuple object, with each argument value being included as an element in the tuple. **kwargs accepts any number of keyword arguments which are ingested as a dictionary object. Each keyword argument name is included as a key in the dictionary, and each corresponding keyword argument value is included as a value in the dictionary.

For example:

>>> def f_args(*args):
...     print(args)
... 
>>> f_args(1, 2, 3)
(1, 2, 3)
>>> 
>>> def f_kwargs(**kwargs):
...     print(kwargs)
... 
>>> f_kwargs(a=1, b=2, c=3)
{'a': 1, 'b': 2, 'c': 3}

Here, we have two functions f_args and f_kwargs, which define *args and **kwargs parameters, respectively. You can see that *args stores a tuple of positional arguments in the variable args, and **kwargs stores a dictionary of keyword arguments in the variable kwargs.

Note that the variable names args and kwargs can be replaced with any other variable name, only the single * or double ** asterisk syntax is important to define how the arguments are ingested.

Here is another example usage of *args:

>>> def my_sum(*nums):
...     total = 0
...     for num in nums:
...             total += num
...     return total
... 
>>> my_sum(1, 2, 3)
6
>>>
>>> my_sum(2, 2, 2, 5)
11
>>>
>>> my_sum()
0

The my_sum function accepts any amount of positional arguments (or no arguments at all), and returns the sum of those arguments.

You can also use both *args and **kwargs together:

>>> def f(*args, **kwargs):
...     print(args, kwargs)
... 
>>> f(1, 2, a=3)
(1, 2) {'a': 3}

Here, all the positional arguments are included in the tuple args, and all the keyword arguments are included in the dictionary kwargs. Note that all positional * parameters must come before keyword ** parameters, or you’ll get an invalid syntax error as below:

>>> def f(**kwargs, *args):
  File "<stdin>", line 1
    def f(**kwargs, *args):
                    ^
SyntaxError: invalid syntax
>>> 

Summary

In this article, you learned how to fix the Python error `SyntaxError: Positional Argument Follows Keyword Argument» using various methods and learned about the different types of arguments in Python.

First, you learned what arguments are and some terminology regarding arguments. Then you learned what positional arguments are and what keyword arguments are.

Next, you saw when the «SyntaxError: Positional Argument Follows Keyword Argument» occurs with an example, and why it occurs. Which was followed, with various methods to fix the error and the benefits and drawbacks of each method.

Additionally, you learned what the *args and **kwargs arguments are in Python and how to use them.

Next Steps

To learn more about the basics of Python, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you’ll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.

References

  1. Python args and kwargs: Demystifie — https://realpython.com/python-kwargs-and-args/
  2. Python Function Arguments — https://www.programiz.com/python-programming/function-argument

Final Notes

Понравилась статья? Поделить с друзьями:
  • Syntaxerror invalid syntax python ошибка
  • Svensson body labs ошибка err4
  • Syntaxerror cannot assign to operator ошибка
  • Sven coop ошибка fatal error
  • Syntax error at or near ошибка