Syntaxerror cannot assign to operator ошибка

def RandomString (length,distribution):
    string = ""
    for t in distribution:
        ((t[1])/length) * t[1] += string
    return shuffle (string)

This returns a syntax error as described in the title. In this example, distribution is a list of tuples, with each tuple containing a letter, and its distribution, with all the distributions from the list adding up to 100, for example:

[("a",50),("b",20),("c",30)] 

And length is the length of the string that you want.

wjandrea's user avatar

wjandrea

28.5k9 gold badges62 silver badges82 bronze badges

asked Jan 21, 2012 at 21:25

TheFoxx's user avatar

Make sure the variable does not have a hyphen (-).

Hyphens are not allowed in variable names in Python and are used as subtraction operators.

Example:

my-variable = 5   # would result in 'SyntaxError: can't assign to operator'

answered Nov 6, 2019 at 13:59

Anupam's user avatar

AnupamAnupam

15k19 gold badges67 silver badges94 bronze badges

0

Python is upset because you are attempting to assign a value to something that can’t be assigned a value.

((t[1])/length) * t[1] += string

When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn’t a «container».

Based on what you’ve written, you’re just misunderstanding how this operator works. Just switch your operands, like so.

string += str(((t[1])/length) * t[1])

Note that I’ve wrapped the assigned value in str in order to convert it into a str so that it is compatible with the string variable it is being assigned to. (Numbers and strings can’t be added together.)

answered Jan 21, 2012 at 21:31

cheeken's user avatar

cheekencheeken

33.7k4 gold badges35 silver badges42 bronze badges

2

Instead of ((t[1])/length) * t[1] += string, you should use string += ((t[1])/length) * t[1]. (The other syntax issue — int is not iterable — will be your exercise to figure out.)

answered Jan 21, 2012 at 21:31

Makoto's user avatar

MakotoMakoto

104k27 gold badges192 silver badges230 bronze badges

2

Well, as the error says, you have an expression (((t[1])/length) * t[1]) on the left side of the assignment, rather than a variable name. You have that expression, and then you tell Python to add string to it (which is always "") and assign it to… where? ((t[1])/length) * t[1] isn’t a variable name, so you can’t store the result into it.

Did you mean string += ((t[1])/length) * t[1]? That would make more sense. Of course, you’re still trying to add a number to a string, or multiply by a string… one of those t[1]s should probably be a t[0].

answered Jan 21, 2012 at 21:32

kindall's user avatar

kindallkindall

179k35 gold badges279 silver badges310 bronze badges

1

What do you think this is supposed to be: ((t[1])/length) * t[1] += string

Python can’t parse this, it’s a syntax error.

answered Jan 21, 2012 at 21:31

Marcin's user avatar

MarcinMarcin

48.6k18 gold badges128 silver badges201 bronze badges

2

in python only work

a=4
b=3

i=a+b

which i is new operator

Liam's user avatar

Liam

27.8k28 gold badges128 silver badges190 bronze badges

answered Aug 12, 2016 at 8:01

Chang Federico's user avatar

Put simply, All Star is in the business of connecting students and schools.
We help students find schools that are great matches for their educational
needs, personal preferences and lifestyles, and schools pay us for our work.

Here’s a quick Q & A of information we think you should know if you choose
to use our websites. The main takeaways: Using our services is free, but
starting and completing a degree, certificate or diploma program takes
commitment and effort and should be considered carefully.

1. How do you provide your services for free?

Schools pay to advertise on our sites. This allows us to offer our service
to prospective students like you for free.

Schools place a very high priority on enrolling students who go on to
graduate. By using All Star’s focused, information-rich services, schools
can be more confident that the prospective students we introduce them to are
truly committed to their education and to succeeding once they’re enrolled
in school.

2. How do you differ from your competitors?

There are other companies out there that do what we do. But there is no one
that does it with more integrity or respect for our users and their choices.
We put you, the student, in control. You get to choose the schools you’re
interested in, and you get to choose what programs you’d like to learn more
about. We will never submit your contact information to a school without
your consent.

3. Do you really work with ALL schools?

No. Our listings are not exhaustive, we do not list all schools, but they do
include a rich selection of options. We believe this wide variety of options
from hundreds of schools meets the needs of most prospective students who
visit our sites. We partner with smaller schools that specialize in one
particular career field, such as Pima Medical Institute, as well as
world-class, multi-discipline institutions like the University of Southern
California.

4. Is getting a degree really going to open up doors for me?

We really want you to succeed in the program you choose. So does your
school. But we feel compelled to be very frank and upfront: You must work
hard and stay committed to graduate. And assuming you do graduate, there is
no guarantee you will find a job in your chosen field, or any job for that
matter.

