-1

Why is code like

if a = "hello":
    pass

invalid in Python? The a = "Hello" is just a expression whose value is the Rvalue. It's valid in most languages like C or php. Some opinions?

1
  • 1
    If you tell your C compiler to emit warnings, it'd warn you while making an assignment in a condition. Commented Mar 24, 2014 at 3:30

2 Answers 2

2

While Python will allow you to chain assignment,

a = b = "hello"

it will not allow you to use it in an expression,

"hi" > b = "hello"    # => Syntax error

This is for safety, to keep you from accidentally using = when you meant ==

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot. It really confused me when the a = b = "hello" is valid while the if a = "hello is invalid. But I don't think it is necessary for experienced developers.
1

This is intentionally made illegal in python as allowing it is a huge source of error and making it illegal is a minor inconvenience.

See the Design and History FAQ

My experience in python is that this is basically right. I rarely miss not being able to do this.

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.