Fundamentals of Python: From First Programs Through Data Structures

Slides:



Advertisements
Similar presentations
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Advertisements

String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Lecture 2 Introduction to C Programming
Guide to Programming with Python
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Python Dictionary.
Chapter 10.
VBA Modules, Functions, Variables, and Constants
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
Introduction to C Programming
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Fundamentals of Python: From First Programs Through Data Structures
Chapter 8: String Manipulation
Programming with Microsoft Visual Basic th Edition
Fundamentals of Python: First Programs
Introduction to Python
Lists in Python.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 14 Tuples, Sets, and Dictionaries 1.
Java Programming, Second Edition Chapter Five Input and Selection.
Input, Output, and Processing
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Fundamentals of Python: First Programs
Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Built-in Data Structures in Python An Introduction.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
CONTENTS Processing structures and commands Control structures – Sequence Sequence – Selection Selection – Iteration Iteration Naming conventions – File.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Computer Science 111 Fundamentals of Programming I Dictionaries redux.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Eight String Manipulation.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Programming with Microsoft Visual Basic 2008 Fourth Edition Chapter Eight String Manipulation.
Data Collections CS 127. Lists Lists are ordered sequences of items All programming languages provide a sequence structure similar to a Python list; in.
Chapter 9: Completing the Basics. In this chapter, you will learn about: – Exception handling – Exceptions and file checking – The string class – Character.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Dictionaries. The compound types you have learned about - - strings, lists, and tuples – use integers as indices. If you try to use any other type as.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
String and Lists Dr. José M. Reyes Álamo.
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
Containers and Lists CIS 40 – Introduction to Programming in Python
Department of Computer Science,
Introduction to Scripting
JavaScript: Functions.
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
Topics Introduction to File Input and Output
CS190/295 Programming in Python for Life Sciences: Lecture 6
String and Lists Dr. José M. Reyes Álamo.
Fundamentals of Python: First Programs
Python Primer 1: Types and Operators
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Fundamentals of Python: First Programs Second Edition
Topics Introduction to File Input and Output
Lists [] First = [1, 2, 3, 4] Second = list[range(1,5)]
Presentation transcript:

Fundamentals of Python: From First Programs Through Data Structures Chapter 5 Lists and Dictionaries

Objectives After completing this chapter, you will be able to: Construct lists and access items in those lists Use methods to manipulate lists Perform traversals of lists to process items in the lists Define simple functions that expect parameters and return values Fundamentals of Python: From First Programs Through Data Structures

Objectives (continued) Construct dictionaries and access entries in those dictionaries Use methods to manipulate dictionaries Decide whether a list or a dictionary is an appropriate data structure for a given application Fundamentals of Python: From First Programs Through Data Structures

Introduction A list allows the programmer to manipulate a sequence of data values of any types A dictionary organizes data values by association with other data values rather than by sequential position Lists and dictionaries provide powerful ways to organize data in useful and interesting applications Fundamentals of Python: From First Programs Through Data Structures

Lists List: Sequence of data values (items or elements) Some examples: Shopping list for the grocery store To-do list Guest list for a wedding Recipe, which is a list of instructions Text document, which is a list of lines Words in a dictionary Each item in a list has a unique index that specifies its position (from 0 to length – 1) Fundamentals of Python: From First Programs Through Data Structures

List Literals and Basic Operators Some examples: ['apples', 'oranges', 'cherries'] [[5, 9], [541, 78]] When an element is an expression, its value is included in the list: Lists of integers can be built using range: Fundamentals of Python: From First Programs Through Data Structures

List Literals and Basic Operators (continued) len, [], +, and == work on lists as expected: To print the contents of a list: in detects the presence of an element: Fundamentals of Python: From First Programs Through Data Structures

List Literals and Basic Operators (continued) Fundamentals of Python: From First Programs Through Data Structures

Replacing an Element in a List A list is mutable Elements can be inserted, removed, or replaced The list itself maintains its identity, but its state—its length and its contents—can change Subscript operator is used to replace an element: Subscript is used to reference the target of the assignment, which is not the list but an element’s position within it Fundamentals of Python: From First Programs Through Data Structures

Replacing an Element in a List (continued) Examples: Fundamentals of Python: From First Programs Through Data Structures

