Syntaxerror cannot assign to function call питон

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

Читайте также:  Java create nested exception

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)

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.

Have fun and happy researching!

Share this:

Источник

SyntaxError: «can’t assign to function call»

You are attempting to assign a value to a function call, as the error says. What are you trying to accomplish? If you’re trying set subsequent_amount to the value of the function call, switch the order:

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

You wrote the assignment backward: to assign a value (or an expression) to a variable you must have that variable at the left side of the assignment operator ( = in python )

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

You are assigning to a function call:

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

which is illegal in Python. The question is, what do you want to do? What does invest() do? I suppose it returns a value, namely what you’re trying to use as subsequent_amount , right?

If so, then something like this should work:

amount = invest(amount,top_company(5,year,year+1),year) 

Then you must have a literal like a number or a string (in quotes) on the left-hand side of the assignment.

then I can not put the value neither on the left nor on the right ! that will be an infinite cycle !!

The name (variable) goes on the left, the value on the right. This is the same across practically all programming languages.

You must be having a function call on the left side (something like foo(bar, baz) = 123 . There may only be names, possibly tuples, on the left side. Please show the line that‘s causing the error.

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:

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

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 = .

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.

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 (==).

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

Источник

Syntaxerror cannot assign to function call питон

Last updated: Feb 17, 2023
Reading time · 3 min

banner

# 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.

syntaxerror cannot assign to function call here

Here is an example of how the error occurs.

Copied!
def get_num(): return 100 # ⛔️ SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='? get_num() = 'abc'

cannot assign to function call here

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

# Specify the function call on the right-hand side

To solve the error, make sure to specify the function call on the right-hand side of the assignment.

Copied!
def get_num(): return 100 # ✅ call the function on the right-hand side of the assignment my_num = get_num() print(my_num) # 👉️ 100

call function on right hand side

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

When declaring a variable, specify the variable name on the left-hand side and the value on the right-hand side of the assignment ( = ).

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

The parentheses are used to invoke the function.

If your function takes parameters, make sure to specify them.

Copied!
def greet(first, last): return 'hello ' + first + ' ' + last result = greet('bobby', 'hadz') print(result) # 👉️ hello bobby hadz

# Use double equals when performing an equality comparison

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

Copied!
def get_num(): return 100 # ✅ using double equals when comparing values if 100 == get_num(): # 👇️ this runs print('success') else: print('failure')

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

Copied!
# ✅ assignment (single equals) name = 'bobby' # ✅ equality comparison (double equals) if name == 'bobby': print('success')

# Use square brackets when adding keys to a Dictionary

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

Copied!
my_dict = > # ⛔️ SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='? my_dict('name') = 'Bobby'

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.

Copied!
my_dict = > my_dict['name'] = 'Bobby' print(my_dict['name']) # 👉️ 'Bobby'

Square brackets are used to add key-value pairs to a dictionary and to access keys in a dictionary.

# Use square brackets when updating or accessing elements in a list

You should also use square brackets when updating or accessing elements in a list.

Here is an example of how the error occurs when parentheses are used.

Copied!
my_list = ['bobby', 'hadz', 'com'] # ⛔️ SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='? my_list(0) = 'abc'

To resolve the issue, use square brackets [] instead.

Copied!
my_list = ['bobby', 'hadz', 'com'] my_list[0] = 'abc' print(my_list) # 👉️ ['abc', 'hadz', 'com'] print(my_list[0]) # 👉️ abc

We used square brackets to update the value of the list element at index 0 and then accessed the element using square brackets.

# Valid names for variables and functions in Python

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 _ .

Copied!
def get_num(): return 100 my_num = get_num() print(my_num) # 👉️ 100

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

Variable names in Python are case-sensitive.

Copied!
def get_num(): return 100 def get_num_2(): return 200 my_num = get_num() print(my_num) # 👉️ 100 MY_NUM = get_num_2() print(MY_NUM) # 👉️ 200

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

# Incorrect syntax when looping

You might also get the error when you have syntax errors in list comprehensions or generator expressions.

Copied!
def get_name(): return 'bobby' result = [char for get_name() in char] # ⛔️ SyntaxError: cannot assign to function call print(result)

Notice that the order in the list comprehension is incorrect.

Instead, it should be [char for char in get_name()] .

Copied!
def get_name(): return 'bobby' result = [char for char in get_name()] # ['b', 'o', 'b', 'b', 'y'] print(result)

Make sure the order of operations in your for loops, generator expressions and list comprehensions is correct.

We iterate over the result of calling the function, not over a character or element of the return value of the function.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью