Cannot assign to function call ошибка

In Python, if we put parenthesis after a function name, e.g, main(), this indicates a function call, and its value is equivalent to the value returned by the main() function.

The function-calling statement is supposed to get a value.
For example:

total = add(1, 4)
#total = 5

And if we try to assign a value to the function call statement in Python, we receive the Syntax error.

 add(1, 4) = total

SyntaxError: cannot assign to function call here. Maybe you meant ‘==’ instead of ‘=’?

In Python 3.10, we receive some extra information in the error that suggests that we may want to perform the comparison test using the == operator instead of assigning =.

In this statement

invest(initial_amount,top_company(5,year,year+1)) = subsequent_amount

we can conclude two things:

1. illegal use of assignment operator.
This is a syntax error when we assign a value or a value return by a function to a variable. The variable should be on the left side of the assignment operator and the value or function call on the right side.

Example

subsequent_amount = invest(initial_amount,top_company(5,year,year+1)) 

2. forget to put double == operators for comparison.

This is a semantic error when we put the assignment operator (=) instead of the comparison (==).

Example

invest(initial_amount,top_company(5,year,year+1)) == subsequent_amount

Function calls and variable assignments are distinct operations in Python. Variable assignments are helpful for code structure, and function calls help reuse code blocks. To assign the result of a function to a variable, you must specify the variable name followed by an equals = sign, then the function you want to call. If we do not follow this syntax, the Python interpreter will raise “SyntaxError: can’t assign to function call” when you execute the code.

This tutorial will go through the correct use of variable assignments and function calls. We will go through the premise of syntax errors and look at example scenarios that raise the “SyntaxError: can’t assign to function call” error and solve it.

Table of contents

  • SyntaxError: can’t assign to function call
  • Example: Square Root Function for an Array
    • Solution
  • Summary

SyntaxError: can’t assign to function call

In Python, variable assignment uses the following syntax

particle = "Muon"

The variable’s name comes first, followed by an equals sign, then the value the variable should hold. We can say this aloud as

particle is equal to Muon“.

You cannot declare a variable by specifying the value before the variable. This error occurs when putting a function call on the left-hand side of the equal sign in a variable assignment statement. Let’s look at an example of the error:

def a_func(x):

    return x ** 2

a_func(2) = 'a_string'
    a_func(2) = 'a_string'
    ^
SyntaxError: cannot assign to function call

This example uses a function called a_func, which takes an argument x and squares it as its output. We call the function and attempt to assign the string ‘a_string’ to it on the right-hand side of the equal sign. We will raise this error for both user-defined and built-in functions, and the specific value on the right-hand side of the equals sign does not matter either.

Generally, SyntaxError is a Python error that occurs due to written code not obeying the predefined rules of the language. We can think of a SyntaxError as bad grammar in everyday human language.

Another example of this Python error is “SyntaxError: unexpected EOF while parsing“. This SyntaxError occurs when the program finishes abruptly before executing all of the code, likely due to a missing parenthesis or incorrect indentation.

Example: Square Root Function for an Array

Let’s build a program that iterates over an array of numbers and calculates the square root of each, and returns an array of the square root values.

To start, we need to define our list of numbers:

square_numbers = [4, 16, 25, 36, 49, 64]

Then we define our function that calculates the square root of each number:

def square_root(numbers):

   square_roots = []

   for num in numbers:

       num_sqrt = num ** 0.5

       square_roots.append(num_sqrt)

   return square_roots

Let’s try to assign the value it returns to a variable and print the result to the console

square_root(square_numbers) = square_roots

print(square_roots)
    square_root(square_numbers) = square_roots
    ^
SyntaxError: cannot assign to function call

The error occurs because we tried to assign a value to a function call. The function call in this example is square_root(square_numbers). We tried to assign the value called square_roots to a variable called square_root(square_numbers).

When we want to assign the response of a function to a variable, we must declare the variable first. The order is the variable name, the equals sign, and the value assigned to that variable.

