Chapter 2. Statements and Expressions

CONTENTS
  •  Comments and Document Strings
  •  Statements
  •  Expressions
  •  Variables
  •  Data Types
  •  Python Collection Types
  •  Advanced Topic: Determining Types at Runtime
  •  Literals
  •  Summary

Terms in This Chapter

  • Assignment

  • Case sensitivity

  • Class

  • Collection type

  • Comment

  • Declaration

  • Definition

  • Document string

  • Escape sequence

  • Expression

  • File path

  • Function

  • Immutability

  • Initialization

  • Instance

  • Key

  • Key/value pair

  • Literal

  • Method

  • Module

  • Object

  • Operator

  • Runtime

  • Sequence

  • Source code

  • Statement execution

  • Tuple

  • Type

  • Value

  • Variable

  • Whitespace

In this chapter, we continue our tour of Python with perhaps the most basic feature: statements. We'll also look at data types, comments, variables, and literals.

Novices, you should know the drill by now: You learn to program by programming, so try to follow along with the interactive sessions in this chapter. If you get stuck on something, just enter in a few of the examples in Jython and skip the rest. Most of the ideas here will be used through the rest of the book, so what you don't understand here you may later on in a different context. Go ahead and read the Advanced Topic sections, but again, don't worry if they confuse you at this point.

You programmers can skim or skip this chapter. The material here literals, variables, and the like is common to almost all languages. If you do read the chapter through, focus on the parts that are unique to Python, particularly the section "Python Collection Types" and the Advanced Topic section "Determining Types at Runtime." Also read the "For Programmers" sidebars.

Comments and Document Strings

Python has two ways to document, or explain, what your code is doing. One way uses code comments; the other uses document strings.

Comments

Comments, unlike the code itself, don't tell Python what to do. They're more like notes to yourself, and to other programmers who may want to modify or edit your code later, that say, "This is why I wrote it this way." In Python, a comment starts with the pound (#) character, which tells the interpreter to ignore the text after it until the end of the line. Each line of a comment must start with this character.

As the following example shows, you can put comments on their own line or you can add them after a statement.

#The following example demonstrates #printing hello world to the console print ("hello world") #this prints hello world

For Programmers: Comments in Other Languages

Visual Basic uses two double quotes (" ") to indicate a comment, but otherwise it uses comments like Python does; so does UNIX. Java, C, and C++ have two types of comments. One is similar to Python's but uses two forward slashes (//). The other is a multiline comment starting with /* and ending with */. Python doesn't have a multiline comment style.

Document Strings

Document strings are literals that you put at the beginning of modules, functions, classes, and methods. Unlike comments, they're not thrown away but can be displayed from the interactive interpreter. The following example (comments.py) shows a document string for a module, a class, and a function, respectively. (We'll get to these in Chapter 5.)

"""Example showing a module document string for the comments module. This module document string is multi-line. """ class Camp:       """Example showing a class document string"""       def sayHello(self):             return "\n Hello Mom \n Hello Dad" def sayCampHello():       """Example showing a function document string"""       camp = Camp()       print ("Hello: " + camp.sayHello()) if __name__ == "__main__":       sayCampHello()

Here's another example. The __doc__ attribute of the Camp class and the sayCampHello() function hold the document strings.

C:\book\chap2>jython -i comments.py Hello:  Hello Mom  Hello Dad >>> Camp.__doc__ 'Example showing a class document string' >>> sayCampHello.__doc__ 'Example showing a function document string'

Let's say we want to learn something about a module named comments and we don't have the source code. So, we start a new Jython session, import comments to it, and view its document string.

>>> import comments >>> print comments.__doc__ Example showing a module document string for the comments module. This module document string is multi-line.

In the example below, notice the dir command. Python's dir is like the dir command at a DOS prompt, but, unlike the DOS dir, which lists files and directories, it shows members of a module, class, or instance. This means that you can use it to list a comment's attributes.

