Cannot assign to function call как исправить

Function calls and variable assignments are distinct operations in Python. Variable assignments are helpful for code structure, and function calls help

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!

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

To assign the result of a function to a variable, you must specify the variable name, followed by an equals sign, followed by the function you want to call. If you do not follow this order, you’ll encounter a “SyntaxError: can’t assign to function call” error.

This guide discusses what this error means and why it is raised. We’ll walk through an example of this error to help you understand how you can fix it in your code.

Get offers and scholarships from top coding schools illustration

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Access exclusive scholarships and prep courses

Select your interest

First name

Last name

Email

Phone number

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

SyntaxError: can’t assign to function call

Python variables are defined using the following syntax:

favorite_cheese = “Stilton”

The name of a variable comes first. The variable name is followed by an equals sign. After this equals sign, you can specify the value a variable should hold.

If you read this out loud as if it were a sentence, you’ll hear:

“Favorite cheese is equal to Stilton.”

You must follow this order when you declare a variable. You cannot declare a variable by specifying the value first and the name of a variable last.

The SyntaxError: can’t assign to function call error occurs if you try to assign a value to a function call. This means that you’re trying to assign a value to a function instead of trying to assign a function call to a variable.

An Example Scenario

We’re building a program that creates a list of all the sandwiches that have been sold more than 1,000 times at a shop in the last month.

To start, define a list of sandwiches:

sandwiches = [
	{ "name": "Egg Salad", "sold": 830 },
	{ "name": "Ham and Cheese", "sold": 1128 },
	{ "name": "Cheese Supreme", "sold": 1203 },
	{ "name": "Tuna Mayo", "sold": 984 }
]

Our list of sandwiches contains four dictionaries. An individual dictionary contains information about one sandwich. Next, we define a function that calculates which sandwiches have been sold more than 1,000 times:

def sold_1000_times(sandwiches):
	top_sellers = []

	for s in sandwiches:
		if s["sold"] > 1000:
			top_sellers.append(s)

	return top_sellers

This function accepts one argument: a list of sandwiches. We iterate through this list of sandwiches using a for loop. If a sandwich has been sold more than 1000 times in the last month, that sandwich is added to the 1000_sales list. Otherwise, nothing happens.

Next, we call our function and assign the value it returns to a variable:

sold_1000_times(sandwiches) = top_sellers
print(top_sellers)

We’ve assigned our function call to the variable top_sellers. We then print that value to the console so we can see the sandwiches that have been sold more than 1,000 times.

Let’s run our code:

  File "main.py", line 17
	sold_1000_times(sandwiches) = top_sellers
	^
SyntaxError: cannot assign to function call

We receive an error message.

The Solution

Our code does not work because we’re trying to assign a value to a function call.

When we want to assign the response of a function to a variable, we must declare the variable like any other. This means the variable name comes first, followed by an equals sign, followed by the value that should be assigned to that variable.

Our code tries to assign the value top_sellers to a variable called sold_1000_times(sandwiches):

sold_1000_times(sandwiches) = top_sellers

This is invalid syntax. To solve this error, we need to reverse the order of our variable declaration:

top_sellers = sold_1000_times(sandwiches)

The name of our variable now comes first. The value we want to assign to the variable comes after the equals sign. Let’s run our program:

[{'name': 'Ham and Cheese', 'sold': 1128}, {'name': 'Cheese Supreme', 'sold': 1203}]

Our code returns a list of all the sandwiches that have been sold more than 1,000 times.

Conclusion

The “SyntaxError: can’t assign to function call” error is raised when you try to assign a function call to a variable.

This happens if you assign the value of a function call to a variable in reverse order. To solve this error, make sure you use the correct syntax to declare a variable. The variable name comes first, followed by an equals sign, followed by the value you want to assign to the variable.
Now you’re ready to solve this error in your own Python programs!

Venus profile photo

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»

Venus, Software Engineer at Rockbot

In this Python tutorial, we will discuss how to fix an error, syntaxerror return outside function python, and can’t assign to function call in python The error return outside function python comes while working with function in python.

In python, this error can come when the indentation or return function does not match.

Example:

def add(x, y):
  sum = x + y
return(sum)
print(" Total is: ", add(20, 50))

After writing the above code (syntaxerror return outside function python), Ones you will print then the error will appear as a “ SyntaxError return outside function python ”. Here, line no 3 is not indented or align due to which it throws an error ‘return’ outside the function.

