官术网_书友最值得收藏!

Operators

Operators take one or two values (or variables), perform an operation, and return a value. Let's check out a simple example of using an operator, just to clarify the terminology.

>>> 1 + 2

3

In this code:

  • + is the operator
  • The operation is addition
  • The input values are 1 and 2 (the input values are also called operands)
  • The result value is 3

Instead of using the values 1 and 2 directly in the operation, you can use variables. You can also use a variable to store the result of the operation, as the following example demonstrates:

>>> var a = 1; 
>>> var b = 2; 
>>> a + 1 

2

>>> b + 2 

4

>>> a + b 

3

>>> var c = a + b; 
>>> c 

3

The following table lists the basic arithmetic operators:

When you type var a = 1; this is also an operation; it's the simple assignment operation and = is the simple assignment operator.

There is also a family of operators that are a combination of an assignment and an arithmetic operator. These are called compound operators. They can make your code more compact. Let's see some of them with examples.

>>> var a = 5;
>>> a += 3;

8

In this example a += 3; is just a shorter way of doing a = a + 3;

>>> a -= 3;

5

Here a -= 3; is the same as a = a - 3;

Similarly:

>>> a *= 2;

10

>>> a /= 5;

2

>>> a %= 2;

0

In addition to the arithmetic and assignment operators discussed above, there are other types of operators, as you'll see later in this and the following chapters.

主站蜘蛛池模板: 平阳县| 洪湖市| 云霄县| 大余县| 漾濞| 株洲市| 龙井市| 清镇市| 伊金霍洛旗| 信宜市| 赫章县| 元朗区| 新竹县| 阜新市| 上饶县| 荆门市| 田林县| 长岭县| 陈巴尔虎旗| 德保县| 虞城县| 保靖县| 贵港市| 屯昌县| 云南省| 江都市| 加查县| 德庆县| 太保市| 石门县| 昌江| 镇远县| 六枝特区| 呼伦贝尔市| 治多县| 隆回县| 独山县| 丹凤县| 固阳县| 赣州市| 临西县|