Obtaining an education has many personal benefits and can also improve your
financial prospects. However, it’s important to keep in mind that obtaining
an education does not guarantee financial success or even a job. Job markets
vary greatly by region, state, and even locally, and are affected by trends
in the national economy and even international events. Other factors
affecting your job-hunting success may include your job history and
experience, and your level of education, degree, or certificate type. Your
area of specialization plays a role, too.

5. If I do find a job, what can I expect in terms of salary?

The government publishes a great deal of information related to hundreds of
jobs on the Bureau of Labor Statistics (BLS) website. We use this as a
resource for many of the articles on the All Star websites. As comprehensive
as the BLS information is, it is neither complete nor entirely accurate. The
BLS salary information we publish is a national average. Actual salaries for
a particular job or skill may be different where you live. For example, if
you live in a large city or where the job market for particular skills is
especially competitive, such as Silicon Valley in California, you’re likely
to receive a higher wage or salary for the same job than you would in a
rural or economically depressed market. Other factors that can affect salary
rates include the size of the employer, union contracts and governmental
regulations to name a few.

6. Where are you located? How can I contact you?

All Star Directories is located at P.O. Box 1677 Renton, WA 98057. You can
reach us at (206) 436-7500 or at customerservice@allstardirectories.com.

def RandomString (length,distribution):
    string = ""
    for t in distribution:
        ((t[1])/length) * t[1] += string
    return shuffle (string)

This returns a syntax error as described in the title. In this example, distribution is a list of tuples, with each tuple containing a letter, and its distribution, with all the distributions from the list adding up to 100, for example:

[("a",50),("b",20),("c",30)] 

And length is the length of the string that you want.

wjandrea's user avatar

wjandrea

28.5k9 gold badges62 silver badges82 bronze badges

asked Jan 21, 2012 at 21:25

TheFoxx's user avatar

Make sure the variable does not have a hyphen (-).

Hyphens are not allowed in variable names in Python and are used as subtraction operators.

Example:

my-variable = 5   # would result in 'SyntaxError: can't assign to operator'

answered Nov 6, 2019 at 13:59

Anupam's user avatar

AnupamAnupam

15k19 gold badges67 silver badges94 bronze badges

0

Python is upset because you are attempting to assign a value to something that can’t be assigned a value.

((t[1])/length) * t[1] += string

When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. In your case, there is no variable or element on the left, but instead an interpreted value: you are trying to assign a value to something that isn’t a «container».

Based on what you’ve written, you’re just misunderstanding how this operator works. Just switch your operands, like so.

string += str(((t[1])/length) * t[1])

Note that I’ve wrapped the assigned value in str in order to convert it into a str so that it is compatible with the string variable it is being assigned to. (Numbers and strings can’t be added together.)

answered Jan 21, 2012 at 21:31

cheeken's user avatar

cheekencheeken

33.7k4 gold badges35 silver badges42 bronze badges

2

Instead of ((t[1])/length) * t[1] += string, you should use string += ((t[1])/length) * t[1]. (The other syntax issue — int is not iterable — will be your exercise to figure out.)

answered Jan 21, 2012 at 21:31

Makoto's user avatar

MakotoMakoto

104k27 gold badges192 silver badges230 bronze badges

2

Well, as the error says, you have an expression (((t[1])/length) * t[1]) on the left side of the assignment, rather than a variable name. You have that expression, and then you tell Python to add string to it (which is always "") and assign it to… where? ((t[1])/length) * t[1] isn’t a variable name, so you can’t store the result into it.

Did you mean string += ((t[1])/length) * t[1]? That would make more sense. Of course, you’re still trying to add a number to a string, or multiply by a string… one of those t[1]s should probably be a t[0].

answered Jan 21, 2012 at 21:32

kindall's user avatar

kindallkindall

179k35 gold badges279 silver badges310 bronze badges

1

What do you think this is supposed to be: ((t[1])/length) * t[1] += string

Python can’t parse this, it’s a syntax error.

answered Jan 21, 2012 at 21:31

Marcin's user avatar

MarcinMarcin

48.6k18 gold badges128 silver badges201 bronze badges

2

in python only work

a=4
b=3

i=a+b

which i is new operator

Liam's user avatar

Liam

27.8k28 gold badges128 silver badges190 bronze badges

answered Aug 12, 2016 at 8:01

Chang Federico's user avatar

We can assign the result of a mathematical calculation to a variable, but we can not assign a value to a mathematical expression. While assigning a value to a variable in

Python

, we write the variable name on the left side of the assignment operator «=» and the mathematical computational expression on the right side. But if we try to switch it around, we will encounter the error

SyntaxError: cannot assign to operator

.