Solution

To solve this error, we need to reverse the variable declaration order.

square_roots = square_root(square_numbers)

print(square_roots)
[2.0, 4.0, 5.0, 6.0, 7.0, 8.0]

Our code runs successfully and prints the square root numbers to the console.

Summary

Congratulations on reading to the end of this tutorial. The error “SyntaxError: can’t assign to function call” occurs when you try to assign a function call to a variable. Suppose we put the function call before a variable declaration. In that case, the Python interpreter will treat the code as trying to assign a value to a variable with a name equal to the function call. To solve this error, ensure you follow the correct Python syntax for variable assignments. The order is the variable name first, the equals sign, and the value to assign to that variable.

Here are some other SyntaxErrors that you may encounter:

  • SyntaxError: unexpected character after line continuation character
  • SyntaxError: ‘return’ outside function

Go to the online courses page on Python to learn more about Python for data science and machine learning.

Have fun and happy researching!

When programming with Python, the understanding of the “SyntaxError: cannot assign to function call” error boils down to understanding these three topics:

  • What is SyntaxError?
  • Understanding variable assignment and
  • How to call a function.

Let’s discuss those three before we go into the actual causes of the “Can’t Assign to Function Call” error.

What is SyntaxError?

A SyntaxError is a Python error raised when our code violates the language’s predefined rules.

Understanding variable assignment

One of the Python rules governs how to define a variable. It states that (paraphrased):

When declaring a variable, the variable name comes first, followed by an assignment operator (=), then the value“.

Going against that rule leads to SyntaxError.

A Python function is called by using its name followed by parentheses. If the function accepts arguments, then pass the arguments inside the parenthesis, for example.

def multiply1(a, b):

    return a * b

# Function call — calling the multiply1 function with the two arguments.

multiply1(4, 6)

Note that a Python function returns a value (thus, a function call evaluates to a value). Therefore, we can assign the function call to a variable, as shown below.

val1 = multiply1(5.6, 6)

print(val1)

Output:

We are now ready to discuss some common causes of “Can’t Assign to Function Call” and their solutions.

Causes and Solutions to “Can’t Assign to Function Call” Error

This Section discusses four common causes of the error and how to solve each.

Case 1: Specifying a function call to the left-hand side of the assignment operator (=)

As stated earlier, the variable assignment rule requires the variable name to be on the left side of the “=” operator and the value on the right.

That is also true for the function call (because it returns a value) – a function call should be defined on the right-hand side of the assignment operator. Doing the opposite leads to the “Can’t Assign to Function Call” error, for example.

def ApplyDiscount(amount):

    if amount > 1000:

        return amount (0.1 * amount)

    return amount (0.02 * amount)

# Wrong way to assign a function call

ApplyDiscount(2150) = result3

Output:

# Another wrong way

ApplyDiscount(2150) = 456

Solution

The correct way to assign a function call is to keep it on the right side of the “=” operator and the variable name on the left. For example,

# Correct way of assigning a function call

result1 = ApplyDiscount(1350)

print(result1)

# Another right way

result2 = ApplyDiscount(260)

print(result2)

Output:

Case 2: Confusing comparison and assignment operator

Sometimes, you use the assignment operator (=) when you meant to use the comparison operator (==).

def Add2(a, b):

    return a + b

# This leads to the error

Add2(3, 4) = 7

If you want to compare the result of the function call with another value, use the comparison operator (==), as shown below.

print(Add2(3, 4) == 7)

Output:

Add2(3,4) returns 7, therefore, Add2(3, 4) == 7 evaluates to True.

Case 3: Using square brackets when assigning an item to a dictionary or list

You can also face the “Can’t Assign to Function Call” error when you attempt to assign or add an item into a dictionary using parentheses, as shown below.

dict1 = {«Id»: 1, «City»: «San Diego», «Name»: «Allan»}

dict1(«City») = «New York»

Output:

SyntaxError: cannot assign to function call here. Maybe you meant ‘==’ instead of ‘=’?

