Python Review IPRE

Similar documents
Python Review IPRE

Python Intro GIS Week 1. Jake K. Carr

The Practice of Computing Using PYTHON

Data Structures. Lists, Tuples, Sets, Dictionaries

Python and Bioinformatics. Pierre Parutto

Compound Data Types 2

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

University of Texas at Arlington, TX, USA

Python: common syntax

def order(food): food = food.upper() print( Could I have a big + food + please? ) return fresh + food

Topic 7: Lists, Dictionaries and Strings

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif

Sequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

1 Strings (Review) CS151: Problem Solving and Programming

Collections. Lists, Tuples, Sets, Dictionaries

CMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Slicing. Open pizza_slicer.py

Python I. Some material adapted from Upenn cmpe391 slides and other sources

CS1 Lecture 11 Feb. 9, 2018

MITOCW watch?v=rvrkt-jxvko

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Sharing, mutability, and immutability. Ruth Anderson UW CSE 160 Spring 2018

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments

Unit 2. Srinidhi H Asst Professor

CS 2316 Exam 1 Spring 2014

Types, lists & functions

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Advanced Python. Executive Summary, Session 1

Comp 151. More on working with Data

Python - Variable Types. John R. Woodward

Introduction to Computer Programming for Non-Majors

Episode 3 Lists and Strings

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

MUTABLE LISTS AND DICTIONARIES 4

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

Introduction to Python. Data Structures

S206E Lecture 19, 5/24/2016, Python an overview

Lists, loops and decisions

Here n is a variable name. The value of that variable is 176.

Python debugging and beautification

COMP1730/COMP6730 Programming for Scientists. Strings

Notebook. March 30, 2019

Try and Error. Python debugging and beautification

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Babu Madhav Institute of Information Technology, UTU 2015

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

CMSC201 Computer Science I for Majors

LECTURE 3 Python Basics Part 2

CMSC201 Computer Science I for Majors

Compound Data Types 1

Chapter 2: Lists, Arrays and Dictionaries

Using Lists (Arrays) Notes

Ex: If you use a program to record sales, you will want to remember data:

Introduction to Problem Solving and Programming in Python.

ENGR/CS 101 CS Session Lecture 12

Level 3 Computing Year 2 Lecturer: Phil Smith

Python Tutorial. Day 1

For strings (and tuples, when we get to them), its easiest to think of them like primitives directly stored in the variable table.

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Review Sheet for Midterm #1 COMPSCI 119 Professor William T. Verts

CIS192 Python Programming

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

CS 1301 Exam 2 Fall 2010

The Pyth Language. Administrivia

A list a **mutable** collection of ordered items, that can be of mixed type - created using square brackets.

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Mr. Monroe s Guide to Mastering Java Syntax

Introduction to Computer Programming for Non-Majors

Notes on Chapter 1 Variables and String

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Programming in Python

CS 11 python track: lecture 3. n Today: Useful coding idioms

Script language: Python Data structures

Announcements. Lecture Agenda. Class Exercise. Hashable. Mutability. COMP10001 Foundations of Computing Iteration

python 01 September 16, 2016

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

Data Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.

Python for ArcGIS. Lab 1.

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Advanced Algorithms and Computational Models (module A)

"Hello" " This " + "is String " + "concatenation"

ENGR 102 Engineering Lab I - Computation

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Python. Executive Summary

DM502 Programming A. Peter Schneider-Kamp.

All programs can be represented in terms of sequence, selection and iteration.

6. Data Types and Dynamic Typing (Cont.)

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

Python in 10 (50) minutes

Introduction to Python 2

Introduction to Python. Fang (Cherry) Liu Ph.D. Scien5fic Compu5ng Consultant PACE GATECH

Exercise: The basics - variables and types

Transcription:

Python Review Jay Summet 2005-12-31 IPRE

Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing Elements Cloning Slices Mutable Types: Lists Dictionaries Aliasing vs Cloning 2

Compound Data Types - A data type in which the values are made up of elements that are themselves values. Strings Enclosed in Quotes, holds characters, (immutable): This is a String Tuples Values separated by commas, (usually enclosed by parenthesis) and can hold any data type (immutable): (4, True, Test, 34.8) Lists Enclosed in square brackets, separated by commas, holds any data type (mutable): [4, True, Test, 34.8] Dictionaries Enclosed in curly brackets, elements separated by commas, key : value pairs separated by colons, keys can be any immutable data type, values can be any data type: { 1 : I, 2 : II, 3 : III, 4 : IV, 5 : V } 3

Immutable Types Strings and Tuples are immutable, which means that once you create them, you can not change them. The assignment operator (=) can make a variable point to strings or tuples just like simple data types: mystring = This is a test mytuple = (1,45.8, True, String Cheese ) Strings & Tuples are both sequences, which mean that they consist of an ordered set of elements, with each element identified by an index. 4

Accessing Elements mystring = This is a test. You can access a specific element using an integer index which counts from the front of the sequence (starting at ZERO!) mystring[0] produces 'T' mystring[1] produces 'h' mystring[2] produces 'i' mystring[3] produces 's' The len() function can be used to find the length of a sequence. Remember, the last element is the length minus 1, because counting starts at zero! mystring[ len(mystring) 1] produces '.' 5

