16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 1 ■ INSTANT HACKING: THE BASICS 11<br />

>>> 1.0/2<br />

0.5<br />

>>> 1/2.<br />

0.5<br />

If you’d rather have <strong>Python</strong> do proper division, you could add the following statement <strong>to</strong><br />

the beginning of your program (writing full programs is described later) or simply execute it in<br />

the interactive interpreter:<br />

>>> from __future__ import division<br />

Another alternative, if you’re running <strong>Python</strong> from the command line (e.g., on a Linux<br />

machine), is <strong>to</strong> supply the command-line switch -Qnew. In either case, division will suddenly<br />

make a bit more sense:<br />

>>> 1 / 2<br />

0.5<br />

Of course, the single slash can no longer be used for the kind of integer division shown<br />

earlier; but there is a separate opera<strong>to</strong>r that will do this for you—the double slash:<br />

>>> 1 // 2<br />

0<br />

The double slash consistently performs integer division, even with floats:<br />

>>> 1.0 // 2.0<br />

0.0<br />

There is a more thorough explanation of the __future__ stuff in the section “Back <strong>to</strong> the<br />

__future__,” later in this chapter.<br />

Now you’ve seen the basic arithmetic opera<strong>to</strong>rs (addition, subtraction, multiplication,<br />

and division), but one more opera<strong>to</strong>r is quite useful at times:<br />

>>> 1 % 2<br />

1<br />

This is the remainder (modulus) opera<strong>to</strong>r—x % y gives the remainder of x divided by y.<br />

For example:<br />

>>> 10 / 3<br />

3<br />

>>> 10 % 3<br />

1<br />

>>> 9 / 3<br />

3<br />

>>> 9 % 3<br />

0<br />

>>> 2.75 % 0.5<br />

0.25

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!