Introduction to Python Programming for Business and Social Science Applications. Frederick Kaefer

Чтение книги онлайн.

Читать онлайн книгу Introduction to Python Programming for Business and Social Science Applications - Frederick Kaefer страница 24

Introduction to Python Programming for Business and Social Science Applications - Frederick Kaefer

Скачать книгу

a dictionary is and how we can define one. We also learned about a number of operations that are used to work with dictionaries to do things like returning information corresponding to a dictionary entry or adding or changing a dictionary entry.

      Example Using Tuples and Dictionaries

      The following example illustrates the usefulness of both tuples and dictionaries in an example using data from the GSS. As described in Chapter 1 when we introduced the GSS data set, many of the fields in the data set are coded. Dictionaries are very useful when working with coded data to look up the meaning of specific codes. The Python code in Figure 3.21 also demonstrates the usefulness of tuples when passing multiple arguments to a function.

      A screenshot displays a Python code in a Python file as an example for tuple and dictionary.Description

      Figure 3.21 Tuple and Dictionary Example

      The execution of the Python code in Figure 3.21 begins on line 14, as the code that precedes that is a function that we only execute when we invoke it using Python code statements. The code in line 14 creates a tuple of two elements, which are codes corresponding to the data fields “Region” and “Happy” from the GSS. The code in line 15 prints out the value of the variable codes, which is a tuple shown in the first line of output in Figure 3.22. Line 16 calls the code_lookup function with the codes variable as an argument and then assigns the function result to the response variable. It is at this point in the code execution that the flow of control transfers to the code_lookup function starting in line 3. Line 4 unpacks the tuple into two variables, region and happy. Line 5 uses a print statement to display the values of those two variables, shown in the second line of output in Figure 3.22. These variables result from the tuple that the function received as an argument, but they are not tuples themselves but rather individual values. Lines 6 to 9 and 10 to 11 create two dictionaries used in line 12. Line 12 uses a return statement to pass back to the code that called this function two values. The first value is the value found in the region_dict dictionary corresponding to the region key value. The second value is the value in the happy_dict dictionary corresponding to the happy key value. When the flow of control returns to line 16, the interpreter creates a variable (a tuple) through the assignment of the two returned values. This code in line 17 prints out the value of the result variable and in the third line of output in Figure 3.22. Finally, lines 18 and 19 print the individual values from indexing the tuple. Note in line 18 that the index value of 0 references the first value, and in line 19, the index value of 1 references the second value in the tuple. The output in the last two lines of Figure 3.22 shows the results of these two lines of code.

      A screenshot displays the output from the execution of the Python code from tuple and dictionary example.Description

      Figure 3.22 Output from Tuple and Dictionary Example

      Dictionaries will resurface later in Chapter 5 when we talk more about structured data, and we will see tuples again as some packages have functions or objects with methods that either require parameters to be tuples or return results in tuples.

      Lessons learned: In this section, we demonstrated using both tuples and dictionaries alongside each other in our code. We learned that tuples can be very useful for passing multiple values to a function and that dictionaries are very useful with looking up values that correspond to coded data, such as that found in the GSS data set.

      Chapter Summary

      In this chapter, we introduced the mutable list object and the immutable tuple object. We learned that lists enable us to store multiple values of different data types in the same variable and that each item in a list can be referenced using an index value. We also learned about list methods, which are actions that can be performed to or with lists. Lists are very useful when working with data sets that are made up of different types of data. We also learned about Python string operations, which are very useful when working with portions of strings. We learned that strings are immutable, so we are not able to modify portions of strings in place, but we are able to replace strings by assigning portions of a string or combinations of string portions using concatenation. We then learned how Python sequence operations can be used on strings and lists to do things like searching for values or counting how many times a value appears in a list of values. We also learned about tuples, which are immutable sequences. Tuples have important usages when we have sequences of elements that we do not want to change.

      We also learned about Python dictionaries in this chapter and how we can define one. We learned a number of operations that are used to work with dictionaries to do things like returning information corresponding to a dictionary entry or adding or changing a dictionary entry. We then demonstrated using both tuples and dictionaries alongside each other in our code. We learned that tuples can be very useful for passing multiple values to a function and that dictionaries are very useful for looking up values that correspond to coded data, such as that found in the GSS data set.

      In the next chapter, we will cover control logic and loops, which enable the conditional and repeated execution of code statements but also can make it more challenging to detect and resolve errors. At the end of the next chapter, we will cover error handling as well as techniques that are useful in identifying and resolving logic errors in Python code.

      Glossary

      CharacterThe smallest possible component of a text. Characters vary depending on the language and context used.Compound data typesData types that group together multiple values.ConcatenationOperation that combines multiple strings into one string.DictionaryA data type that contains key-value pairs. Known in other languages as associative arrays or hash tables, this enables the programmer to store multiple related data values in one structure and reference entries by their specified key values.Dictionary keysUsed to locate values within a dictionary, must be an immutable type.Dot operatorUsed to reference a method property of an object.ImmutableHaving a value that is not modifiable.IndexA reference to a specific element of a data structure such as a list.ListAn object that is a collection of elements that are referenceable using an index.MutableHaving a value that is modifiable.SlicingAccesses a portion of a string by referencing a starting index and an ending index value.TupleLike lists, tuples are sequences. However, unlike lists, tuples are immutable, meaning they are not modifiable. This can be useful to ensure integrity of the data throughout the program.

      End-of-Chapter Exercises

       3.1. Identify the names of the functions and methods used in the following code.Description

       3.2. Use the input() function learned in Chapter 2 to input three strings (a first name, a middle initial, and a last name). Concatenate these strings together with a space between each, storing the result in a new variable. Print out the concatenated string.

       3.3. Define a list of survey response values (5, 7, 3, and 8) and store them in a variable. Next define a tuple of respondent ID values (1012, 1035, 1021, and 1053). Use the .append() method to append the tuple to the list. Print out the list. What happened?

       3.4. Create the list of responses from Exercise 3.3 (values 5, 7, 3, 8). Next add the response “0”

Скачать книгу