Python uses = for assignment and == for an equality test. They are different operations even though both include an equals sign.
Understanding the Concept
Assignment binds a name to a value: score = 10. Equality comparison asks whether two values are equal and produces True or False: score == 10. An equality expression can appear in a condition or be assigned to another name. Writing if score = 10: is not valid Python condition syntax; use ==. For None specifically, idiomatic code checks identity using is None, a concept covered later.
When and Why You Would Use This
Use a simple test to decide whether a supplied score matches a target. The program does not change the score when performing the comparison.
Practical Example
target_score = 10
current_score = 8
is_target_reached = current_score == target_score
print("Matched:", is_target_reached)
Understanding the Example
The output is Matched: False. The comparison checks values and returns a Boolean. The earlier assignments established the two values that are being compared.
Example Output
Matched: False
Try It Yourself
Change current_score to 10 and predict the Boolean output. Then try an invalid assignment inside an if statement and read the syntax error.
Common Beginner Mistakes
- Using = inside an if condition when == was intended.
- Assuming == assigns a new value to a variable.
- Reading an assignment as a statement that two expressions are mathematically equal.
Key Takeaways
=assigns a value to a name.==compares two values and returns a Boolean.- A comparison leaves the original variables unchanged.