# StartProgramming-1-3 比较Compare

You know how to give objects names, but you will also need to know how to tell if one thing is the same as another, or if it is equal, greater or less than another.

To do this, we use comparison operators.

The most common comparison is equality:

`this == 5`

Note the difference between these two lines:

```   1 this = 4
2 this == 5
```

The first line is an assignment. It uses 1 equals sign (=) and it says "Set the variable this equal to 4." This is naming, like we talked about on the last page.

The second line is a comparison. It uses 2 equals signs (==) and it asks a question: "Is the variable this equal to 5?"

Try these lines in the Python interpreter:

 this = 5 assignment赋值 that = 10 assignment赋值 this == that True真or或者False假? this = that assignment赋值 this == that True真or或者False假?

If this is equal to that then Python will return True (1) and if not, then Python returns False (0).

Some other common comparisons:

 3 < 5 is less than小于 True真 9 > 8 is greater than大于 True真 1 != 0 is not equal to不等于 True真 5 is not None is not 不是（id不等于） True真

The last example introduces two new ideas:

First, None is a special object you can use to mean "no value" or "unknown" or "not set" or "null". It took me a long time to really understand when to use None and the best way is just to read other people's code and see how they use it.

Second, the comparison is a bit different, as it does not compare the values of the two objects, but their actual identities.

In Python, every object has a unique id number which you can get by using the builtin id() function.

So, what the last line actually means is:

`id(5) != id(None)`

We use is or is not because it is quicker and easier to read.

This comparison of identity also implies that two objects can be equal even if they are not identical.

 x1 = 3.2 3.2 is not an integer,it is a floating point number.3.2不是一个整数，它是一个浮点数。 x2 = 1.8 1.8 is also a float.1.8还是一个浮点数。 x_total = x1 + x2 Adding floats always returns a float.两个浮点数相加仍然返回一个浮点数。 x_total == 5 equals等于 True真 x_total is 5 isid等于 False假

• 译者注：id就好像出厂的序列号一样。比方说刚刚生产的小轿车，它们的颜色、体积、重量、发动机等等完全都是相同的，但是出厂的时候，汽车生产商要为小轿车贴上一个出厂序列号，标明是哪年哪月哪日生产的第几辆小轿车，因为次序的不同，所以这个id号也是不同的。

StartProgramming-1-3 (last edited 2009-12-25 07:14:13 by localhost)