Starting Out Top Combining Literals Contents

Literals

Python works by figuring out the meaning or value of some code. This is true for the tiniest pieces of code to the largest programs. The process of finding out the meaning of code is known as evaluation.

The things whose values are the things themselves are known as literals. The literals of Python can be categorized by the following types: integers, real numbers, strings, Booleans, and arrays.

Python (or more correctly, the Python interpreter) responds to literals by echoing back the literal itself. Here are examples of each of the types:

    >>> 3
    3
     
    >>> -4.9
    -4.9
     
    >>> "hello"
    'hello'
     
    >>> True
    True

    >>>[3, -4.9, "hello"]
    [3, -4.9, 'hello']

Let's examine the five types in more detail.

Integers

Integers are numbers without any fractional parts. Examples of integers are:

    >>> 3
    3
    
    >>> -5
    -5
    
    >>> 0
    0

Integers must begin with a digit or a minus sign. The initial minus sign must immediately be followed by a digit.

Real Numbers

Reals are numbers that do have a fractional part (even if that fractional part is zero!). Examples of real numbers are:

    >>> 3.2
    3.2
    
    >>> 4.0
    4.00000000000
       
    >>> 5.
    5.00000000000
       
    >>> 0.3
    0.30000000000
       
    >>> .3
    0.30000000000
    
    >>> 3.0e-4
    0.0003
    
    >>> 3e4
    30000.0
    
    >>> .000000987654321
    9.87654321e-07

Real numbers must start with a digit or a minus sign or a decimal point. An initial minus sign must immediately be followed by a digit or a decimal point. An initial decimal point must immediately be followed by a digit. Python accepts real numbers in scientific notation. For example, 3.0 * 10-11 would be entered as 3.0e-11. The "e" stands for exponent and the 10 is understood, so e-11 means multiply whatever precedes the e by 10-11.

The Python interpreter can hold huge numbers, limited by only the amount of memory available to the interpreter, but holds only 15 digits after the decimal point:

    >>> 1.2345678987654329
    1.234567898765433

Note that Python rounds up or rounds down, as necessary.

Numbers greater than 106 and less than 10-6 are displayed in scientific notation.

Strings

Strings are sequences of characters delineated by double quotation marks:

    >>> "hello, world!"
    'hello, world!'
    
    >>> "x\nx"
    'x\nx'
    
    >>> "\"z\""
    '"z"' 
    
    >>> ""
    ''

Python accepts both double quotes and single quotes to delineate strings. In this text, we will use the convention that double quotes are used for strings of multiple characters and single quotes for strings consisting of a single character.

Characters in a string can be escaped (or quoted) with the backslash character, which changes the meaning of some characters. For example, the character n, in a string refers to the letter n while the character sequence \n refers to the newline character. A backslash also changes the meaning of the letter t, converting it into a tab character. You can also quote single and double quotes with backslashes. When other characters are escaped, it is assumed the backslash is a character of the string and it is escaped (with a backslash) in the result:

    >>> "\z"
    '\\z'

Note that Python, when asked the value of strings that contain newline and tab characters, displays them as escaped characters. When newline and tab characters in a string are printed in a program, however, they are displayed as actual newline and tab characters, respectively. As already noted, double and single quotes can be embedded in a string by quoting them with backslashes. A string with no characters between the double quotes is known as an empty string.

Unlike some languages, there is no character type in Python. A single character a, for example, is entered as the string "a" or 'a'.

True, False, and None

There are two special literals, True and False. These literals are known as the Boolean values and are used to guide the flow of a program. The term Boolean is derived from the last name of George Boole, who, in his 1854 paper An Investigation of the Laws of Thought, on which are founded the Mathematical Theories of Logic and Probabilities, laid one of the cornerstones of the modern digital computer. The so-called Boolean logic or Boolean algebra is concerned with the rules of combining truth values (i.e., true or false). As we will see, knowledge of such rules will be important for making Python programs behave properly. In particular, Boolean expressions will be used to control conditionals and loops.

Another special literal is None. This literal is used to indicate the end of lists; it also is used to indicates something that has not yet been created. More on None when we cover lists and objects.

Collections of literals

If you read any other text on Python, the basic way of grouping literals together (rather like throwing a bunch of groceries in a shopping bag) is called a list. However, in all Python implementations I have tested, these lists are not lists at all, at least in the Computer Science sense, but are actually arrays, specifically dynamic arrays. Because this text is a Computer Science text, rather than a programming text, we will use the term array rather than list and introduce true lists in a later chapter1.

Arrays are just collections of values. One creates an array by enclosing a comma-separated listing of values in square brackets. The simplest array is empty:

    >>>[]
    []

Arrays can contain any values:

    >>>[2, "help", len]
    [2, 'help', <built-in function len>]

The first value is an integer, the second a string, and the third is something known as a function. We will learn more about functions later, but the len function is used to tell us how many items are in an array:

    >>> len([2, "help", len])
    3

As expected, the len function tells us that the array [2, "help", len] has three items in it.

Arrays can even contain arrays!

    >>>[0, [3, 2, 1], 4]
    [0, [3, 2, 1], 4]

An array is something known as a data structure; data structures are extremely important in writing sophisticated programs.

Indexing into Arrays

You can pull out an item from an array by using bracket notation. With bracket notation, you specify exactly which element (or elements) you wish to extract from the array. This specification is called an index. The first element of the array has index 0, the second index 1, and so on. This concept of having the first element having an index of zero is known as zero-based counting, a common concept in Computer Science. Here is some code that extracts the first element of an array. Note that the first interaction creates a variable named items that points to an array of three elements.

    >>> items = ['a', True, 7]

    >>> items
    ['a', True, 7]

    >>> items[0]
    'a'

    >>> items[1]
    True

    >>> items[2]
    7

    >>> items
    ['a', True, 7]

Note that extracting an item from an array leaves the array unchanged. What happens if our index is too large?

    >>> items[3]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      IndexError: list index out of range

Not surprisingly, we get an error. Note that error message refers to a "list" as opposed to an array. Do not be confused.

There is a special notation for extracting more than one element of an array. This notation is known as a slice. Here is a slice that extracts all but the first element of an array:

    >>> items[1:]
    [True, 7]

This particular slice (you can slice an array many different ways) says, start extracting at the second item (which has index one) and go to the end. This operation is so common, it has a special name, taking the tail of an array.

Here is a slice that says, start extracting at the first element (which has index 0) and go up to, but do not include, the element with index 2:

    >>> items[0:2]
    ['a', True]

We will see more of slicing when we study recursion in a later chapter.

lusth@cs.ua.edu


Starting Out Top Combining Literals Contents