You will also experience the same when updating an element in a list.

lst1 = [1, «San Diego», «Allan»]

lst1(0) = 5

Output:

SyntaxError: cannot assign to function call here. Maybe you meant ‘==’ instead of ‘=’?

Solution

Use square brackets (not parentheses) to update an item in a list or Python dictionary, as shown in the following examples.

lst1 = [1, «San Diego», «Allan»]

lst1[0] = 5

# Update the first element in the list.

print(lst1)

dict1 = {«Id»: 1, «City»: «San Diego», «Name»: «Allan»}

# Update an item on a dictionary.

dict1[«City»] = «New York»

print(dict1)

Output

[5, ‘San Diego’, ‘Allan’]

{‘Id’: 1, ‘City’: ‘New York’, ‘Name’: ‘Allan’}

Case 4: Incorrect syntax when using the “in” operator in a loop

Here is an example of that.

def name1(name):

    return list(name)

result = [i for name1(«Smith») in i]

print(result)

Output:

SyntaxError: cannot assign to function call

Note that the order in the list comprehension is incorrect. We should iterate over the result of a function call, not over the element of the return value of the function. The correct code should be

def name1(name):

    return list(name)

result = [i for i in name1(«Smith»)]

print(result)

Output:

[‘S’, ‘m’, ‘i’, ‘t’, ‘h’]

Conclusion

This post discussed the causes and solutions to the “SyntaxError: cannot assign to function call” error. After going through the four common cases that lead to the error discussed in this article, you should be able to identify and fix this error when it arises.

Python shows SyntaxError: cannot assign to function call error when you assign a value to the result of a function call.

Here’s an example code that triggers this error:

def add(a, b):
    return a + b


result = add(3, 4)
add(3, 4) = 5  # ❌ SyntaxError

In the code above, the number 5 is assigned to the result of calling the add() function.

Python responds with the error below:

    add(3, 4) = 5
    ^^^^^^^^^
SyntaxError: cannot assign to function call here. 
Maybe you meant '==' instead of '='?

In Python, a function call is an expression that returns a value. It cannot be used as the target of an assignment.

To fix this error, you need to avoid assigning a value to a function call result.

When you want to declare a variable, you need to specify the variable name on the left side of the operator and the value on the right side of the operator:

# Assign value 5 to the variable x
x = 5

You can also assign the function call result to a variable as follows:

x = add(3, 4)
print(x)  # 7

If you want to compare the result of a function call to a value, you need to use the equality comparison operator ==.

The following code example is valid because it checks whether the result of add() function equals to 5:

# Checks whether add(3, 4) equals to 5
x = 5
add(3, 4) == x  # ✅

A single equal operator = assigns the right side of the operator to the left side, while double equals == compares if the left side is equal to the right side.

You can even assign the result of the comparison to a variable like this:

result = add(3, 4) == x  # ✅
print(result)  # False

Finally, you can also encounter this error when working with Python iterable objects (like a list, dict, or tuple)

You can’t reassign or compare a list element as long as you used the parentheses as shown below:

numbers = [1, 2, 3]

numbers(2) = 5  # ❌ SyntaxError
numbers(2) == 5  # ❌ TypeError

When you use parentheses with the equality comparison operator, Python responds with TypeError: 'list' object is not callable.

Whether you want to reassign or compare a list element, you need to use the square brackets like this:

numbers = [1, 2, 3]

numbers[2] = 5  # ✅

print(numbers)  # [1, 2, 5] 

print(numbers[2] == 5)  # True

And that’s how you fix Python SyntaxError: cannot assign to function call error.

Would you like to learn more about the “SyntaxError: can’t assign to function call” error and how to troubleshoot and fix it  🤔? Don’t fret; we have given you answers. 😀

Python’s programming language is based on function calls and variable definitions. Therefore, the source code can be used repeatedly. The usage of arguments allows for the dynamic activation of functions, which may be called while altering specific values to provide a new result or stream of instructions. Inappropriate use of it will result in a syntax error.

