Python SyntaxError: cannot assign to operator - python

The following Python script raises syntax error:
def main(number, number2, equation):
if equation == 1:
number + number2 = answer
SyntaxError: cannot assign to operator is the raised error. Please help.

You must assign (=) operation (number + number2) to variable answer in this direction.
answer = number + number2
Variable name is on right side and value, expression, object, etc. is on the left.

In python you set variables to be equal to the their result instead of the result to be equal to the variable.
So where you have put
number + number2 = answer
You need to do
answer = number + number2
As what you are doing is making the sum of number and number2 equal to answer which is not possible

Related

your program produce no output [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am new to the field. simple program, all I need to do is to find the smallest number.
number1 = input ('')
number2= input('')
number3 = input('')
number1 = input ('')
number2= input('')
number3 = input('')
if (number1<number2) and (number1<number3):
smallest=number1
elif (number2<number1) and (number2 < number3):
smallest=number2
else:
smallest=number3
print(smallest)
This occurs because input() returns a string:
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Because of this, all checks amongst the input values won't be between integers, as you want, but strings, leading to comparisons being based upon lexicographical ordering rather than value. This can be solved by converting the inputs to integers:
number1 = int(input(''))
number2 = int(input(''))
number3 = int(input(''))
if (number1 < number2) and (number1 < number3):
smallest = number1
elif (number2 < number1) and (number2 < number3):
smallest = number2
else:
smallest = number3
print(smallest)
simply use min() and max()
n1,n2,n3 = 1,2,3
print("min:", min(n1,n2,n3) )
print("max:", max(n1,n2,n3))
output:
> min: 1
> max: 3
When you enter "7", "15", and "3", your program compares those three values as strings, which means that it will find the one that is "smallest" alphabetically -- the first character is compared first, which makes "15" come first in the ordering (then "3", then "7").
To fix this, you need to convert the values to ints:
number1 = int(input())
You may be getting blank strings ("") in some cases because you copied and pasted the input lines, which means you're getting prompted six times and only the last three times count.
Overall the fixed version of your code would look like:
number1 = int(input())
number2 = int(input())
number3 = int(input())
if number1 < number2 and number1 < number3:
smallest = number1
elif number2 < number3:
smallest = number2
else:
smallest = number3
print(smallest)
Note that you don't need to pass an empty string to input() (it defaults to an empty string), and you don't need the parentheses around your comparison operations (because < already takes precedence over and).
A shortened version of this code that uses min and a loop would be:
print(min(int(input()) for _ in range(3)))
In this line of code, the expression int(input()) for _ in range(3) generates three inputs (one per number in range(3)), and the min function finds the minimum value from that generator. The nice thing about using a loop like this is that you can easily make it work for any number of inputs without having to write a bunch more if ... < ... checks!
When you use input(''), it takes the number from terminal (at the running time), so your code is OK, just to understand how it works, run your modified code below, some added strings can help you find your problem better.
number1 = input('Please insert the first number ?')
number2 = input('Please insert the second number ?')
number3 = input('Please insert the third number ?')
if (number1 < number2) and (number1 < number3):
smallest = number1
elif (number2 < number1) and (number2 < number3):
smallest = number2
else:
smallest = number3
print("result is : ", smallest)

How to print variables depending on an operator in python?

I am trying to code a simple calculator but I am having a problem. I can't seem to add, subtract, multiply, or divide two variables and print them. I am trying to code so the user can input the numbers along with the operator. Any ideas?
Thanks,
SanguineL
number1 = raw_input ("What is the first number?")
operator = raw_input ("What is the operator?")
number2 = raw_input ("What is the second number?")
elif operator == +
answer = number1 + number2
elif operator == -
answer = number1 - number2
elif operator == *
answer = number1 * number2
elif operator == /
answer = number1 / number2
print answer
You need to distinguish the string you get from raw_input from the function an operator represents.
if operator == "+":
answer = number1 + number2
elif ...
The operator module lets you build a dictionary that abstracts away the lookup process:
import operator
number1 = raw_input ("What is the first number?")
op = raw_input ("What is the operator?")
number2 = raw_input ("What is the second number?")
funcs = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div}
try:
f = funcs[op]
except KeyError:
raise ValueError("Undefined operator %s" % (op,))
answer = f(number1, number2)
So there's a couple issues with your code, the first issue is that raw_input will always assume the input is a string and so your number1, operator, and number2 objects will be strings (and I assume you only want the operator variable to be a string). If you want to convert your numbers to floats, then you need to write something like number1 = float(raw_input ("What is the first number?"))
The second issue is that you need to start an if block with an if statement not an elif statement. elif statements come only after the if statement since it stands for "else if" - i.e. in the form if something else if something.
The third issue is that you didn't put quotes around your operators in your conditional statements. Python will not automatically assume they are strings. Python will assume they are variables which you haven't declared yet. You should have a statement like elif operator == '-' in order to make the comparison valid.
The fourth and last issue (that I see) is that since you are using raw_input it appears you are using python 2. Python 2 has a weird behavior when using the division operator / - namely it floors the division if the inputs to it are ints or longs. That behavior can cause a lot of headaches if you are not aware of it. You should probably include a from __future__ import division line at the beginning of your code so dividing doesn't floor the answer.
Don't know what does raw_input ("What is the first number?") mean (assume that is some kind of form input or sdt_in), but lower part might be (don't forget to convert your inputs like this number1 = int(number1)):
if operator == '+'
answer = number1 + number2
elif operator == '-'
answer = number1 - number2
elif operator == '*'
answer = number1 * number2
elif operator == '/'
answer = number1 / number2
print(answer)