You can refer to the below screenshot python syntaxerror: ‘return’ outside function

Syntaxerror return outside function python
python syntaxerror: ‘return’ outside function

To solve this SyntaxError: return outside function python we need to check the code whether the indentation is correct or not and also the return statement should be inside the function so that this error can be resolved.

Example:

def add(x, y):
  sum = x + y
  return(sum)
print(" Total is: ", add(20, 50))

After writing the above code (syntaxerror return outside function python), Once you will print then the output will appear as a “ Total is: 70 ”. Here, line no. 3 is resolved by giving the correct indentation of the return statement which should be inside the function so, in this way we can solve this syntax error.

You can refer to the below screenshot:

Syntaxerror return outside function python
return outside function python

SyntaxError can’t assign to function call in python

In python, syntaxerror: can’t assign to function call error occurs if you try to assign a value to a function call. This means that we are trying to assign a value to a function.

Example:

chocolate = [
     { "name": "Perk", "sold":934 },
     { "name": "Kit Kat", "sold": 1200},
     { "name": "Dairy Milk Silk", "sold": 1208},
     { "name": "Kit Kat", "sold": 984}
]
def sold_1000_times(chocolate):
    top_sellers = []
    for c in chocolate:
        if c["sold"] > 1000:
            top_sellers.append(c)
    return top_sellers
sold_1000_times(chocolate) = top_sellers
print(top_sellers)

After writing the above code (syntaxerror: can’t assign to function call in python), Ones you will print “top_sellers” then the error will appear as a “ SyntaxError: cannot assign to function call ”. Here, we get the error because we’re trying to assign a value to a function call.

You can refer to the below screenshot cannot assign to function call in python

SyntaxError can't assign to function call in python
SyntaxError can’t assign to function call in python

To solve this syntaxerror: can’t assign to function call we have to assign a function call to a variable. We have to declare the variable first followed by an equals sign, followed by the value that should be assigned to that variable. So, we reversed the order of our variable declaration.

Example:

chocolate = [
     { "name": "Perk", "sold":934 },
     { "name": "Kit Kat", "sold": 1200},
     { "name": "Dairy Milk Silk", "sold": 1208},
     { "name": "Kit Kat", "sold": 984}
]
def sold_1000_times(chocolate):
    top_sellers = []
    for c in chocolate:
        if c["sold"] > 1000:
            top_sellers.append(c)
    return top_sellers
top_sellers
 = sold_1000_times(chocolate)
print(top_sellers)

After writing the above code (cannot assign to function call in python), Ones you will print then the output will appear as “[{ “name”: “Kit Kat”, “sold”: 1200}, {“name”: “Dairy Milk Silk”, “sold”: 1208}] ”. Here, the error is resolved by giving the variable name first followed by the value that should be assigned to that variable.

You can refer to the below screenshot cannot assign to function call in python is resolved

SyntaxError can't assign to function call in python
SyntaxError can’t assign to function call in python

You may like the following Python tutorials:

  • Remove character from string Python
  • Create an empty array in Python
  • Invalid syntax in python
  • syntaxerror invalid character in identifier python3
  • How to handle indexerror: string index out of range in Python
  • Unexpected EOF while parsing Python
  • Python built-in functions with examples

This is how to solve python SyntaxError: return outside function error and SyntaxError can’t assign to function call in python. This post will be helpful for the below error messages:

  • syntaxerror return outside function
  • python syntaxerror: ‘return’ outside function
  • return outside of function python
  • return’ outside function python
  • python error return outside function
  • python ‘return’ outside function
  • syntaxerror return not in function

Bijay Kumar MVP

Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

Cover image for How to fix "SyntaxError: cannot assign to function call here" in Python

Reza Lavarian

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

Python raises “SyntaxError: cannot assign to function call here. Maybe you meant ‘==’ instead of ‘=’?” when a function call is the left-hand side operand in a value assignment:

# Raises 🚫 SyntaxError
f() = 23

Enter fullscreen mode

Exit fullscreen mode

Python also provides you a hint, assuming you meant to use the equality operator (==):

File /dwd/sandbox/test.py, line 4
  my_func() = 12
  ^^^^^^^^
SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?

Enter fullscreen mode

Exit fullscreen mode

Most of the time, the reason is a typo in your code — usually a missing =.