Counting Backwards mystring = This is a test. As a short cut (to avoid writing len(mystring) ) you can simply count from the end of the string using negative numbers: mystring[ len(mystring) 1 ] produces '.' mystring[-1] also produces '.' mystring[-2] produces 't' mystring[-3] produces 's' mystring[-4] produces 'e' 6

Index out of Range! mystring = This is a test. Warning! If you try to access an element that does not exist, Python will throw an error! mystring[5000] produces An ERROR! mystring[-100] produces An ERROR! 7

Traversal MyString = Daddy, I want a Peanut butter and Jelly bread. How many J s are in the string? 8

Traversals Many times you need to do something to every element in a sequence. (e.g. Check each letter in a string to see if it contains a specific character.) Doing something to every element in a sequence is so common that it has a name: a Traversal. You can do a traversal using a while loop as follows: index = 0 while ( index < len (mystring) ): if mystring[index] == 'J': print Found a J! index = index + 1 9

Easy Traversals The FOR Loop Python makes traversals easy with a FOR loop: for ELEMENT_VAR in SEQUENCE: STATEMENT STATEMENT A for loop automatically assigns each element in the sequence to the (programmer named) ELEMENT_VAR, and then executes the statements in the block of code following the for loop once for each element. Here is an example equivalent to the previous WHILE loop: for myvar in mystring: if myvar == 'J': print I found a J! Note that it takes care of the indexing variable for us. 10

Grabbing Slices from a Sequence The slice operator will clip out part of a sequence. It looks a lot like the bracket operator, but with a colon that separates the start and end points. SEQUENCE_VAR [ START : END ] mystring = This is a test. mystring[0:2] produces 'Th' (0, 1, but NOT 2) mystring[3:6] produces 's I' (3-5, but NOT 6) POP QUIZ: mystring[ 1: 4 ] produces? mystring[ 5: 7 ] produces? 11

Slices Default values for blanks SEQUENCE_VAR [ START : END ] mystring = This is a test. If you leave the start part blank, it assumes you want zero. mystring[ : 2] produces 'Th' (0,1, but NOT 2) mystring[ : 6] produces 'This i' (0-5, but NOT 6) If you leave the end blank, it assumes you want until the end of the string mystring[ 5 : ] produces 'is a test.' (5 end) mystring [ : ] produces 'This is a test.' (0-end) 12

Using Slices to make clones (copies) You can assign a slice from a sequence to a variable. The variable points at a copy of the data. mystring = This is a test. hisstring = mystring [ 1 : 4 ] isstring = mystring [ 5 : 7 ] teststring = mystring [10 : ] 13

