Variables


Python variables do not have to be declared before you can use them. You do not need to add a $ in front of variable names, as you do in Perl or in shell scripts when getting the value of a variable. In fact, variable names cannot start with a special character. Python variable names, and the language in general, are case-sensitive.

This section explains how you can use numbers, strings, lists, and dictionaries. Python also has a file data type, which is described in the section “Input and Output.” Data types that are not covered here include tuples, which are very similar to lists, and sets, which are like unordered lists. For information about tuples and sets, see http://docs.python.org/tut/node7.html.

Numbers

Python supports integers and floating-point numbers, as well as complex numbers. Variables are assigned with=(equals), as shown.

 x = y = −10           # Set both x and y equal to the integer −10 dist = 13.7           # This is a floating-point decimal z = 7 – 3j            # The letter j marks the imaginary part of a complex number

Python also allows you to enter numbers in scientific notation, hexadecimal, or octal. See http://docs.python.org/ref/integers.html and http://docs.python.org/ref/floating.html for more information.

You can perform all of the usual mathematical operations in Python:

 >>> print 5 + 3 8 >>> print 2.5 – 1.5 1.0 >>> print (6–4j) * (6+4j)      # Can multiply complex numbers just like integers. (52+0j) >>> print 7 / 2                # Division of two integers returns an integer! 3 >>> print 7.0 / 2 3.5 >>> print 2 ** 3               # The operator ** is used for exponentiation 8 >>> print 13 % 5               # Modulus is done with the % operator 3

In newer versions of Python, if you run your script with python -Qnew, integer division will return a floating-point number when appropriate.

Variables must be initialized before they can be used. For example,

 >>> n = n + 1 NameError: name 'n' is not defined

will cause an error if n has not yet been set. This is true of all Python variable types, not just numbers.

Python supports some C-style assignment shortcuts:

 >>> x = 4 >>> x += 2            # Add 2 to x >>> print x 6 >>> x /= 1.0          # Divide x by 1.0, which converts it to a floating-point >>> print x 6.0

But not the increment or decrement operators:

 >>> X++ SyntaxError: invalid syntax

Functions such as float, int, and hex can be used to convert numbers. For example,

 >>> print float(26)/5 5.2 >>> print int (5.2) 5 >>> print hex (26) 0x1a

You can assign several variables at once if you put them in parentheses:

 (x, y) = (1.414, 2.828)                    # Same as x = 1.414 and y = 2.828

This works for any type of variable, not just numbers.

Useful Modules for Numbers

The math module provides many useful mathematical functions, such as sqrt (square root), log (natural logarithm), and sin (sine of a number). It also includes the constants e and pi. For example,

 >>> import math >>> print math.pi, math.e 3.14159265359 2.71828182846 >>> print math.sqrt(3**2 + 4**2) 5.0

The module cmath includes similar functions for working with complex numbers.

The random module includes functions for generating random numbers.

 import random x = random.random()                          # Random number, with 0 <= x < 1 diceroll = int (random.random() * 6) + 1     # Random integer from 1 to 6 dice2 = int (random.uniform(1, 7))           # Equivalent to previous statement.

Strings

Python allows you to use either single or double quotes around strings. Strings can contain escape sequences, including \n for newline and \t for tab. Here is an example of a string:

 >>> title = "Alice's Adventures\nin Wonderland" >>> print title Alice's Adventures in Wonderland

Printing Strings

Since variable names do not start with a distinguishing character (such as $), Python does not expand variables if you embed them in a string. One way to print variables as part of a string is with the concatenation operator, +, which allows you to combine several strings:

 >>> name = "Alice" >>> print "The value of name is " + name The value of name is Alice

There are some drawbacks to this method. The concatenation operator only works on strings, so variables of other data types (such as numbers) must be converted to a string with str() in order to concatenate them. When many variables and strings are combined in one statement, the result can be messy:

 >>> (n1, n2, n3) = (5, 7, 2) >>> print "First:" + str(n1) + "Second:" + str (n2) + "Third:" + str (n3) First: 5 Second: 7 Third: 2

You can shorten this a little bit by giving print a list of arguments separated by commas. This allows you to print numbers without first converting them to strings. In addition, print automatically adds a space between each term. So you could replace the print statement in the previous example with

 >>> print "First:", n1, "Second:", n2, "Third:", n3 First: 5 Second: 7 Third: 2