>>> dir (comments) ['Camp', '__doc__', '__file__', '__name__', 'sayCampHello']

Here we see the __file__ and __name__ attributes, which provide the file path and name of this module. We also see Camp and sayCampHello, so we can check if they have the __doc__ attribute. (Follow along.)

>>> from comments import Camp, sayCampHello >>> dir (Camp) # List the attributes for Camp class ['__doc__', '__module__', 'sayHello'] >>> dir (sayCampHello) # List attributes for sayCampHello [] >>> Camp.__doc__ 'Example showing a class document string' >>> sayCampHello.__doc__ 'Example showing a function document string'

The Camp class does have a __doc__ attribute listing, but, strangely, the sayCampHello() function doesn't. Still, we can print out its document string. That's because, although functions don't show attributes, they do have the __doc__ attribute built in.

Statements

A statement is simply an instruction to Python to perform a task. Through the interpreter, Python reads the statement and does as instructed. In other words, it executes the statement. In this example, each line is a statement.

Hello = "Hello %s how are you doing" from java import awt print ("Hello World")

By default, a statement is contained on a single line. A multiline statement is indicated by a backslash at the end of each of its lines and an indentation at the beginning of the next. Here's one complete statement spanning two lines:

>>> reallyLongLine = 5 + 5 - 5 * 5 /5 * 100 - 1000 \  + 200 - 300 + 60 / 5

Two statements can fit on one line if they're separated by a semicolon.

>>> print("Hello"); print("Goodbye") Hello Goodbye

You can also end a statement with a semicolon.

>>> print ("This statement has a semicolon at the end"); This statement has a semicolon at the end >>> print ("This one does not") This one does not >>>

Stylewise, an ending semicolon isn't the best idea, but if you're switching between Jython and Java or CPython and C or C++, it's a nice feature because in these languages using semicolons to terminate a line is standard. You can't do this when switching between C++ and Visual Basic. If you try, you'll probably get a few frustrating syntax errors.

For Programmers: Multiline Statements and Visual Basic

If you come from a Visual Basic background, Python's style of line continuation should be familiar. The only real difference between the two is Python's use of a backslash (\) and Visual Basic's use of an underscore(_) and an End statement (Function End, Sub End, etc.) to mark the end of a statement instead of indentation.

If you come from a Java background, Python's line continuation and code block indentation may seem a little weird. Java explicitly ends statements with a semicolon, so there's no need for a line continuation indicator. It uses the backslash for string continuation. Indenting in Java is strictly up to the taste and style of the individual programmer.

Statements use whitespace tabs and spaces to denote an associated block of code. It can also denote a suite associated with a clause in a compound statement. (Compound statements and suites will be covered in Chapter 3.) The amount of whitespace within a statement doesn't matter. All of the following examples do the same thing even though the whitespace in each is different.

x=1 x = 1 x =   1 x =     1

Expressions

Expressions are also instructions to Python to perform a task. That task is to return a value, such as the result of a mathematical operation or the truth or falsity of a statement. Expressions can be assigned variables. Also, many of them use operators, which can be words like and, or, and not, or symbols such as + (plus), - (minus), * (multiplication), and = (equals). We'll cover operators in detail in Chapter 3. For now, just remember that expressions return a value and usually use operators.

For Novices: Expressions in Spreadsheets

If you've ever used spreadsheets, you've used expressions and operators. An expression is equivalent to a spreadsheet formula.

Let's say that, in cell D1 of a spreadsheet, you have the formula =(A1*B1)/C1, which multiplies cell A1 by cell B1 and then divides their product by C1. The equivalent in Python is D1 = (A1*B1)/C1, where D1, A1, and C1 are variables. The right side of this equation (A1*B1)/C1 is the actual expression.

To illustrate how expressions work, we'll first create three variables, x, y, and z.

>>> x,y,z = 1, 2, 3 # This is *not* an expression

(Notice the comment in the above example. See the box titled "Assignment" for an explanation.)