List Methods for Inserting and Removing Elements The list type includes several methods for inserting and removing elements Fundamentals of Python: From First Programs Through Data Structures

List Methods for Inserting and Removing Elements (continued) Fundamentals of Python: From First Programs Through Data Structures

Searching a List in determines an element’s presence or absence, but does not return position of element (if found) Use method index to locate an element’s position in a list Raises an error when the target element is not found Fundamentals of Python: From First Programs Through Data Structures

Sorting a List A list’s elements are always ordered by position, but you can impose a natural ordering on them For example, in alphabetical order When the elements can be related by comparing them <, >, and ==, they can be sorted The method sort mutates a list by arranging its elements in ascending order Fundamentals of Python: From First Programs Through Data Structures

Mutator Methods and the Value None All of the functions and methods examined in previous chapters return a value that the caller can then use to complete its work Mutator methods (e.g., insert, append) usually return no value of interest to caller Python automatically returns the special value None Fundamentals of Python: From First Programs Through Data Structures

Aliasing and Side Effects Mutable property of lists leads to interesting phenomena: first and second are aliases (refer to the exact same list object) Fundamentals of Python: From First Programs Through Data Structures

Aliasing and Side Effects (continued) To prevent aliasing, copy contents of object: Alternative: Fundamentals of Python: From First Programs Through Data Structures

Equality: Object Identity and Structural Equivalence Fundamentals of Python: From First Programs Through Data Structures

Example: Using a List to Find the Median of a Set of Numbers Fundamentals of Python: From First Programs Through Data Structures

Tuples A tuple resembles a list, but is immutable Indicate by enclosing its elements in () Most of the operators and functions used with lists can be used in a similar fashion with tuples Fundamentals of Python: From First Programs Through Data Structures

Defining Simple Functions Defining our own functions allows us to organize our code in existing scripts more effectively Fundamentals of Python: From First Programs Through Data Structures

The Syntax of Simple Function Definitions Definition of a function consists of header and body Docstring contains information about what the function does; to display, enter help(square) A function can be defined in a Python shell, but it is more convenient to define it in an IDLE window Syntax of a function definition: Fundamentals of Python: From First Programs Through Data Structures

Parameters and Arguments A parameter is the name used in the function definition for an argument that is passed to the function when it is called For now, the number and positions of arguments of a function call should match the number and positions of the parameters in the definition Some functions expect no arguments They are defined with no parameters Fundamentals of Python: From First Programs Through Data Structures

The return Statement Place a return statement at each exit point of a function when function should explicitly return a value Syntax: If a function contains no return statement, Python transfers control to the caller after the last statement in the function’s body is executed The special value None is automatically returned Fundamentals of Python: From First Programs Through Data Structures

Boolean Functions A Boolean function usually tests its argument for the presence or absence of some property Returns True if property is present; False otherwise Example: Fundamentals of Python: From First Programs Through Data Structures

Defining a main Function main serves as the entry point for a script Usually expects no arguments and returns no value Definition of main and other functions can appear in no particular order in the script As long as main is called at the end of the script Script can be run from IDLE, imported into the shell, or run from a terminal command prompt Fundamentals of Python: From First Programs Through Data Structures

Defining a main Function (continued) Fundamentals of Python: From First Programs Through Data Structures

Case Study: Generating Sentences Request: write a program that generates sentences Analysis: program will generate sentences from a simplified subset of English Fundamentals of Python: From First Programs Through Data Structures

Case Study: Generating Sentences (continued) Design: Assign task of generating each phrase to a separate function Fundamentals of Python: From First Programs Through Data Structures

Case Study: Generating Sentences (continued) Implementation (coding): The variables for the data are initialized just below the import statement Fundamentals of Python: From First Programs Through Data Structures

Case Study: Generating Sentences (continued) Fundamentals of Python: From First Programs Through Data Structures

Case Study: Generating Sentences (continued) Testing: Two approaches: Bottom-up Top-down Wise programmer can mix bottom-up and top-down testing as needed Fundamentals of Python: From First Programs Through Data Structures

Dictionaries A dictionary organizes information by association, not position Example: When you use a dictionary to look up the definition of “mammal,” you don’t start at page 1; instead, you turn directly to the words beginning with “M” Data structures organized by association are also called tables or association lists In Python, a dictionary associates a set of keys with data values Fundamentals of Python: From First Programs Through Data Structures