How to fix «SyntaxError: cannot assign to function call»

The long error «SyntaxError: cannot assign to function call here. Maybe you meant ‘==’ instead of ‘=’?» occurs under various scenarios:

  1. Using the assignment operator (=) instead of the equality operator (==)
  2. Wrong left-hand side operand
  3. Incomplete list comprehension

Let’s see some examples.

Using the assignment operator (=) instead of the equality operator (==): One of the most common causes of this SyntaxError is using the assignment operator (=) instead of the equality operator (==) in value comparisons:

def my_func():
    return 12

# 🚫 SyntaxError
if my_func() = 12:
    print ('Passed')

Enter fullscreen mode

Exit fullscreen mode

In the above example, we’re trying to compare the return value of my_func() to the value of 12. However, the = operator isn’t a comparison operator.

To fix the error, we use the equality operator (==) instead:

def my_func():
    return 12

if my_func() == 12:
    print ('Passed')

# Output: Passed

Enter fullscreen mode

Exit fullscreen mode

Wrong left-hand side operand (in assignment statements): Assignment statements bind names to values. (e.g., age = 25)

Based on Python syntax and semantics, the left-hand side of the assignment operator (=) should always be an identifier — an arbitrary name you choose for a specific value (a.k.a variable). For instance, age for 25.

That said, if you have a function call as the left-hand side operand, you’ll get the «SyntaxError: cannot assign to function call here. Maybe you meant ‘==’ instead of ‘=’?» error.

def get_age():
    return 25

# 🚫 SyntaxError
get_age() = age

Enter fullscreen mode

Exit fullscreen mode

If your code looks like the above, switch sides:

def get_age():
    return 25

age = get_age()

Enter fullscreen mode

Exit fullscreen mode

Incomplete list comprehension: A confusing scenario that leads to this SyntaxError is a wrong list comprehension statement.

We usually use list comprehensions to generate a list where each element is the result of an operation applied to each member of another sequence or iterable.

Imagine you have a range object from 1 to 10, and you want to calculate the square root of each element and store them in a separate list.

A list comprehension statement consists of brackets containing an expression (e.g., x**2) followed by a for clause (e.g., for x in range(1, 10)).

We can implement the above example like so:

squares = [x**2 for x in range(1, 10)]

print(squares)
# Output: [1, 4, 9, 16, 25, 36, 49, 64, 81]

Enter fullscreen mode

Exit fullscreen mode

In the above example, x**2 is applied to every item in our range. Now, if you accidentally replace the for keyword with in, you’ll get this SyntaxError:

# 🚫 SyntaxError
squares = [x**2 in x for range(1, 10)]

print(squares)

Enter fullscreen mode

Exit fullscreen mode

The reason is whatever follows for is supposed to be the variable that holds the current item on each iteration.

Alright, I think it does it. I hope this quick guide helped you solve your problem.

Thanks for reading.

❤️ You might like:

SyntaxError: ‘break’ outside loop in Python (Solved)
SyntaxError: invalid decimal literal in Python (Solved)
TypeError: can only concatenate str (not «list») to str (Fixed)
TabError: inconsistent use of tabs and spaces in indentation (Python)
How to fix the «TypeError: unhashable type: ‘dict'» error in Python

To assign a value to a variable in Python, we use the assignment operator between the variable name and value. And during this process, the variable name must be on the left side of the assignment operator and the value on the right side.

We can also write

functions

in Python that return values when they are called. But if we try to assign a value to a function call statement, we will receive the

SyntaxError: can’t assign to function call

error in Python.

In this Python guide, we will discuss why this error occurs in Python and how to solve it. We will also discuss an example that demonstrates this error in Python to get a better idea of this Python error. So let’s get started with the Error statement.

The PythonError Statement

SyntaxError: can’t assign to function call here. Maybe you meant '==' instead of '='?

is divided into two parts separated by colon

:

