Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Gauld A.Learning to program (Python)_1.pdf
Скачиваний:
22
Добавлен:
23.08.2013
Размер:
1.34 Mб
Скачать

Note: in both Tcl and BASIC only double quotes can be used for strings.

Integers

Integers are whole numbers from a large negative value through to a large positive value. That’s an important point to remember. Normally we don’t think of numbers being restricted in size but on a computer there are upper and lower limits. The size of this upper limit is known as MAXINT and depends on the number of bits used on your computer to represent a number. On most current computers it's 32 bits so MAXINT is around 2 billion.

Numbers with positive and negative values are known as signed integers. You can also get unsigned integers which are restricted to positive numbers, including zero. This means there is a bigger maximum number available of around 2 * MAXINT or 4 billion on a 32 bit computer since we can use the space previously used for representing negative numbers to represent more positive numbers.

Because integers are restricted in size to MAXINT adding two integers together where the total is greater than MAXINT causes the total to be wrong. On some systems/languages the wrong value is just returned as is (usually with some kind of secret flag raised that you can test if you think it might have ben set). Normally an error condition is raised and either your program can handle the error or the program will exit. Python adopts this latter approach while Tcl adopts the former. BASIC throws an error but provides no way to catch it (at least I don't know how!)

Arithmetic Operators

We've already seen most of the arithmetic operators that you need in the 'Simple Sequences' section, however to recap:

 

 

Arithmetic and Bitwise Operators

 

 

 

 

Operator

 

Description

 

Example

 

 

 

 

 

 

 

 

M + N

 

Addition of M and N

 

 

 

 

M - N

 

Subtraction of N from M

 

 

 

 

M * N

 

Multiplication of M and N

 

 

 

 

M / N

 

Division, either integer or floating point result depending on the types

 

 

of M and N. If either M or N are real numbers(see below) the result

 

 

 

will be real.

 

 

 

 

M % N

 

Modulo: find the remainder of M divided by N

 

 

 

 

M**N

 

Exponentiation: M to the power N

 

 

 

 

 

We haven’t seen the last one before so let’s look at an example of creating some integer variables and using the exponentiation operator:

>>>i1 = 2 # create an integer and assign it to i1

>>>i2 = 4

>>>i3 = 2**4 # assign the result of 2 to the power 4 to i3

>>>print i3

16

23