Dictionary Literals A Python dictionary is written as a sequence of key/value pairs separated by commas Pairs are sometimes called entries Enclosed in curly braces ({ and }) A colon (:) separates a key and its value Examples: {'Sarah':'476-3321', 'Nathan':'351-7743'} A Phone book {'Name':'Molly', 'Age':18} Personal information {} An empty dictionary Keys can be data of any immutable types, including other data structures Fundamentals of Python: From First Programs Through Data Structures

Adding Keys and Replacing Values Add a new key/value pair to a dictionary using []: Example: Use [] also to replace a value at an existing key: Fundamentals of Python: From First Programs Through Data Structures

Accessing Values Use [] to obtain the value associated with a key If key is not present in dictionary, an error is raised If the existence of a key is uncertain, test for it using the dictionary method has_key Easier strategy is to use the method get Fundamentals of Python: From First Programs Through Data Structures

Removing Keys To delete an entry from a dictionary, remove its key using the method pop pop expects a key and an optional default value as arguments Fundamentals of Python: From First Programs Through Data Structures

Traversing a Dictionary To print all of the keys and their values: Alternative: Use the dictionary method items() Entries are represented as tuples within the list You can sort the list first: Fundamentals of Python: From First Programs Through Data Structures

Traversing a Dictionary (continued) Fundamentals of Python: From First Programs Through Data Structures

Example: The Hexadecimal System Revisited You can keep a hex-to-binary lookup table to aid in the conversion process Fundamentals of Python: From First Programs Through Data Structures

Example: Finding the Mode of a List of Values The mode of a list of values is the value that occurs most frequently The following script inputs a list of words from a text file and prints their mode Fundamentals of Python: From First Programs Through Data Structures

Example: Finding the Mode of a List of Values (continued) Fundamentals of Python: From First Programs Through Data Structures

Case Study: Nondirective Psychotherapy (Request) Doctor in this kind of therapy responds to patient’s statements by rephrasing them or indirectly asking for more information Request: Write a program that emulates a nondirective psychotherapist Fundamentals of Python: From First Programs Through Data Structures

Case Study: Nondirective Psychotherapy (Analysis) Fundamentals of Python: From First Programs Through Data Structures

Case Study: Nondirective Psychotherapy (Analysis) (continued) When user enters a statement, program responds in one of two ways: With a randomly chosen hedge, such as “Please tell me more” By changing some key words in user’s input string and appending string to a randomly chosen qualifier Thus, to “My teacher always plays favorites,” program might reply, “Why do you say that your teacher always plays favorites?” Fundamentals of Python: From First Programs Through Data Structures

Case Study: Nondirective Psychotherapy (Design) Program consists of a set of collaborating functions that share a common data pool Pseudocode: output a greeting to the patient while True prompt for and input a string from the patient if the string equals “Quit” output a sign-off message to the patient break call another function to obtain a reply to this string output the reply to the patient Fundamentals of Python: From First Programs Through Data Structures

Case Study: Nondirective Psychotherapy (Implementation) Fundamentals of Python: From First Programs Through Data Structures

Case Study: Nondirective Psychotherapy (Implementation) (continued) Fundamentals of Python: From First Programs Through Data Structures

Case Study: Nondirective Psychotherapy (Testing) Functions in this program can be tested in a bottom-up or a top-down manner Program’s replies break down when: User addresses the therapist in the second person User uses contractions (for example, I’m and I’ll) With a little work, you can make the replies more realistic Fundamentals of Python: From First Programs Through Data Structures

Summary A list is a sequence of zero or more elements Can be manipulated with the subscript, concatenation, comparison, and in operators Mutable data structure index returns position of target element in a list Elements can be arranged in order using sort Mutator methods are called to change the state of an object; usually return the value None Assignment of a variable to another one causes both to refer to the same data object (aliasing) Fundamentals of Python: From First Programs Through Data Structures

Summary (continued) A tuple is similar to a list, but is immutable A function definition consists of header and body return returns a value from a function definition A dictionary associates a set of keys with values [] is used to add a new key/value pair to a dictionary or to replace a value associated with an existing key dict type includes methods to access and remove data in a dictionary Testing can be bottom-up, top-down, or you can use a mix of both Fundamentals of Python: From First Programs Through Data Structures