Chapter 3. Variables — Names for Values

In the previous two chapters, you learned how Python views strings, integers, floats, and imaginary numbers and how they can be created and displayed. This chapter presents more examples that demonstrate how these data types can be used.

In this chapter you learn:

  • To use names to store the types you already know as well as other basic types to which you will be introduced.

  • How to work with different types of objects that you haven't learned about yet. Variables and new, different types — specifically, you will become better acquainted with lists, tuples, and dictionaries.

  • What a reference is and have some experience in using references.

  • To get the most out of this chapter, you should type the examples yourself and alter them to see what happens.

Referring to Data — Using Names for Data

It's difficult to always write strings and numbers explicitly throughout a program because it forces you to remember everything. The exacting memory that computers have enable them to remember far more details than people can, and taking advantage of that capability is a huge part of programming. However, to make using data more flexible and easy, you want to give the data names that can be used to refer to them.

Changing Data Through Names

If your data is a number or a string, you can change it by using the operations you already know you can do with them.

Copying Data

The name that you give data is only a name. It's how you refer to the data that you're trying to access. This means that more than one name can refer to the same data:

>>> pennies_saved=1
>>> pennies_earned = pennies_saved
>>> print(pennies_earned)
1

When you use the = sign again, you are referring your name to a new value that you've created, and the old value will still be pointed to by the other name:

>>> pennies_saved = pennies_saved + 1
>>> print(pennies_saved)
2
>>> print(pennies_earned)
1

Names You Can't Use and Some Rules

Python uses a few names as special built-in words that it reserves for special use to prevent ambiguity. The following words are reserved by Python and can't be used as the names for data:

and, as, assert, break, class, continue, def, del, elif, else,
except, exec,False,  finally, for, from, global, if, import, in,
is, lambda, not, None, or, pass, print, raise, return, try, True,
while, with, yield

In addition, the names for data cannot begin with numbers or most non-alphabet characters (such as commas, plus or minus signs, slashes, and so on), with the exception of the underscore character. The underscore is allowed and even has a special meaning in some cases (specifically with classes and modules, which you see in Chapter 6 and later).

You will see a number of these special reserved words in the remaining discussion in this chapter. They're important when you are using Python to do various tasks.

Using More Built-in Types

Beside strings and numbers, Python provides four other important basic types: tuples, lists, sets, and dictionaries. These four types have a lot in common because they all allow you to group more than one item of data together under one name. Each one also gives you the capability to search through them because of that grouping. These groupings are indicated by the presence of enclosing parentheses (), square brackets [], and curly braces {}.

Note

When you write a program, or read someone else's program, it is important to pay attention to the type of enclosing braces when you see groupings of elements. The differences among {}, [], and () are important.

Tuples — Unchanging Sequences of Data

In Chapters 1 and 2, you saw tuples (rhymes with supple) being used when you wanted to assign values to match more than one format specifier in a string. Tuples are a sequence of values, each one accessible individually, and a tuple is a basic type in Python. You can recognize tuples when they are created because they're surrounded by parentheses:

>>> print("A %s %s %s %s" % ("string", "filled", "by a", "tuple"))
A string filled by a tuple

Lists — Changeable Sequences of Data

Lists, like tuples, are sequences that contain elements referenced starting at zero. Lists are created by using square brackets:

>>> breakfast = [ "coffee", "tea", "toast", "egg" ]

Dictionaries — Groupings of Data Indexed by Name

A dictionary is similar to lists and tuples. It's another type of container for a group of data. However, whereas tuples and lists are indexed by their numeric order, dictionaries are indexed by names that you choose. These names can be letters, numbers, strings, or symbols — whatever suits you.

Treating a String Like a List

Python offers an interesting feature of strings. Sometimes, it is useful to be able to treat a string as though it were a list of individual characters. It's not uncommon to have extraneous characters at the end of a string. People may not recognize these, but computers will get hung up on them. It's also common to only need to look at the first character of a string to know what you want to do with it. For instance, if you had a list of last names and first names, you could view the first letter of each by using the same syntax that you would for a list. This method of looking at strings is called slicing and is one of the fun things about Python:

>>> last_names = [ "Douglass", "Jefferson", "Williams", "Frank", "Thomas" ]
>>> print("%s" % last_names[0])
Douglass
>>> print("%s" % last_names[0][0])
D
>>> print("%s" % last_names[1])
Jefferson
>>> print("%s" % last_names[1][0])
J
>>> print("%s" % last_names[2])
Williams
>>> print("%s" % last_names[2][0])
W
>>> print("%s" % last_names[3])
Frank
>>> print("%s" % last_names[3][0])
F
>>> print("%s" % last_names[4])
Thomas
>>> print("%s" % last_names[4][0])
T