This Python guide will discuss the above error and how to solve it. Also, we shall go through an example demonstrating this error, so you can learn how to solve it yourself.

So let’s get started.

According to the syntax defined by Python, when we want to assign a computational mathematical value to a variable, we need to write the variable on the left side and the mathematical computation on the right side of the assignment operator «=». In simple terms, You must write a mathematical expression on the right side and a variable on the left.


Example

x = 20 + 30
print(a)     #50

The above example is the correct syntax to assign a mathematical computational value to a variable x. When the Python interpreter reads the above code, it assigns

20+30

, i.e., 50 to the variable

x

.

But if we switch the position of the mathematical computation and variable, we encounter the

SyntaxError: cannot assign to operator

Error.


Example

20 + 30 = a    # SyntaxError: cannot assign to operator print(a)

The error statement

SyntaxError: cannot assign to operator

has two parts.

  1. SyntaxError (Exception type)
  2. cannot assign to the operator (Error Message)


1. SyntaxError

SyntaxError is a standard Python exception. It occurs when we violate the syntax defined for a Python statement.


2. cannot assign to operator

«cannot assign to operator» is an error message. The Python interpreter raises this error message with the SyntaxErorr exception when we try to perform the arithmetic operation on the left side of the assignment operator. Python cannot assign the value on the right side to the mathematical computation on the left side.


Common Example Scenario

Now, you know the reason why this error occurs. Let us now understand this through a simple example.


Example

Let’s say we have a list

prices

that contains the original prices of the different products. We need to write a program that discounts 10 rupees from every product price and adds a 2 rupee profit to every price.

discount = 10
profit = 2

prices = [7382, 3623, 9000,3253,9263,9836]


for i in range(len(prices)):
    # discount 10 and profit 2
    prices[i] + (profit - discount) = prices[i]

print(prices)


Output

  File "main.py", line 9
    prices[i] + (profit - discount) = prices[i]
    ^
SyntaxError: cannot assign to operator


Break the code

In the above example, we get the error

SyntaxError: cannot assign to operator

because the variable to which we want to assign the value »

prices[i]

» is on the right side of the assignment operator, and the value that we want to assign

prices[i] + (profit - discount)

is on the left side.


Solution

When we want to assign a mathematical or arithmetic result to a variable in Python, we should always write the variable on the left side of the assignment operator and the mathematical computational value on the right side. To solve the above example error, we need to ensure that the

prices[i]

must be on the left side of the assignment operator.

discount = 10
profit = 2

prices = [7382, 3623, 9000,3253,9263,9836]


for i in range(len(prices)):
    # discount 10 and profit 2
    prices[i] = prices[i] + (profit - discount)
print(prices)


Output

[7374, 3615, 8992, 3245, 9255, 9828]


Conclusion

When we try to assign a value to a mathematical computational statement, the » SyntaxError: cannot assign to operator» error is raised in a Python program. This means if you write the mathematical computational expression on the assignment operator’s left side, you will encounter this error. To debug or fix this error, you need to ensure that the variable or variables you write on the left side of the assignment operator do not have an arithmetic operator between them.

If you still get this error in your Python program, you can share your code and query in the comment section. We will try to help you with debugging.

Happy Coding!


People are also reading:

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

  • How to check the size of a file using Python?

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

  • What is a constructor in Python?

  • Python typeerror: ‘int’ object is not subscriptable Solution

  • Difference Between Del, Remove and Pop on Python Lists

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

  • How to Build a Port Vulnerability Scanner in Python?

  • Python TypeError: object of type ‘int’ has no len() Solution

  • How to print colored Python output on the terminal?

Ad

At Career Karma, our mission is to empower users to make confident decisions by providing a trustworthy and free directory of bootcamps and career resources. We believe in transparency and want to ensure that our users are aware of how we generate revenue to support our platform.

Career Karma recieves compensation from our bootcamp partners who are thoroughly vetted before being featured on our website. This commission is reinvested into growing the community to provide coaching at zero cost to their members.

It is important to note that our partnership agreements have no influence on our reviews, recommendations, or the rankings of the programs and services we feature. We remain committed to delivering objective and unbiased information to our users.

In our bootcamp directory, reviews are purely user-generated, based on the experiences and feedback shared by individuals who have attended the bootcamps. We believe that user-generated reviews offer valuable insights and diverse perspectives, helping our users make informed decisions about their educational and career journeys.

Find the right bootcamp for you

ck-logo

X

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.

Понравилась статья? Поделить с друзьями:
  • System antipollution defaillant на ситроен с4 ошибка
  • Synsopos exe failed error неопознанная ошибка
  • System aggregateexception произошла одна или несколько ошибок
  • System abs defaillant пежо 307 ошибка
  • Synology проверка сетевой среды ошибка