Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Having a hard time differentiating differences between '=' and '==' in Python. Can somebody please help me understand?

When writing code, I'm having a hard time understanding when = is appropriate vs. ==. I have watched the videos several times, but I'm still not fully understanding when one is appropriate over the other. Can somebody please help me clear this up so I don't make the mistake of using = when I should be using ==?

2 Answers

Hi Sean,

= is called the assignment operator. And it is used to put a value in a variable. For example

a = 5

We're putting 5 in the a variable.

Because = is used for this purpose, we need a different operator to represent what we commonly think of as 'equals'. This is where == is used. For example:

a = 5   # put 5 in 'a'
b = 3   # put 3 in 'b'
a == b   # check if a is equal to b

Any time that if you were in a school maths class and you would use '=' is when in Python you would use ==.

Feel free to share any examples of code where the use seems ambiguous, and I'll see if I can explain why it is the way it is in that case.

Hope that's clear

Alex

Thank you so much! This completely clears up my confusion I've been having about this! I really appreciate the help!

a = 5 is simply for assigning when we say a = 5 we mean a is a box with value 5 or if we say a = True then the box has value TRUE if we say a = "Hello World" then the box has strings "Hello World"

But on the other hand

if lets say there are two boxes a and b a = 5 b = 5 and we say a == b then we are comparing the values of two boxes : which will return true as 5 == 5