Sum two numbers

When I type the input of the sum of number1 + number2 as "answer" and number1, number2 are two randomized numbers between 1-500, I get my "Wrong, sorry!" statement instead of the "Right!" when the answer is correct.
For example, if the two numbers are 479 + 121, the answer should be 600, right? Well, apparently it's not, my code likes to say. Due to some error logic, I'll guess. (Note this is just an excerpt, obviously. The variables were declared as integers before in the main module and random is imported.)
def getNumbers():
number1 = random.randint(1, 500)
number2 = random.randint(1, 500)
return number1, number2
def getAnswer(number1, number2, answer):
print("What is the answer to the following equation:")
print(number1)
print("+")
print(number2)
answer = input("What is the sum? ")
return answer
def checkAnswer(number1, number2, answer, right):
if answer == number1 + number2:
print("Right!")
else:
print("Wrong, sorry!")
It comes out as:
What is the answer to the following equation?
479
+
121
What is the sum? 600
Wrong, sorry!
0 also comes in as incorrect, so I'm not sure what the value is being set to. Any idea how to fix this code?
input function returns string , you should cast it to int :
answer = int(input("What is the sum? "))
because you didn't cast it to int "600" == 600 is always False and Wrong printed .

How to loop a formula into a list

I am new to coding and my spelling is not the best but I need help with something, I am trying to loop a formula to make a sequence that is stored in a list. Here is my code so far;
for i in range(list):
number1 = number63*number99
number2 = number1*number33
number3 =(number2*number34)+(number64*number35)
total = number1 + number2 + number3
don't worry about the variables they are completely irrelevant as they only make sense to me but i just was to know how i could do this.
Is this what you want to do?
for i in range(list):
number1 = number63*number99
number2 = number1*number33
number3 =(number2*number34)+(number64*number35)
total += [number1] + [number2] + [number3]
This will make total a list which adds the three numbers to it each loop iteration
An alternative is to use extend:
total.extend([number1, number2, number3])
Please note that for both of these methods, you need to initialize total somewhere earlier in your code, e.g.
total = []
Additionally, you are using the range function wrong. If you want to iterate the length of a list, do range(0,len(lst)). Please also note that using the variable name list is ill-advised as it is a built-in function in Python.

Why is my normal 'if' statement not working on python

I am trying make a maths game but the output says wrong when I answer it correctly. (on python 2.7.2)
The code:
import random
number1 = random.randrange(1, 10)
number2 = random.randrange(1, 10)
print "Whats",number1,"+",number2
answer = raw_input('=')
if answer is (number1 + number2):
print "Correct!"
else:
print "Wrong!"
You want to use == instead of is. is is used for checking reference equality. You can look at this for a better explanation. raw_input reads values in as strings by default, so you need to convert it to an integer to be able to check if the input is equal to the answer. Or more simply, use input instead.
import random
number1 = random.randrange(1, 10)
number2 = random.randrange(1, 10)
print "Whats",number1,"+",number2
answer = input('=')
if answer == (number1 + number2):
print "Correct!"
else:
print "Wrong!"

Categories

Resources