Python raises SyntaxError on "=" in if statement [closed]

I'm writing a program that takes user input and compares it to different command strings. When I attempt to run the program, I get a SyntaxError about the line if method = 'addition': and IDLE highlights the = in red.

num1 = input('Enter your first value: ')
num2 = input('Enter your second value: ')
method = input('Which method will you be using? ')

if method = 'addition':
    solveFor = num1 + num2
elif method = 'subtraction':
    solveFor = num1 - num2
else:
    print("Please enter 'addition' or 'subtraction'")

The equality comparison operator in Python is ==. = is a statement for assigning a value to a variable.

Your code has a number of other errors (beginning with the undefined names num1, num2, sitting there doing nothing at the beginning). You should read the Python tutorial to brush up on the basics of Python syntax.


Here are some tips:

  • Python doesn't require you to declare variables like other languages do, as it is dynamically typed, so there is no need to write num1 at the beginning of your script.
  • The single equals sign is used for setting a value (a = 2), while the double equals sign is used to compare values (if a == 2:).
  • You need to place colons after all if, else and elif statements.
  • Indentation is important in Python.

You seem to be lacking basic Python knowledge and should really read through a decent Python tutorial. I've been told that this online book is good: http://learnpythonthehardway.org/book/

For reference, here's a fixed version of your code:

print "Welcome to PyCalcBasic"

num1 = input("Enter your first value")
num2 = input("Enter you second value")
method = raw_input("Which mathematical operator will you be using?")

if method == "addition":
    solveFor = num1 + num2
elif method == "subtraction":
    solveFor = num1 - num2
else:
    print ("Please enter 'addition' or 'subtraction'")