If you add a comma at the end of a print statement, print will not add a newline at the end, so this example will print the same line as the previous two:

 print "First:", n1, print "Second:", n2, print "Third:", n3

Another way to include variables in a string is with variable interpolation, like this:

 >>> print "How is a %s like a %s?" % ('raven', 'writing desk') How is a raven like a writing desk? >>> year = 1865 >>> print "It was published in %d." % year It was published in 1865. >>> print "%d times %f is %f" % (4, 0.125, 4 * 0.125) 4 times 0.125000 is 0.500000

The operator % (which works a little like the C command printf) replaces the format codes embedded in a string with the values that follow it. The format codes include %s for a string, %d for an integer, and %f for a floating-point value. The full set of codes you can use to format strings is documented at http://docs.python.org/lib/typesseq-strings.html.

Because the % formatting operator produces a string, it can be used anywhere a string can be used. So, for example,

 print len("Hello, %s" % name)

will print the length of the string after the value of name has been substituted for %s.

String Operators

As you have seen, the + operator concatenates strings. For example,

 fulltitle = title + '\nby Lewis Carroll'

The * operator repeats a string some number of times, as in

 print '-' * 80                # Repeat the - character 80 times.

which prints a row of dashes.

The function len returns the length of a string.

 length = len("Jabberwocky\n")

The length is the total number of characters, including the newline at the end, so in this example length would be 12.

You can index the characters in strings as you would the values in an array (or a list). For example,

 print name [3]

will print the fourth character in name (since the first index is 0, the fourth index is 3).

String Methods

This sections lists some of the most common string methods. A complete list can be found at http://docs.python.org/lib/string-methods.html.

The method strip() removes white space from around a string. For example,

 >>> print "            Jabberwocky             ".strip() Jabberwocky

You can also use lstrip() or rstrip() to remove leading or trailing white space.

The methods upper() and lower() convert a string to upper- or lowercase.

 >>> str = "Hello, world" >>> print str.upper (), str.lower () HELLO, WORLD hello, world

You can use the method center() to center a string:

 >>> print "'Twas brillig, and the slithy toves".center(80)                         'Twas brillig, and the slithy toves >>> print "Did gyre and gimble in the wabe" . center (80)                           Did gyre and gimble in the wabe

You can split a string into a list of substrings with split(). By itself, split() will divide the string wherever there is white space, but you can also include a character by which to divide the string. For example,

 wordlist = sentence.split()              # Split a sentence into a list of words passwdlist = passwdline.split(':')       # Split a line from /etc/passwd

join() is an interesting method that concatenates a list of strings into a single string. The original string is used as the separator when building the new string. For example,

 print ":".join(passwdlist)

will restore the original line from /etc/passwd.

To find the first occurrence of a substring, use find(), which returns an index. Similarly, rfind() returns the index of the last occurrence.

 scriptpath = "/usr/bin/python" i = scriptpath.rfind('/')                    # i = 8

You can use replace() to replace a substring with a new string:

 newpath = oldpath.replace('perl', 'python')

This example replaces perl with python every time it occurs in oldpath, and saves the result in newpath. The method count() can be used to count the number of times a substring occurs.

More powerful tools for working with strings are discussed in the section “Regular Expressions” later in this chapter.

Lists

A list is a sequence of values. For example,

 mylist = [3, "Queen of Hearts", 2.71828, x]

Lists can contain any types of values (even other lists). There is no limit to the size or number of elements in a list, and you do not need to tell Python how big you want a list to be.

Each element in a list can be accessed or changed by referring to its index (starting from 0 for the first element):

 print mylist[1]         # Print "Queen of Hearts" mylist[0] += 2          # Change the first element to 5

You can also count backward through the array with negative indices. For example, mylist[1] is the last element in mylist, mylist[2] is the element before that, and so on.

You can get the number of elements in a list with the function len(), like this:

 size = len (mylist)               # size is 4,  because mylist has 4 elements

The range() function is useful for creating lists of integers. For example,

 numlist = range (10)             # numlist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

creates a list containing the numbers from 0 to 9.

List Slices

Python allows you to select a subsection of a list, called a slice. For example, you could create a new list containing elements 2 through 5 of numlist:

 numlist = range (10) sublist = numlist[2:6]            # sublist=[2, 3, 4, 5]