The following examples are pretty self-explanatory. They illustrate, in turn, the use of the multiplication operator, the division operator, and the logical operator and (all of which will be covered in Chapter 3). What they all demonstrate is this simple point: Expressions are statements that return values.

>>> y * 2 4 >>> 10 / z 3 >>> x and y 2 >>> x and 0 0

Assignment

In the example that creates the variables we used in our expression, the comment stated This is *not* an expression. In fact, it may look like an expression, but in Python it's actually an assignment. Take a look at the following code, in which it appears that a value is returned:

x = y = z = 3 

We might think that z = 3 returns 3, and y = z returns the value of z, which is 3, but this isn't the case. We know this because in interactive interpreter mode an expression is printed out to the screen.

>>> x = y = z = 3 >>> x = z >>> x==z 1 

As you can see, x = z and x = y = z = 3 aren't printed to the screen, which means that they don't return a value and so are not expressions. In Python, the use of the comparison operator (==), not the assignment operator, is what makes a statement an expression. This is because the == returns a value, usually 1 or 0, whereas = doesn't.

In Java, C, and C++, an assignment is an expression, which is why confusing the assignment and comparison operators is a common programmer error (mostly in C and C++; Java has its own way of dealing with this problem).

Consider these two examples:

if(x=z): pass while(x=z): pass 

Here the if and while statements expect an expression, that is, a value to be returned, but the assignment operator can't do this, and syntax errors are the result.

Variables

Think of variables as individual storage containers that hold different kinds of data in memory. Each variable has a name and a value, and each variable value has a type.

Declaring Variables

In most languages, before you can use a variable you have to declare it; that is, you must assign it a name and a type. Python is different; unlike in other languages, you declare a variable implicitly by assigning a value to it. Here's an example:

# declare age to be of type integer and of value 28. age = 28 # declare name to be of type string # and of value "rick" name = "rick"

Variable declarations can go anywhere in a module. You can declare more than one variable at once by stringing them together. (Follow along).

>>> x,y,z = 1,2,3 >>> print ("x=" + `x` + " y=" + `y` + " z=" +`z`) x=1 y=2 z=3

The first statement defines three variables as of type Integer (that is, whole numbers) and assigns them the values 1, 2, and 3, such that x = 1, y = 2, and z = 3. Notice that in the second statement the variable names are enclosed in back quotes. That tells Python to convert the variable to a string.

Here's an interactive example of Python stringing together several variable definitions with different types:

>>> name, age, sex = "Kiley", 22, "female" >>> print (name + " is " + `age` + " and " + sex) Kiley is 22 and female

For Programmers: Variable Declarations in Python as Compared to Visual Basic and Java

In Python, you can't access a variable that you haven't declared, but remember: The first time you assign a value to a variable, you declare that variable. That means that you can't make the mistake of trying to use an unassigned variable, as you can in Visual Basic. Only if you don't use Visual's Explicit option can you use a variable that has no value assigned.

Visual Basic has a Variant type, which can be anything. Python variables don't have a type unto themselves but are whatever type is assigned to them String, List, and so forth so they support dynamic polymorphism with their late-binding features. Visual Basic also supports dynamic polymorphism as well. (Polymorphism is discussed in Chapter 6.)

In Java, variable declaration is very strict. You have to explicitly declare the variables themselves and their types. Even so, you can do dynamic polymorphic programming if you declare a variable a superclass of the instance you're working with.

Obviously, Python is more flexible and dynamic than Java, but not as type safe. If you come from a Smalltalk background, this is probably a boon, but probably not if you come from C++. Read Appendix C on the advantages of scripting languages, and then decide for yourself.

Valid Variable Names

Variable names in Python can start with a letter or an underscore (_). After the first character, they can also contain numbers, and they can be as long as you want them to be. Keep in mind that variable names are case sensitive. That is, age, AGE, and Age mean different things to the interpreter. Here are a few valid variable names:

_name = "John Souza" favorite_sport = "Baseball" SF49ers = "San Francisco 49ers"