The SyntaxError: can’t assign to function call error in Python occurs when you try to assign a value to the result of a function call. This is not allowed in Python because function calls are expressions and cannot be used as values (the left side of an assignment statement).

To resolve this error, you need to either assign the result of the function call to a variable and then assign a value to the variable or modify the function to return a mutable data structure that can be modified, such as a list or a dictionary.

So without further ado, let’s dive deep into the topic and see some causes and solutions! 👇

Table of Contents
  1. What is a Function Call in Python?
  2. Why Does the “SyntaxError: Cannot Assign To Function Call” Error in Python Occur?
  3. How to Fix the “SyntaxError: Can’t Assign to Function Call” Error in Python?

What is a Function Call in Python?

In programming, a function call is an act of executing a function. A function is a block of code that performs a specific task and can be called multiple times from different parts of your code.

When you call a function, you pass in arguments (if required), and the function performs its task and returns a result. The result of the function call can be assigned to a variable, used as an argument for another function call, or simply displayed to the user.

Here’s an example of a function call in Python:

Code

def my_function(x):

    return x * 2




result = my_function(10)

print(result)

Output

20

In this example, the function my_function takes in a single argument x, multiplies it by 2, and returns the result. Next, the result of calling my_function(10) is assigned to the variable result, and finally, the value of the result is printed, which is 20.

Why Does the “SyntaxError: Cannot Assign To Function Call” Error in Python Occur?

When you attempt to assign a function call to a variable, the error SyntaxError: can’t assign to function call is shown. This occurs when you assign a function call’s value to a variable in the wrong sequence. Use the appropriate variable declaration syntax to fix this issue. The value you wish to give the variable occurs after the equals sign and before the variable name.

For example, the following code would cause this error:

 Code

def my_function():

    return 82




my_function() = 79

Output

SyntaxError: cannot assign to function call here error in PHP

 This code will result in a SyntaxError: cannot assign to function call error. This error occurs because you are trying to assign a value to the result of the function my_function, but in Python, you can only assign values to variables or object attributes, not to function calls.

When you call a function, it returns a value, but that value is not a variable to that you can assign a new value. For example, in the code you posted, my_function() returns the value 89, but you are trying to assign the value 79 to it, which is not allowed.

To fix the error, you need to assign the result of the function call to a variable and then assign a value to that variable.

Here is an example to demonstrate the solution:

Code

def my_function():

    return 89



result = my_function()

result = 79


print("The value:",result)

Output

The value: is 79

The code first defines a function my_function which returns the value 89. Then, the result of calling my_function is assigned to the variable result. Finally, the value of the result is reassigned to 79, and the final value of the result is printed.

Conclusion

In conclusion, the SyntaxError: cannot assign to function call occurs in Python when you attempt to assign a value to a function call, which is not allowed. You can only assign values to variables or object attributes in Python, not to function calls.

To resolve this error, you need to assign the result of the function call to a variable and then assign a value to that variable. This allows you to manipulate the result of the function call and use it in your code.

In this way, understanding and resolving the SyntaxError: can’t assign to function call is essential to becoming a proficient Python programmer.

If you found this helpful article, please comment below 👇 and let us know which solutions worked best for you.

Zeeshan is a detail-oriented software engineer and technical content writer with a Bachelor’s in Computer Software Engineering and certifications in SEO and content writing. Thus, he has a passion for creating high-quality, SEO-optimized technical content to help companies and individuals document ideas to make their lives easier with software solutions. With over 150 published articles in various niches, including computer sciences and programming languages such as C++, Java, Python, HTML, CSS, and Ruby, he has a proven track record of delivering well-researched and engaging technical content.

Понравилась статья? Поделить с друзьями:
  • Candy optima ошибка е03
  • Cannot add foreign key constraint ошибка
  • Candy krio vital ошибка e0
  • Cannot access before initialization js ошибка
  • Candy сушильная машина ошибка loc