Book Image

The Python Apprentice

By : Robert Smallshire, Austin Bingham
Book Image

The Python Apprentice

By: Robert Smallshire, Austin Bingham

Overview of this book

Experienced programmers want to know how to enhance their craft and we want to help them start as apprentices with Python. We know that before mastering Python you need to learn the culture and the tools to become a productive member of any Python project. Our goal with this book is to give you a practical and thorough introduction to Python programming, providing you with the insight and technical craftsmanship you need to be a productive member of any Python project. Python is a big language, and it’s not our intention with this book to cover everything there is to know. We just want to make sure that you, as the developer, know the tools, basic idioms and of course the ins and outs of the language, the standard library and other modules to be able to jump into most projects.
Table of Contents (21 chapters)
Title Page
Credits
About the Authors
www.PacktPub.com
Customer Feedback
Preface
12
Afterword – Just the Beginning

Scalar data types: integers, floats, None and bool


Python comes with a number of built-in datatypes. These include primitive scalar types like integers as well as collection types like dictionaries. These built-in types are powerful enough to be used alone for many programming needs, and they can be used as building blocks for creating more complex data types.

The basic built-in scalar types we'll look at are:

  • int — signed, unlimited precision integers
  • float — IEEE 754 floating-point numbers
  • None — a special, singular null value
  • booltrue/false boolean values

For now we'll just be looking at their basic details, showing their literal forms and how to create them.

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

 

float

Floating point numbers are supported in Python by the float type. Python floats are implemented as IEEE-754 double-precision floating point numbers with 53 bits of binary precision. This is equivalent to between 15 and 16 significant digits in decimal.

Any literal number containing a decimal point is interpreted by Python as a float:

3.125

Scientific notation can be used, so for large numbers — such as {ParseError: KaTeX\ parse error: Expected 'EOF', got '}' at position 1: }̲3\times10^8{/}, the approximate speed of light in metres per second — we can write:

>>> 3e8
300000000.0

and for small numbers like Planck's constant {ParseError: KaTeX parse error:\ Expected 'EOF', got '}' at position 1: }̲1.616\times10^} we can enter:

>>> 1.616e-35
1.616e-35

Notice how Python automatically switches the display representation to the most readable form.

As for integers, we can convert to floats from other numeric or string types using the float constructor. For example, the constructor can accept an int:

>>> float(7)
7.0

The float constructor can also accept a string as follows:

>>> float("1.618")
1.618

 

Special floating point values

By passing certain strings to the float constructor, we can create the special floating point value NaN (short for Not aNumber) and also positive and negative infinity:

>>> float("nan")
nan
>>> float("inf")
inf
>>> float("-inf")
-inf

Promotion to float

The result of any calculation involving int and float is promoted to a float:

>>> 3.0 + 1
4.0

You can read more about Python's number types in the Python documentation.

None

Python has a special null value called None, spelled with a capital N. None is frequently used to represent the absence of a value. The Python REPL never prints None results, so typing None into the REPL has no effect:

>>> None
>>>

The null value None can be bound to variable names just like any other object:

>>> a = None

and we can test whether an object is None by using Python's is operator:

>>> a is None
True

We can see here that the response is True, which brings us conveniently on to the bool type.

bool

The bool type represents logical states and plays an important role in several of Python's control flow structures, as we'll see shortly. As you would expect there are two bool values, True and False, both spelled with initial capitals:

>>> True
True
>>> False
False

There is also a bool constructor which can be used to convert from other types to bool. Let's look at how it works. For ints, zero is considered falsey and all other values truthy:

>>> bool(0)
False
>>> bool(42)
True
>>> bool(-1)
True

We see the same behavior with floats where only zero is considered falsey:

>>> bool(0.0)
False
>>> bool(0.207)
True
>>> bool(-1.117)
True
>>> bool(float("NaN"))
True

When converting from collections, such as strings or lists, only empty collections are treated as falsey. When converting from lists — which we'll look at shortly — we see that only the empty list (shown here in it's literal form of []) evaluates to False:

>>> bool([])
False
>>> bool([1, 5, 9])
True

Similarly, with strings only the empty string, "", evaluates to False when passed to bool:

>>> bool("")
False
>>> bool("Spam")
True

In particular, you cannot use the bool constructor to convert from string representations of True and False:

>>> bool("False")
True

Since the string False is not empty, it will evaluate to True. These conversions to bool are important because they are widely used in Pythonif-statements and while-loops which accept bool values in their condition.