Here are some invalid ones:

$name = "John Souza" favorite sport = "Baseball" 49ers = "San Francisco 49ers"

Data Types

Each variable has a type, which can be the following:

  • One of the six basic data types (see the next section)

  • One of the five standard container types

  • One of the standard callable types

  • One of the two object-oriented types

  • Any Java class or standard object

In this chapter we'll cover the basic types.

The Basic Data Types

Most of the six basic data types in Python are analogous to the basic types in Visual Basic and Java. Here they are:

  • String sequences of characters

  • Integer integers (whole numbers)

  • Float floating-point numbers

  • Long large integers

  • None no value

  • Type type

All of them are built into the system. Unlike in Java, everything in Python is an object, including functions, modules, and types. (We'll get to objects in Chapter 6, which is on object-oriented programming.)

Float, Integer, and Long are numeric types. The table below shows their individual ranges that is, the size of the values they can hold.

Type From To
Integer 2,147,483,648 2,147,483,647
Float 4.9e 324 1.7976931348623157e308
Long As small as you want As big as you want

 

For Programmers: Numeric Type Ranges

The range of the numeric types depends on the system running them, unless, of course, they're running under Java. This means that, in Jython, Integer is implemented with Java Int, and Float is implemented with Java Double. The reverse is true in CPython: Integer is implemented with C Long, and Float with C Double. Long has an unlimited range in both CPython and Jython. Unlike in C, in Java Integer always holds the same range of values.

You often need to know the biggest or smallest Integer or Float type, but trying to remember this information is difficult. I'm going to show you an interactive session that will give you this information when you need it. Remember that Float in Python equates to Java Double, so the first thing to do is import class Double from the java.lang package.

>>> from java.lang import Double 

We could instead do a dir on Double to see its MAX_VALUE and MIN_VALUE attributes.

>>> dir (Double) ['MAX_VALUE', 'MIN_VALUE', 'NEGATIVE_INFINITY', 'NaN', 'POSITIVE_INFINITY', 'TYPE', '__doc__', '__init__', '__module__', 'compareTo', 'doubleToLongBits', 'infinite', 'isInfinite', 'isNaN', 'longBitsToDouble', 'naN', 'parseDouble', 'toString', 'valueOf'] 

Here's how to access the largest and smallest Float, respectively:

>>> Double.MAX_VALUE 1.7976931348623157E308 >>> Double.MIN_VALUE 4.9E-324 

Now we'll do the same thing for the biggest and smallest Integer.

>>> from java.lang import Integer >>> max = Integer.MAX_VALUE >>> min = Integer.MIN_VALUE >>> max, min (2147483647, -2147483648) 

TypeType

As I said before, everything in Python is an object, that is, a "container" for properties and methods. This means that all of the basic types are of type Type that is, a variable type that holds another variable type. Here's the proof:

>>> if type(FloatType) == TypeType: ...     print("FloatType is of TypeType") ... FloatType is of TypeType

For Programmers: Jython versus Python

In Jython, the built-in type() function returns the class name of the Java implementation for that type for Jython. For example:

>>> int = 1 #holds a integer >>> float = 1.0 #holds a float >>> long = 1L #holds a long >>> string = "string" #holds a string >>> type (int) <jclass org.python.core.PyInteger at -712990957> >>> type (long) <jclass org.python.core.PyLong at 46702445> >>> type (string) <jclass org.python.core.PyString at -710631661> >>> type (float) <jclass org.python.core.PyFloat at -1307009172> >>> type (FloatType) <jclass org.python.core.PyJavaClass at -693854445> >>> type (TypeType) <jclass org.python.core.PyJavaClass at -693854445> >>> type (None) <jclass org.python.core.PyNone at -693592301> 

In Python, the type() function returns Int, Long, String, and Float instead of the Java class name.

None

Variables that reference nothing are of type None, meaning that they have no value. If you work with databases, think of None as similar to NULL. Don't think of it as zero, which is a value. Programmers, you may know that in Java and Visual Basic the counterparts to Python's None are, respectively, null and Nothing. In Delphi, this same concept is called Nil.

Python Collection Types

One thing that sets Python apart from most other languages is its built-in collection types. As in the real world, in programming a collection represents more than one item. By "built-in" I mean that Python uses a special syntax for its collections, which it calls sequences. Strings are also considered sequences in Python, so all of the rules that apply to strings also apply to collections slice notation, indexes, and so forth.

For Programmers: Hashtables, Vectors, and Collection Objects

If you use Java, you probably use hashtables and vectors in about 85 percent of the programs you write. Hashtables are similar to Python dictionaries, and vectors are similar to Python lists. The key difference is that Python's lists, dictionaries, and tuples have built-in syntax support for addition, multiplication, member referencing, literals, for loop iteration, and so forth. This makes things easier on the programmer. It also means that you can define objects to act like collections so that other programmers can use the syntax when working with them.

The Visual Basic collection object is like Python's list and dictionary rolled into one. Visual Basic supports for loop iteration, as Python does, but otherwise it offers no collection support. Perl's collection support is the only one that comes close to Python's.

Lists

Whereas a string holds a sequence of characters, a list holds a sequence of objects of various types, which you access as you do characters in strings. You can even use slice notation, which we learned about in Chapter 1.

>>>    #Define a list with 5 values in it >>> mylist = ["hello","goodbye", 1, 1.0, 50000000000000000L] >>>    #print the first object in the list >>> print (mylist[0]) hello >>>    #print the first two objects in the list >>> print (mylist[0:2]) ['hello', 'goodbye'] >>>    #print the whole list >>> print (mylist[0:]) ['hello', 'goodbye', 1, 1.0, 50000000000000000L] >>>

You can tell a list by the square brackets ([ ]) that surround it. Empty brackets mean that there are no items in the list.

Lists can be added and multiplied.

>>> list1 = [] #create an empty list >>> list2 = ["a", "b", 10, 11, 12, 13] >>> list1 # show the empty lists contents [] >>> list2 #show the contents of the list with items ['a', 'b', 10, 11, 12, 13] >>> list1 = list2 + list2 #add the lists together >>> list1 ['a', 'b', 10, 11, 12, 13, 'a', 'b', 10, 11, 12, 13] >>> list1 = list2 * 2 #multiply a list >>> list1 ['a', 'b', 10, 11, 12, 13, 'a', 'b', 10, 11, 12, 13]

You can also append and remove list items, with the list object's append() and remove() methods. Chapter 5 is where we'll cover methods and functions; for now all you need to know to use append() and remove() is the form variable_name.methodname(arguments). (You'll learn about arguments in Chapter 5 as well.) Here's an example that continues the previous interactive session:

>>> # remove 'a' from the list >>> list1.remove('a') >>> # display the contents of list1 >>> list1 ['b', 10, 11, 12, 13, 'a', 'b', 10, 11, 12, 13] >>> # remove 'a' from the list again >>> list1.remove('a') >>> #display the contents of the list >>> list1 ['b', 10, 11, 12, 13, 'b', 10, 11, 12, 13] >>> #put the 'a' back in the list >>> list1.append('a') >>> list1 ['b', 10, 11, 12, 13, 'b', 10, 11, 12, 13, 'a'] >>> len (list1) 11

Note that remove() gets rid of only the first occurrence of an item, so to remove both instances of 'a', we have to invoke list1.remove('a') twice. By the way, you can determine how many items are in a list with the len() (length) function.

Another interesting thing you can do with lists is sort them, with sort(), and reverse their order, with reverse(). For instance, you might want your list in alphabetical or reverse alphabetical order.

>>> names = [] >>> #append a bunch of names to the names list >>> names.append("Kiley") >>> names.append("Rick") >>> names.append("Mary") >>> names.append("Adam") >>> names.append("Missy") >>> names.append("Martha") >>> #display names before the sort >>> names ['Kiley', 'Rick', 'Mary', 'Adam', 'Missy', 'Martha'] >>> #sort the names alphabetically >>> names.sort() >>> #display names after sort >>> names ['Adam', 'Kiley', 'Martha', 'Mary', 'Missy', 'Rick'] >>> #reverse the order of the list >>> names.reverse() >>> names ['Rick', 'Missy', 'Mary', 'Martha', 'Kiley', 'Adam']

With insert() you can insert items into the middle of a list. With index(), you determine where an item is numerically.

>>> #display the contents of the names list >>> names ['Rick', 'Missy', 'Mary', 'Martha', 'Kiley', 'Adam'] >>> #determine the index of the "Rick" string >>> names.index("Rick") 0 >>> #insert "Kiley" string next to "Rick" >>> names.insert(1, "Kiley") >>> names ['Rick', 'Kiley', 'Missy', 'Mary', 'Martha', 'Kiley', 'Adam'] >>> #find the index of the "Martha" string >>> names.index("Martha") 4 >>> #insert the "Miguel" string next to Martha >>> names.insert(5, "Miguel") >>> #display the name list >>> names ['Rick', 'Kiley', 'Missy', 'Mary', 'Martha', 'Miguel', 'Kiley', 'Adam']

count() determines the number of times an item occurs in a list.

>>> # Initialize the names list >>> names = ["James", "James", "James", "Bob", "Joe", "Sam"] >>> # Count number of "James" strings in names >>> names.count("James") 3

Tuples

Tuples are collection types similar to lists in that they contain items. However, they're immutable, which means that you can't change them once defined you can't append or remove items or add two tuples together. All you can do is multiply them.

>>> # create an empty tuple >>> tuple1 = () >>> # create a tuple with three greetings >>> tuple2 = ("Hi", "Bye", "Salutations") >>> # multiply this tuple2 and assign to tuple >>> tuple1 = tuple2 * 2 >>> # display the contents of tuple >>> tuple1 ('Hi', 'Bye', 'Salutations', 'Hi', 'Bye', 'Salutations')

This example shows tuples being declared in parentheses, but this isn't mandatory. Furthermore, you can use a tuple to initialize more than one variable and use more than one variable to initialize a tuple. To see this, follow along with this interactive session.

>>> #initialize a tuple without parentheses >>> tuple3 = 3,2,1 >>> tuple3 (3, 2, 1)

Here we initialized tuple3 with three numbers without parentheses. To be explicit, we defined a variable of type Tuple that contains three numeric items with values of 3, 2, and 1.

In the following example, we initialize three numbers with a tuple. In other words, we declare three variables named x, y, and z; then we assign 3 to x, 2 to y, and 1 to z.

>>> x,y,z = 3,2,1 >>> x 3 >>> y 2 >>> z 1

Now we can use these three variables to create a tuple. That is, we use them to declare a tuple, tuple4, that contains the three variables' values.

>>> tuple4 = x,y,z >>> tuple4 (3, 2, 1)

The opposite of this is to use a tuple to declare three new variables by defining them and using tuple4 to initialize them.

>>> q,r,s = tuple4 >>> q 3 >>> r 2 >>> s 1

For Novices: Lists and Tuples Are Both Sequences

Lists work as tuples do for declaring multiple variables and for using variables to assign values to lists. The only difference is that they require brackets. The following example is similar to the examples we saw for tuples, but it uses lists instead.

>>> x,y,z = [5,6,7] >>> x 5 >>> y 6 >>> z 7 >>> list1 = [x,y,z] >>> list1 [5, 6, 7] >>> q,r,s = list1 >>> q 5 >>> r 6 >>> s 7

Dictionaries

A dictionary, another Python collection type, stores keys and values. It uses key/value pairs to locate a value, which can be any object of any type. The dictionary declares a series of key/value pairs using the notation key:value and separates the individual pairs with commas.

>>> namesToAges = {"joe":30, "kelly":32, "john":28} >>> joesAge = namesToAges["joe"] >>> print ("Joe is " + `joesAge` + " years old") Joe is 30 years old >>>

namesToAges is the dictionary, "joe" is the key, and 30 is the value.

Remember that a dictionary is a sequence, and like a sequence you access it by its name and by the index of the value in it that you're looking for. What's different is that the location is a key into the dictionary. In the last example, we wanted to find Joe's age. To do that we had to use the key, "joe", in square brackets like a list, in the namesToAges dictionary. Keys can be any object of any immutable type, such as strings, tuples, or numeric values. However, you can use tuples for dictionary keys only if they contain only immutable items.

A dictionary can be searched by its keys, its values, or its key/value pairs. To get all of a dictionary's keys, values, or pairs, you use keys(), values(), or items(), respectively. We'll continue the previous example to illustrate how.

>>>          #display namesToAges dictionary >>> namesToAges {'john': 28, 'joe': 30, 'kelly': 32} >>>          #display keys in dictionary >>> namesToAges.keys() ['john', 'joe', 'kelly'] >>>          #display values in dictionary >>> namesToAges.values() [28, 30, 32] >>>          #display items in dictionary >>> namesToAges.items() [('john', 28), ('joe', 30), ('kelly', 32)]

To see if a particular key, such as "joe" or "james" is in a dictionary, we can do this:

>>> namesToAges.has_key("joe") 1 >>> namesToAges.has_key("james") 0

Advanced Topic: Determining Types at Runtime

You can determine a type at runtime with the built-in type() function along with the Python types module, which defines all of the basic types.

First, we import the types module and create some variables from all of the basic types.

>>> from types import * >>> int = 1 #holds a integer >>> float = 1.0 #holds a float >>> long = 1L #holds a long >>> string = "string" #holds a string

Now we test to see if the variable string is of type String. Here we'll be using the if statement, which works like if in other languages. Just remember that if's subordinate statements must be indented. (We'll be covering this in Chapter 4.)

The ... prompt tells you to enter the subordinate statement, print. Make sure to indent print, and then hit Enter to indicate that the if statement is finished.

Here is your first if statement, step by step.

  1. At the >>>, type

    >>> if type(string) == StringType: [hit Return]

  2. At the ... prompt,

    [hit Tab] print ("string is a StringType") [hit Return]

  3. At the ... prompt,

    [hit Return]

The next three interactive sessions test whether the variable int is of type Integer, the variable float is of type Float, and the variable long is of type Long.

>>> if type(int) == IntType: ...     print("int is a IntType") ... int is a IntType >>> if type(float) == FloatType: ...     print("float is a FloatType") ... float is a FloatType >>> if type(long) == LongType: ...     print("long is a Long") ... long is a Long

Just for a sanity check, let's see if the string variable is a Float type.

>>> if type(string) == FloatType: ...     print("string is a float") ... else: ...     print("Don't be a GOOF!") ... Don't be a GOOF!

Literals

We've been using literals since Chapter 1, but we didn't call them that. The term is computerspeak for a constant value; that is, what you type is literally what you get. In the following interactive session, for example, the literals are "Hello World", 100, 3200000000000L, and 3.5.

>>> a_literal_string = "Hello World" >>> a_literal_integer = 100 >>> a_literal_long = 3200000000000L >>> a_float_literal = 3.5

Literals can be contained in statements.

print ("Hello I am a literal string")
Table 2-1. Escape Sequence Characters
Character Meaning
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\r ASCII Carriage return (CR)
\t ASCII Horizontal tab (TAB)
\v ASCII Vertical tab (VT)
\ooo ASCII character with octal value ooo
\xhh... ASCII character with hex value hh

String literals are identified by the quotes that enclose them. The quotes can be single (' '), double (" "), triple single (' ' '), or triple double ( " " " ). Here are the four styles illustrated:

>>> string1 = "Hello World" >>> print (string1) #print the string1 to the output Hello World >>> string2 = 'Hello World' >>> print (string2) #compare this output to the first form Hello World >>> string3 = """Hello World""" >>> print (string3) #compare this output to the 1st and 2nd form Hello World >>> string4 = '''Hello World''' >>> print (string4) #compare this output to the first three forms of Strings Hello World

If you're wondering why there are four ways to identify literals, I intend to tell you, but first I have to explain escape sequences.

An escape sequence is a way to add special ASCII characters to a new line or a formfeed. As in Java and C, it's identified in Python by the backslash (\) for example \n (newline). Table 2-1 lists the escape sequence characters.

In the following example, we see that \n places the phrase Goodbye Earth on a new line.

>>> string = "Hello Mars \n Goodbye Earth \n" >>> print (string) Hello Mars  Goodbye Earth >>>

Here we see that \t inserts tabs between Hello Mars and Goodbye Earth and between Goodbye Earth and Goodbye Moon.

>>> string = "Hello Mars \t Goodbye Earth \t Goodbye Moon" >>> print (string) Hello Mars    Goodbye Earth    Goodbye Moon >>>

Escape sequences can get a little messy, especially when you add quotes or newlines to your string. Consider the following interactive session:

>>> print ("She said, \"I love you \" and I said \n \"remember Paris in the spring") #one line She said, "I love you " and I said "remember Paris in the spring >>>

Python has another way, and this is where the different quoting styles come in handy. Strings that use triple-double or triple-single quotes can span multiple lines and include actual quoted lines within them. That means that the previous example can be rewritten as

>>> print ("""She said, "I love you", and I said, ... "remember Paris in the spring" """) #two lines She said, "I love you", and I said, "remember Paris in the spring" >>>

Fun with Escape Characters

Redo the tabs (\t) interactive session with vertical tabs (\v). You should get something weird that looks like the universal symbol for male. Now cut and paste the output line from the DOS box into Microsoft Word. (Use Edit->Mark from the Windows menu from the DOS box. Once the text is selected, choose Edit->Copy Enter from the Windows menu of the DOS box, which will put the text on the clipboard. Then return to Word and paste the text.) What happens?

Numeric Literals

We define integer literals in three ways: regular (base 10), hexadecimal (base 16), and octal (base 8). This code shows three literals that equate to the same integer value, 255.

>>> base10 = 255 >>> base16 = 0xff >>> base8 = 0377 >>> base10,base16,base8 (255, 255, 255) >>>

An octal starts with 0; a hexadecimal, with 0x. If you're not familiar with octal and hexadecimal numbers, don't worry; you don't need them to program in Python.

Exponential notation defines floating-point literals like this:

>>> million = 1e6 >>> million 1000000.0 >>> billion = 1e+9 >>> billion 1.0E9 >>> gates_net = 36.7e+9 >>> gates_net 3.67E10 >>> average_income = 30e3 >>> average_income 30000.0 >>> volts = 3e-3 >>> volts 0.003

We define arbitrarily long integers by appending an L to them.

>>> bignum = 99999999999999999999999999999999999999L >>> bignum 99999999999999999999999999999999999999L

Summary

In this chapter, we covered comments and document strings, which can be used to document Python code. Unlike comments, document strings can be accessed with the interactive interpreter.

We looked at Python easy-to-use built-in container types (dictionaries, tuples, and lists), the values of which are defined by literals. Literals indicate simple values of types Integer, Float, String, and Long.

Statements are instructions to Python to perform tasks. Expressions are simple statements that return a value and usually involve the use of operators. Function and class methods are made up of statements and expressions.

CONTENTS


Python Programming with the JavaT Class Libraries. A Tutorial for Building Web and Enterprise Applications with Jython
Python Programming with the Javaв„ў Class Libraries: A Tutorial for Building Web and Enterprise Applications with Jython
ISBN: 0201616165
EAN: 2147483647
Year: 2001
Pages: 25

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net