1

I have a problem with my code. The language is python. I am trying to use an if statement to execute some code if a variable has a certain value.

op = 5

if(op = 5):
    print("op is 5!")

Every time I run this program, it gives me a syntax error. I have tried doing this instead;

op = 5

if op = 5:
    print("op is 5!")

But it still gives me the error. I am asking this question because I am doing a calculator project and need this.

4
  • You cannot have an assignment statement inin place of the Boolean condition of an if statement. Commented Aug 23, 2020 at 20:24
  • @Prune not technically true now that there are assignment expressions. i.e. walrus operator :=. Edit: Actually I guess you said statement so you are still correct Commented Aug 23, 2020 at 20:25
  • Make sure to include the actual error message in question, formatted appropriately. In this case the ^ points to the exact part of the expression (unfortunately Python doesn't have a super clear diagnostic message which is certainly could in this case). Commented Aug 23, 2020 at 20:26
  • 1
    Yup -- I was incomplete from trying to stay simple. Commented Aug 23, 2020 at 20:26

3 Answers 3

4

= is the assignment operator. You're looking for the equality check operator, ==:

if op == 5:
    print("op is 5!")
Sign up to request clarification or add additional context in comments.

1 Comment

@therealemg If this answers your question please mark it correct for future readers :)
1

You misspelled the equality check operator.

The equality check operator is ==. You put the assignment operator, which is this: =.

The following code will return a SyntaxError:

foo = input('Enter the value of foo: ')
if foo = '5':
    print('foo is equal to 5!')
else:
    print('foo is not equal to 5!')

But this won't:

foo = input('Enter the value of foo: ')
if foo == '5':
    print('foo is equal to 5!')
else:
    print('foo is not equal to 5!')

You just need to change the operator in the if statement to ==.

Comments

1

For comparison we used double equal sign ==

Not single

if op == 5:
    print("op is 5!")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.