In this example, the slice starts at index 2 and goes up to (but does not include) index 6. If you leave off the first number, the slice starts at the beginning of the string, so

 sublist = numlist[:4]             # sublist = [0, 1, 2, 3]

would assign the first 4 elements of numlist to sublist. Similarly, you can leave off the last number to include all the elements up to the end of the string, as in

 sublist = numlist[4:]             # sublist = [4, 5, 6, 7, 8, 9]

You can also use slices to assign new values to part of a list. For example, you could change the elements at indices 1 and 3 of mylist with

 mylist[1:4] = [new1, mylist[2], new3]

Slices work on strings as well as lists. For example, you could remove the last character from a string with

 print inputstr[:−1]

List Methods

The sort() method sorts the elements in a list. For strings, sort() uses ASCII order (in which all the uppercase letters go before the lowercase letters). For numbers, sort() uses numerical order (e.g., it puts “5” before “10”). sort() works in place, meaning that it changes the original list rather than returning a new list.

 mylist.sort() print mylist

The reverse() method reverses the order of the elements in a list. Like sort(), reverse() works in place. The sort() and reverse() methods can be used one after another to put a list in reverse ASCII order.

You can add a new element at the end of a list with append(). For example,

 mylist.append(newvalue)             # Same as mylist[len(mylist)] = newvalue

extend() is just like append(), but it appends all the elements from another list.

To insert an element elsewhere in a list, you can use insert():

 mylist.insert(0, newvalue)            # Insert newvalue at index 0

This will cause all the later elements in the list to shift down one index. To remove an element from a list, you can use pop(). pop() removes and returns the element at a given index. If no argument is given, the last element in the list is removed.

 print mylist.pop(0)       # Print and remove the first element of mylist mylist.pop()              # Remove the last element

Dictionaries

A dictionary is like a list, but it uses arbitrary values, called keys, for the indices. Dictionaries are sometimes called associative arrays. (In Perl, they are called hashes. There is no equivalent intrinsic type in C, although they can be implemented using hashtables.)

As an example, suppose you want to be able to look up a user’s full name when you know that user’s login name. You could create a dictionary, like this:

 fullname = {"lewisc": "L. Carroll", "mhatter": "Bertrand Russell"}

This dictionary has two entries, one for user lewisc and one for user mhatter. To create an empty dictionary, use an empty pair of brackets, like this:

 newdictionary = {}

Adding to a dictionary is just like adding to a list, but you use the key as the index:

 fullname["aliddell"] = "Alice Liddell"

Similarly, you can look up values like this:

 print fullname["mhatter"]

which will print “Bertrand Russell”.

Note that since keys are used to look up values, each key must be unique. To store more than one value for a key, you could use a list, like this:

 dict={} dict['v'] = ['verse', 'vanished', 'venture'] dict['v'].append('vorpal')

Here’s a longer example of a dictionary:

 daysweek = {    "Sunday": 1,    "Monday": 2,    "Tuesday": 3,    "Wednesday": 4,    "Thursday": 5,    "Friday": 6,    "Saturday": 7, } print "Thursday is day number", daysweek['Thursday']

This dictionary links the names of the days to their positions in the week.

Working with Dictionaries

You can get a list of all the keys in a dictionary with the method keys, like this

 listdays = daysweek.keys()            # "Sunday", "Monday", etc

To check if a dictionary contains a particular key, use the method has_key:

 >>> print daysweek. has_key ("Fri") False >>> print daysweek.has_key("Friday") True

This is commonly used in an if statement, so that you can take some particular action depending on whether a key is defined or not. (Note that some older versions of Python will print 0 for false and 1 for true.)

The del statement removes a key (and the associated value):

 >>> del daysweek [ "Saturday"] >>> del daysweek ["Sunday"] >>> print daysweek {'Monday': 2, 'Tuesday': 3, 'Wednesday': 4, 'Thursday': 5, 'Friday': 6}

The function len returns the number of entries in the dictionary:

 print "There are", len (daysweek), "entries."

If you have never used associative arrays, then dictionaries may seem strange at first. But they are remarkably useful, especially for working with text. You will see examples of how convenient dictionaries can be later in this chapter.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

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