Tuples Tuples can hold any type of data! You can make one by separating some values with comas. Convention says that we enclose them with parenthesis to make the beginning and end of the tuple explicit, as follows: (4, True, Test, 14.8) NOTE: Parenthesis are being overloaded here, which make the commas very important! (4) is NOT a tuple (it's a 4 in parenthesis) (4,) IS a tuple of length 1 (note the trailing comma) Tuples are good when you want to group a few variables together (firstname, lastname) (x,y) 14

Using Tuples to return multiple pieces of data! Tuples can also allow you to return multiple pieces of data from a function: def area_volume_of_cube( sidelength): area = 6 * sidelength * sidelength volume = sidelength * sidelength * sidelength return area, volume myarea, myvolume = area_volume_of_cube( 6 ) Note that in this example we left out the (optional) parenthesis from the tuple (area,volume)! You can also use tuples to swap the contents of two variables: a,b = b,a 15

Tuples are sequences! Because tuples are sequences, we can access them using the bracket operator just like strings. mytuple = ( 4,48.8,True, Test ) mytuple[0 ] mytuple[ 1 ] mytuple[ 2 ] mytuple[ -1 ] produces4 produces48.8 producestrue produces'test' 16

Changing Immutable data types Immutable data types can not be changed after they are created. Examples include Strings and Tuples. Although you can not change an immutable data type, you can create a new variable that has the changes you want to make. For example, to capitalize the first letter in this string: mystring = all lowercase. mynewstring = A + mystring[1:] We have concatenated two strings (a string with the capital letter A of length 1, and a clone of mystring missing the first, lowercase, 'a'). 17

Changing mutable data types Mutable data types can be changed after they are created. Examples include Lists and Dictionaries. These changes happen in place. mylist = ['l', 'o', 'w', 'e', 'r', 'c', 'a', 's', 'e'] mylist[0] = 'L' print mylist produces: [ 'L', 'o', 'w', 'e', 'r', 'c', 'a', 's', 'e'] 18

Lists like strings & tuples, but mutable! Lists are a mutable data type that you can create by enclosing a series of elements in square brackets separated by commas. The elements do not have to be of the same data type: mylist = [ 23, True, 'Cheese, 3.1459 ] Unlike Strings and tuples, individual elements in a list can be modified using the assignment operator. After the following commands: mylist[0] = True mylist[1] = 24 mylist[3] = Boo mylist contains: [ True, 24, 'Cheese', 'Boo' ] 19

Different Elements, Different Types Unlike strings, which contain nothing but letters, list elements can be of any data type. mylist = [ True, 24, 'Cheese', 'Boo' ] for eachelement in mylist: print type(eachelement) produces: <type 'bool'> <type 'int'> <type 'str'> <type 'str'> 20

List Restrictions and the append method Just like a string, you can't access an element that doesn't exist. You also can not assign a value to an element that doesn't exist. Lists do have some helper methods. Perhaps the most useful is the append method, which adds a new value to the end of the list: mylist = [ True, 'Boo', 3] mylist.append(5) print mylist [ True, 'Boo', 3, 5] 21

String to list >>># convert into a list of char's >>> w = list(s) >>> w ['b', 'i', 'o', 'v', 'i', 't', 'r', 'u', 'm'] >>> s = 'a few words' >>> w = s.split() >>> w ['a', 'few', 'words'] 22

Converting lists between strings >>> s = 'biovitrum' # create a string >>> w = list(s) # convert into a list of char's >>> w ['b', 'i', 'o', 'v', 'i', 't', 'r', 'u', 'm'] >>> w.reverse() >>> w ['m', 'u', 'r', 't', 'i', 'v', 'o', 'i', 'b'] >>> r = ''.join(w) # join using empty string >>> r 'murtivoib' >>> d = '-'.join(w) # join using dash char >>> d 'm-u-r-t-i-v-o-i-b' Jay Summet 2005-12-31 IPRE

Pop Quiz: convert roman letters to numbers I II III IV V VI VII VIII IX X 24

And now, for something completely different! Dictionaries are an associative data type. Unlike sequences, they can use ANY immutable data type as an index. Dictionaries will associate a key (any immutable data), with a value (any data). 25

Dictionary example: Accessing arabic2roman = { 1 : I, 2 : II, 3 : III, 4 : IV, 5 : V } You can retrieve a value from a dictionary by indexing with the associated key: arabic2roman[1] produces 'I' arabic2roman[5] produces 'V' arabic2roman[4] produces 'IV' 26

Reassigning & Creating new Key/Value associations arabic2roman = { 1 : I, 2 : II, 3 : III, 4 : IV, 5 : V } You can assign new values to existing keys: arabic2roman [1] = 'one' now: arabic2roman[1] produces 'one' You can create new key/value pairs: arabic2roman[10] = 'X' now arabic2roman[10] produces 'X' 27

Dictionaries and default values with the get method If you use an index that does not exist in a dictionary, it will raise an exception (ERROR!) But, you can use the get( INDEX, DEFAULT) method to return a default value if the index does not exist. For example: arabic2roman.get(1, None ) produces 'I' arabic2roman.get(5, None ) produces 'V' arabic2roman.get(500, None ) produces 'None' arabic2roman.get( test, None ) produces 'None' 28

Difference Between Aliases & Clones More than one variable can point to the same data. This is called an Alias (or a reference). For example: a = [ 5, 10, 50, 100] b = a # b = a[:] Now, a and b both point to the same list. If you make a change to the data that a points to, you are also changing the data that b points to: a[0] = 'Changed' a points to the list: [ Changed, 10, 50, 100] But because b points to the same data, b also points to the list ['Changed', 10, 50, 100] 29

Cloning Data with the Slice operator If you want to make a clone (copy) of a sequence, you can use the slice operator ( [:] ) For example: a = [ 5, 10, 50, 100] b = a[0:2] Now, b points to a cloned slice of a that is [ 5, 10] If you make a change to the data that a points to, you do NOT change the slice that b points to. a[0] = 'Changed' a points to the list: [ Changed, 10, 50, 100] b still points to the (different) list [5, 10] 30

Cloning an entire list You can use the slice operator with a default START and END to clone an entire list (make a copy of it) For example: a = [ 5, 10, 50, 100] b = a[: ] Now, a and b point to different copies of the list with the same data values. If you make a change to the data that a points to, nothing happens the the list that b points to. a[0] = 'Changed' a points to the list: [ Changed, 10, 50, 100] b points to the the copy of the old a: [ 5, 10, 50, 100] 31

Be very careful! The only difference in the above examples was the use of the slice operator in addition to the assignment operator: b = a vs b = a[:] This is a small difference in syntax, but it has a very big semantic meaning! Without the slice operator, a and b point to the same list. Changes to one affect the other. With it, they point to different copies of the list that can be changed independently. 32

Objects, names and references A variable is a name referencing an object An object may have several names referencing it Important when modifying objects in-place! You may have to make proper copies to get the effect you want For immutable objects (numbers, strings), this is never a problem >>> a = [1, 3, 2] >>> b = a >>> c = b[0:2] >>> d = b[:] a b [1, 3, 2] >>> b.sort() >>># 'a' is affected! >>> a [1, 2, 3] c d [1, 3] [1, 3, 2] Jay Summet 2005-12-31 IPRE