04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

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 Python do proper division, you could add the following statement to<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 Python from the command line (e.g., on a Linux<br />

machine), is to 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 operator 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 to the<br />

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

Now you’ve seen the basic arithmetic operators (addition, subtraction, multiplication,<br />

and division), but one more operator is quite useful at times:<br />

>>> 1 % 2<br />

1<br />

This is the remainder (modulus) operator—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!