For example, you can use the letter positioning of strings to arrange them into groups in a dictionary based on the first letter of the last name. You don't need to do anything complicated; you can just check to see which letter the string containing the name starts with and file it under that:

>>> by_letter = {}
>>> by_letter[last_names[0][0]] = last_names[0]
>>> by_letter[last_names[1][0]] = last_names[1]
>>> by_letter[last_names[2][0]] = last_names[2]
>>> by_letter[last_names[3][0]] = last_names[3]
>>> by_letter[last_names[4][0]] = last_names[4]

The by_letter dictionary will, thanks to string slicing, only contain the first letter from each of the last names. Therefore, by_letter is a dictionary indexed by the first letter of each last name. You could also make each key in by_letter reference a list instead and use the append method of that list to create a list of names beginning with that letter (if, of course, you wanted to have a dictionary that indexed a larger group of names, where each one did not begin with a different letter).

Remember that, like tuples, strings are immutable. When you are slicing strings, you are actually creating new strings that are copies of sections of the original string.

Special Types

Python has a handful of special types. You've seen them all, but they bear mentioning on their own: None, True, and False are all special built-in values that are useful at different times.

None is special because there is only one None. It's a name that no matter how many times you use it, it doesn't match any other object, just itself. When you use functions that don't have anything to return to you — that is, when the function doesn't have anything to respond with — it will return None.

True and False are special representations of the numbers 1 and 0. This prevents a lot of the confusion that is common in other programming languages where the truth value of a statement is arbitrary. For instance, in a UNIX shell (shell is both how you interact with the system, as well as a programming language), 0 is true and anything else is false. With C and Perl, 0 is false and anything else is true. However, in all of these cases, there are no built-in names to distinguish these values. Python makes this easier by explicitly naming the values. The names True and False can be used in elementary comparisons, which you'll see a lot; and in Chapter 4, you learn how these comparisons can dramatically affect your programs — in fact, they enable you to make decisions within your program.

>>> True
True
>>> False
False
>>> True == 1
True
>>> True == 0
False
>>> False == 1
False
>>> False == 0
True
>>> False > 0
False
>>>False < 1
True

Other Common Sequence Properties

The two types of sequences are tuples and lists; and as you've seen, in some cases strings can be accessed as though they were sequences as well. Strings make sense because you can view the letters in a string as a sequence.

Even though dictionaries represent a group of data, they are not sequences, because they do not have a specific ordering from beginning to end, which is a feature of sequences.

Referencing the Last Elements

All of the sequence types provide you with some shortcuts to make their use more convenient. You often need to know the contents of the final element of a sequence, and you can get that information in two ways. One way is to get the number of elements in the list and then use that number to directly access the value there:

>>> last_names = [ "Douglass", "Jefferson", "Williams", "Frank", "Thomas" ]
>>> len(last_names)
5
>>> last_element = len(last_names) - 1
>>> print("%s" % last_names[last_element])
Thomas

However, that method takes two steps; and as a programmer, typing it repeatedly in a program can be time-consuming. Fortunately, Python provides a shortcut that enables you to access the last element of a sequence by using the number −1, and the next-to-last element with −2, letting you reverse the order of the list by using negative numbers from −1 to the number that is the negative length of the list (−5 in the case of the last_names list).

>>> print("%s" % last_names[−1])
Thomas
>>> print("%s" % last_names[−2])
Frank
>>> print("%s" % last_names[−3])
Williams

Ranges of Sequences

You can take sections of a sequence and extract a piece from it, making a copy that you can use separately. The term for creating these groupings is called slicing (the same term used for this practice when you did it with strings). Whenever a slice is created from a list or a tuple, the resulting slice is the same type as the type from which it was created, and you've already seen this with strings. For example, a slice that you make from a list is a list, a slice you make from a tuple is a tuple, and the slice from a string is a string.

Growing Lists by Appending Sequences

Suppose you have two lists that you want to join together. You haven't been shown a purposely built way to do that yet. You can't use append to take one sequence and add it to another. Instead, you will find that you have layered a sequence into your list:

>>> living_room = ("rug", "table", "chair", "TV", "dustbin", "shelf")
>>> apartment = []
>>> apartment.append(living_room)
>>> apartment
[('rug', 'table', 'chair', 'TV', 'dustbin', 'shelf')]

This is probably not what you want if you were intending to create a list from the contents of the tuple living_room that could be used to create a list of all the items in the apartment.

To copy all of the elements of a sequence, instead of using append, you can use the extend method of lists and tuples, which takes each element of the sequence you give it and inserts those elements into the list from which it is called:

>>> apartment = []
>>> apartment.extend(living_room)
>>> apartment
['rug', 'table', 'chair', 'TV', 'dustbin', 'shelf']

Using Lists to Temporarily Store Data

You'll often want to acquire data from another source, such as a user entering data or another computer whose information you need. To do that, it is best to put this data in a list so that it can be processed later in the same order in which it arrived.

However, after you've processed the data, you no longer need it to be in the list, because you won't need it again. Temporal (time-specific) information such as stock tickers, weather reports, or news headlines would be in this category.

To keep your lists from becoming unwieldy, a method called pop enables you to remove a specific reference to data from the list after you're done with it. When you've removed the reference, the position it occupied will be filled with whatever the next element was, and the list will be reduced by as many elements as you've popped.

Working with Sets

Sets are similar to dictionaries in Python, except that they consist of only keys with no associated values. Essentially, they are a collection of data with no duplicates. They are very useful when it comes to removing duplicate data from data collections.

Sets come in two types: mutable and immutable frozensets. The difference between the two is that with a mutable set, you can add, remove, or change its elements, while the elements of an immutable frozenset cannot be changed after they have been initially set.

Summary

In this chapter, you learned how to manipulate many core types that Python offers. These types are tuples, lists, dictionaries, sets, and three special types: None, True, and False. You've also learned a special way that strings can be treated like a sequence. The other sequence types are tuples and lists.

A tuple is a sequence of data that's indexed in a fixed numeric order, starting at zero. The references in the tuple can't be changed after the tuple is created, nor can it have elements added or deleted. However, if a tuple contains a data type that has changeable elements, such as a list, the elements of that data type are not prevented from changing. Tuples are useful when the data in the sequence is better off not changing, such as when you want to explicitly prevent data from being accidentally changed.

A list is another type of sequence, which is similar to a tuple except that its elements can be modified. The length of the list can be modified to accommodate elements being added using the append method, and the length can be reduced by using the pop method. If you have a sequence whose data you want to append to a list, you can append it all at once with the extend method of a list.

Dictionaries are yet another kind of indexed grouping of data. However, whereas lists and tuples are indexed by numbers, dictionaries are indexed by values that you choose. To explore the indexes, which are called keys, you can invoke the keys method. To explore the data that is referred to, called the values, you can use the values method. Both of these methods return lists.

Sets are a collection of items (0 or more), that contain no duplicates. In theory, they are similar to dictionaries, except that they only have keys, and no values associated with those keys. One use for sets is to remove any duplicates from a collection of data. They are also good at mimicking finite mathematical sets.

Other data types are True, False, and None. True and False are a special way of looking at 1 and 0, but when you want to test whether something is true or false, explicitly using the names True and False is always the right thing to do. None is a special value that is built into Python that only equals itself, and it is what you receive from functions that otherwise would not return any value (such as True, False, a string, or other values).

The key things to take away from this chapter are:

  • Variables are names for data that let you refer to the data.

  • You create a variable by using the syntax: variablename = "Some value".

  • You can copy the value in one variable by assigning it to another: variablename = copyofvariablename.

  • Tuples store more than piece of data and are unchangeable.

  • Lists are also sequences of data, yet unlike tuples, you can change their value.

  • A dictionary is similar to lists and tuples. It's another type of container for a group of data. However, whereas tuples and lists are indexed by their numeric order, dictionaries are indexed by names that you choose. These names can be letters, numbers, strings, or symbols — whatever suits you.

Exercises

Perform all of the following in the Python shell:

  1. Create a list called dairy_section with four elements from the dairy section of a supermarket.

  2. Print a string with the first and last elements of the dairy_section list.

  3. Create a tuple called milk_expiration with three elements: the month, day, and year of the expiration date on the nearest carton of milk.

  4. Print the values in the milk_expiration tuple in a string that reads "This milk carton will expire on 12/10/2009."

  5. Create an empty dictionary called milk_carton. Add the following key/value pairs. You can make up the values or use a real milk carton:

    • expiration_date: Set it to the milk_expiration tuple.

    • fl_oz: Set it to the size of the milk carton on which you are basing this.

    • Cost: Set this to the cost of the carton of milk.

    • brand_name: Set this to the name of the brand of milk you're using.

  6. Print out the values of all of the elements of the milk_carton using the values in the dictionary, and not, for instance, using the data in the milk_expiration tuple.

  7. Show how to calculate the cost of six cartons of milk based on the cost of milk_carton.

  8. Create a list called cheeses. List all of the cheeses you can think of. Append this list to the dairy_section list, and look at the contents of dairy_section. Then remove the list of cheeses from the array.

  9. How do you count the number of cheeses in the cheese list?

  10. Print out the first five letters of the name of your first cheese.

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

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