.


  1. Error Type

    (

    SyntaxError


    ):

    SyntaxError Occurs in Python when we write some wrong syntax in the program.

  2. Error Message (


    can’t assign to function call



    This is the actual error message telling us that we are trying to assign a value to a function call statement in Python, which is invalid.


Error Reason

In Python, we can use the assignment operator

=

to assign a value to a variable name, but if we try to assign a value to a function call statement, then we receive the

SyntaxError: can’t assign to function call

Error.


Example

total = 0

bill = [20, 30, 40, 50]

# assign value to sum() function (error)
sum(bill) = total

print(total)


Output

File "main.py", line 6
sum(bill) = total
^
SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?


Break the Code

In the above example, we are getting the error at line 6 with

sum(bill) = total

the statement. The reason for the error is quite obvious. In line 6, we are trying to assign the value of

total

to the function call statement

sum(bill)

, which is invalid syntax in Python.


Solution

The solution for the above example is very simple. All we need to do is put the

total

variable on the left side of the assignment operator

=

, and

sum(bill)

function call on the right side. So the value of the

sum(bill)

statement can be assigned to the total variable.

total =0

bill = [20, 30, 40, 50]

# assign value to total
total =sum(bill)

print(total)


Output

140


Common Scenario

The most common scenario where many new Python learners commit this mistake is when they misplace the variable and function call statement during the assignment operation. The variable to which we want to assign the value must be on the left side of the assignment operator

=

, and the function that returns the value must be on the right side of the assignment operator.

Let’s take an example where and write the function call on the left and variable name on the right side.


Error Example

def percentage(marks):
    marks_obtain = sum(marks)
    maximum_marks = len(marks) *100

    return round((marks_obtain/maximum_marks)*100, 2)

my_marks = [90, 90, 90, 90, 90]

# assing value to function call 
percentage(my_marks) = total_percentage
print(total_percentage)


Output

 File "main.py", line 9
percentage(my_marks) = total_percentage
^
SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?


Break The code

If we read the error statement, we can tell that at line 9, we are getting this error because we are trying to assign the

total_percentage

variable to the

percentage(my_marks)

function call statement. And according to the Python syntax, it is illegal.


Solution

To solve this problem, we need to swap the position of the

percentage(my_marks)

function call and

total_percentage

variable. So the returned value of

percentage()

could be assigned to the

total_percentage

variable.

def percentage(marks):
    marks_obtain = sum(marks)
    maximum_marks = len(marks) *100

    return round((marks_obtain/maximum_marks)*100, 2)

my_marks = [86, 99, 95, 80, 70]

# assing value to function call
total_percentage = percentage(my_marks)

print(total_percentage, '%')


Output

86.00 %


Final Thoughts!

The

SyntaxError: can’t assign to function call

error occurs in Python when we try to assign a value to a function call statement. This exception is a result of when we write the variable on the right side and function call on the left side of the assignment operation.

To debug this error, we must make sure that whenever we try to assign a return value of a function call to a variable, the function must be on the right side and the variable on the left side.

If you are still getting this error in your Python program, you can share your code in the comment section. We will try to help you in debugging.


People are also reading:

  • Python typeerror: ‘str’ object is not callable Solution

  • Python TypeError: ‘float’ object cannot be interpreted as an integer Solution

  • Python TypeError: ‘method’ object is not subscriptable Solution

  • Python TypeError: ‘NoneType’ object is not callable Solution

  • Python ValueError: invalid literal for int() with base 10: Solution

  • Python Error: TypeError: ‘tuple’ object is not callable Solution

  • Python TypeError: ‘function’ object is not subscriptable Solution

  • What is a constructor in Python?

  • How to Play sounds in Python?

  • Python SyntaxError: unexpected EOF while parsing Solution

Содержание

  1. How to Solve Python SyntaxError: can’t assign to function call
  2. Table of contents
  3. SyntaxError: can’t assign to function call
  4. Example: Square Root Function for an Array
  5. Solution
  6. Summary
  7. Python SyntaxError: can’t assign to function call
  8. Table of Contents
  9. Introduction
  10. When Will You Encounter this Error?
  11. What is a SyntaxError?
  12. Understanding Variable Assignment
  13. What is a Function Call?
  14. SyntaxError Resulting from Confusion Between Comparison Operator (==) and Assignment (=)
  15. Proper Way to Assign a Function to a Variable
  16. Summary
  17. Next Steps
  18. Syntax error cannot assign to function call
  19. SyntaxError: cannot assign to function call here (Python) #
  20. Conclusion #
  21. Python SyntaxError: can’t assign to function call Solution
  22. Table of Content
  23. Python Error: SyntaxError: can’t assign to function call
  24. Error Reason
  25. Common Scenario
  26. Final Thoughts!

How to Solve Python SyntaxError: can’t assign to function call

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

In Python, variable assignment uses the following syntax

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:

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:

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

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

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.

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:

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

Источник

Python SyntaxError: can’t assign to function call

Table of Contents

Introduction

Function calls and variable assignments are powerful tools in Python. They allow us to make our code more efficient and organized. Function calls allow us to easily reuse blocks of code and variable assignments help us keep our code organized. However, if used incorrectly we can run into a SyntaxError , which is a specific type of Python exception. Other types include AttributeError, and TypeError, but today we’ll stick to this specific SyntaxError.

In this article, we will explore variable assignment, function calls, and syntax errors. We will then use our understanding of these concepts to fix or avoid the «SyntaxError: can’t assign to function call» error in Python.

When Will You Encounter this Error?

This error occurs when putting a function call on the left-hand side of the equal sign in a variable assignment statement. An example of this error is shown below:

This example uses a simple function named test_func that takes an argument x and returns x plus 1 as its output. Then the function is called on the left-hand side of the equal sign with an attempt to assign the string ‘test_str’ to it on the right-hand side of the equals sign.

Below is another example, where the built-in function list(. ) is called on the left-hand side of the equal sign and the integer 1 is assigned to it on the right-hand side of the equals sign. This code is in a module named assign_func_call.py :

Then I run the script on the command line to produce the same error:

Through these examples, we see that the specific function that is called on the left side of the equation doesn’t matter — the error happens with both user-defined functions and built-in functions. Similarly, the specific value on the right side doesn’t either, whether it is a string, integer, or anything else.

The error is caused by the incorrect arrangement of the function call and object (string, integer, list, etc) in the assignment statement, hence it being a SyntaxError .

What is a SyntaxError?

A SyntaxError is a Python error that occurs due to writing code that doesn’t obey the predefined rules of the language. It is a very common type of error due to human error occurring in the process of typing and using computers. The Python interpreter gives us helpful information when this type of error occurs, so fixing most syntax errors is pretty simple.

Let’s consider the SyntaxError above, where the error occurs because the return statement is clearly misspelled.

The first line tells us the line number where the error occurs, which is usually all you need to fix a SyntaxError , since once you know what line it’s on, it is sometimes pretty obvious what the problem is. If the error persists, the last line of the SyntaxError gives more detailed information.

When looking for syntax errors, the Python interpreter scans the code from top to bottom. Furthermore, the Python interpreter specifically looks for syntax errors before any other type of error. For example, let’s start by looking at this simple script that throws a different type of error:

Now let’s run the code on the command-line:

In this Python script, x is assigned to a value not defined — y , and running the script produces a NameError (this is not a syntax error). Now let’s see another example:

Here the list() = 1 line is after the x = y line, yet we still get a SyntaxError because Python checks for SyntaxError before any other error.

The official python documentation gives more information on syntax errors Python Docs.

Understanding Variable Assignment

Variable assignment in Python is used temporarily give values to references that we can use in the code. We assign a variable to a value with the = sign as follows:

In this example, we assign the integer value 1 to the variable x and then print it to the console.

Python variable names are restricted to containing letters, digits, or underscores, and must only start with letters or underscores. The order of operations is important too. The variable must always go before the equal sign. The value being assigned must always go on the right side of the equals sign. A variable will always refer to the value it is assigned until you assign it a different value.

What is a Function Call?

Functions are an essential part of Python. They allow blocks of code to be reused multiple times. Functions can also make use of arguments to make them dynamic, so that we can call the same function but change specific values resulting in a different output or flow of instructions. For example:

Here, the function func is defined and returns the sum of the two arguments x and y . To call the function, we first write the function name followed by the arguments in parentheses. In this example, the function call prints the output only because the code is executing in interactive mode. The function call returns the value supplied in the return statement, or null if no return statement exists.

Check out Learn Functions in Python 3 to get a deeper understanding of functions.

SyntaxError Resulting from Confusion Between Comparison Operator (==) and Assignment (=)

One reason you could run into the SyntaxError: can’t assign to function call error is that you confused or mistyped the comparison operator == (double equals sign) instead of the = (single equals sign) used for variable assignment.

The comparison operator == is used to check if two objects are equal, and will yield a boolean, either True or False. For example:

The list() function without arguments returns an empty list, so it’s equal to the empty list but not equal to integer 1. However, if we were to use a single equals sign by mistake = , Python thinks we are trying to assign the integer to the function call, and we get the SyntaxError :

Proper Way to Assign a Function to a Variable

There are two methods to assign a function to a variable. One method is to assign the result of a function call to a variable — like this:

Here, function func returns 1. Then we assign the result of this function call to the variable x , the function call being on the right side of the equal sign. Next, we print x to show that it now holds the value returned by the function call. This method is used a lot when programming, to avoid having to call the same function multiple times, since its result is now stored in our variable.

The second method is assigning the function itself to a variable:

In this example, calling function func and printing the result displays 1. However, then we assign func (without (), so it’s not a function call) to the variable x . Next, we call x to show that it returns 1 because it refers to the same function func . Finally, we assign the 2 to func (again no () so not a function call), and printing func prints 2. From this example, we learn that function names are just like variable names, and we can refer to the same function with a different name. We can also reassign the function name to another object, and it will then refer to that object.

Summary

In this article, we discussed the Python issue SyntaxError: can’t assign to function call . We explained why the error occurs and how to fix it.

We looked into what SyntaxError is and how to use the information provided by the Python interpreter to debug such an error. We also explored how variable assignment works and the proper syntax to use for an assignment statement. We then looked at the basic usage of a function call. Finally, we looked at proper ways to assign a function and its result to a variable.

Next Steps

Understanding function calls and variable assignments will not only allow you to avoid this type of syntax error, but will also allow you to write more organized and efficient code.

However, this is only one of such errors you will encounter when programming in Python. Our post Return Outside Function Error in Python explores another such Python error.

If you’re interested in learning 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.

Источник

Syntax error cannot assign to function call

Reading time В· 2 min

SyntaxError: cannot assign to function call here (Python) #

The Python «SyntaxError: cannot assign to function call here. Maybe you meant ‘==’ instead of ‘=’?» occurs when we try to assign to a function call. To solve the error, specify the variable name on the left, and the function call on the right-hand side of the assignment.

Here is an example of how the error occurs.

The error is caused because we are trying to assign a value to a function call.

Make sure the function returns what you expect, because functions that don’t explicitly return a value return None .

You can think of a variable as a container that stores a specific value (e.g. the value that the function returns).

You might also get the error when working with a dictionary.

The error is caused because we used parentheses instead of square brackets to add a new key-value pair to the dict.

Make sure to use square brackets if you have to access a key-value pair in a dictionary.

If you meant to perform an equality comparison, use double equals.

We use double equals == for comparison and single equals = for assignment.

The name of a variable must start with a letter or an underscore.

A variable name can contain alpha-numeric characters ( a-z , A-Z , 0-9 ) and underscores _ .

Note that variable names cannot start with numbers or be wrapped in quotes.

Variable names in Python are case-sensitive.

The 2 variables in the example are completely different and are stored in different locations in memory.

Conclusion #

The Python «SyntaxError: cannot assign to function call here. Maybe you meant ‘==’ instead of ‘=’?» occurs when we try to assign to a function call. To solve the error, specify the variable name on the left, and the function call on the right-hand side of the assignment.

Источник

Python SyntaxError: can’t assign to function call Solution

Vinay Khatri
Last updated on September 21, 2022

Table of Content

To assign a value to a variable in Python, we use the assignment operator between the variable name and value. And during this process, the variable name must be on the left side of the assignment operator and the value on the right side.

We can also write functions in Python that return values when they are called. But if we try to assign a value to a function call statement, we will receive the SyntaxError: can’t assign to function call error in Python.

In this Python guide, we will discuss why this error occurs in Python and how to solve it. We will also discuss an example that demonstrates this error in Python to get a better idea of this Python error. So let’s get started with the Error statement.

Python Error: SyntaxError: can’t assign to function call

The PythonError Statement SyntaxError: can’t assign to function call here. Maybe you meant ‘==’ instead of ‘=’? is divided into two parts separated by colon : .

  1. Error Type ( SyntaxError ): SyntaxError Occurs in Python when we write some wrong syntax in the program.
  2. Error Message ( can’t assign to function call This is the actual error message telling us that we are trying to assign a value to a function call statement in Python, which is invalid.

Error Reason

In Python, we can use the assignment operator = to assign a value to a variable name, but if we try to assign a value to a function call statement, then we receive the SyntaxError: can’t assign to function call Error.

Example

Output

Break the Code

In the above example, we are getting the error at line 6 with sum(bill) = total the statement. The reason for the error is quite obvious. In line 6, we are trying to assign the value of total to the function call statement sum(bill) , which is invalid syntax in Python.

Solution

The solution for the above example is very simple. All we need to do is put the total variable on the left side of the assignment operator = , and sum(bill) function call on the right side. So the value of the sum(bill) statement can be assigned to the total variable.

Output

Common Scenario

The most common scenario where many new Python learners commit this mistake is when they misplace the variable and function call statement during the assignment operation. The variable to which we want to assign the value must be on the left side of the assignment operator = , and the function that returns the value must be on the right side of the assignment operator.

Let’s take an example where and write the function call on the left and variable name on the right side.

Error Example

Output

Break The code

If we read the error statement, we can tell that at line 9, we are getting this error because we are trying to assign the total_percentage variable to the percentage(my_marks) function call statement. And according to the Python syntax, it is illegal.

Solution

To solve this problem, we need to swap the position of the percentage(my_marks) function call and total_percentage variable. So the returned value of percentage() could be assigned to the total_percentage variable.

Output

Final Thoughts!

The SyntaxError: can’t assign to function call error occurs in Python when we try to assign a value to a function call statement. This exception is a result of when we write the variable on the right side and function call on the left side of the assignment operation.

To debug this error, we must make sure that whenever we try to assign a return value of a function call to a variable, the function must be on the right side and the variable on the left side.

If you are still getting this error in your Python program, you can share your code in the comment section. We will try to help you in debugging.

People are also reading:

Источник

  1. Syntax Error in Python
  2. Fix the SyntaxError: can't assign to function call in Python

Fix the SyntaxError: Can't Assign to Function Call in Python

This article will discuss how to fix the SyntaxError: can't assign to function call error in Python.

Syntax Error in Python

The syntax of computer programming is the grammar or proper writing structure that developers must follow efficiently to avoid bugs in code. Like there are naming conventions and defined structures of loops and conditions you need to follow; otherwise, your code will not be executed.

It is mandatory to follow the rules and regulations of programming language to code properly and avoid bugs. Let us understand it through an example.

for x in range(1,6): # this will print 1,2,3,4,5
    print(x, end= " ")

Output:

The above program demonstrates a proper definition of a for loop in Python. If you write a for loop in an undefined manner in Python, it will throw a Syntax Error.

for in x range(1,6): # this will print 1,2,3,4,5
    print(x, end= " ")

Output:

SyntaxError: invalid syntax

See, we have just changed the positions of in and x in the above for loop. The Python compiler did not support this syntax, throwing a Syntax Error.

This is why following the defined syntax is mandatory. Otherwise, the Python compiler will throw a Syntax Error.

Fix the SyntaxError: can't assign to function call in Python

In Python, the can't assign to function call error occurs when you try to assign a variable or a value to the function, which is not allowed or against the syntax of Python. You can assign a function to a variable but not a variable to a function.

Let us understand it through an example.

Output:

SyntaxError: can't assign to literal

The above statement is invalid in Python. You cannot assign a variable to a string, but the opposite is possible.

name = "Delft Stack"
print(name)

Output:

This is the right syntax acceptable in Python, so it is executed without causing any error. Similarly, you cannot assign a variable to a function, but the opposite is possible.

Let’s understand it through an example.

class Greetings():
    def hi(self):
        return "Hey! How are you?"

Delft = Greetings()
Delft.ftn() = x #This statement is invalid
print(x)

Output:

SyntaxError: can't assign to function call

In the above program, the statement Delft.ftn() = x is not supported by the Python compiler because the syntax is incorrect; that’s why it has thrown a Syntax Error. Let’s change the assignment order of this Delft.ftn() = x statement to fix the Syntax Error.

Let’s fix the error can't assign to function call in Python.

class Greetings():
    def hi(self):
        return "Hey! How are you?"

Delft = Greetings()
x = Delft.hi()
print(x)

Output:

As you can see, this program is now executed without causing any error. This statement x = Delft.hi() is now in the proper order; it follows Python’s defined syntax.

Понравилась статья? Поделить с друзьями:
  • Cannot access java lang netbeans как исправить
  • Caniuse lite is outdated как исправить
  • Candy сушильная машина ошибка loc
  • Candy сушильная машина ошибка e14
  • Candy стиральная машина ошибка sp3