int

We've already seen Python integers in action quite a lot. Python integers are signed and have, for all practical purposes, unlimited precision. This means that there is no pre-defined limit to the magnitude of the values they can hold.

Integer literals in Python are typically specified in decimal:

>>> 10
10

They may also be specified in binary with a 0b prefix:

>>> 0b10
2

There may also be a octal, with a 0o prefix:

>>> 0o10
8

If its a hexadecimal we use the 0x prefix:

>>> 0x10
16

We can also construct integers by a call to the int constructor which can convert from other numeric types, such as floats, to integers:

>>> int(3.5)
3

Note that, when using the int constructor, the rounding is always towards zero:

>>> int(-3.5)
-3
>>> int(3.5)
3

We can also convert strings to integers as follows:

>>> int("496")
496

Be aware, though, that Python will throw an exception (much more on those later!) if the string doesn't represent an integer.

You can even supply an optional number base when converting from a string. For example, to convert from base 3 simply pass 3 as the second argument to the constructor:

>>> int("10000", 3)
81

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset