It is time to go find some Data to mess with!
|
|
- Diane Blake
- 5 years ago
- Views:
Transcription
1 Files & Lists 4
2 Software What Next? It is time to go find some Data to mess with! Input and Output Devices Central Processing Unit if x < 3: print Secondary Memory Files R Us Main Memory From stephen.marquard@uct.ac.za Sat Jan 5 09:14: Return-Path: <postmaster@collab.sakaiproject.org> Date: Sat, 5 Jan :12: To: source@collab.sakaiproject. orgfrom: stephen.marquard@uct.ac.zasubject: [sakai] svn commit: r content/branches/details: org/viewsvn/?view=rev&rev=
3 File Processing A text file can be thought of as a sequence of lines From stephen.marquard@uct.ac.za Sat Jan 5 09:14: Return-Path: <postmaster@collab.sakaiproject.org> Date: Sat, 5 Jan :12: To: source@collab.sakaiproject.org From: stephen.marquard@uct.ac.za Subject: [sakai] svn commit: r content/branches/ Details: A file on the Web: 6
4 Opening a File Before we can read the contents of the file, we must tell Python which file we are going to work with and what we will be doing with the file This is done with the open() function open() returns a file handle - a variable used to perform operations on the file Similar to File -> Open in a Word Processor 7
5 Using open() handle = open(filename, mode) fhand = open('mbox.txt', 'r') > returns a handle use to manipulate the file > filename is a string > mode is optional and should be 'r' if we are planning to read the file and 'w' if we are going to write to the file 8
6 What is a Handle? >>> fhand = open('mbox.txt') >>> print fhand <open file 'mbox.txt', mode 'r' at 0x b0> 9
7 When Files are Missing >>> fhand = open('stuff.txt') Traceback (most recent call last): File "<stdin>", line 1, in <module>ioerror: [Errno 2] No such file or directory: 'stuff.txt' 10
8 But What if It Is Opened for Writing? >>> open( non-existent.txt, w ) No problem! 11
9 Remember? The newline Character We use a special character called the newline to indicate when a line ends We represent it as \n in strings Newline is still one character - not two >>> stuff = 'Hello\nWorld!' >>> stuff 'Hello\nWorld!' >>> print stuff Hello World! >>> stuff = 'X\nY' >>> print stuff X Y >>> len(stuff) 3 12
10 File Processing A text file can be thought of as a sequence of lines From stephen.marquard@uct.ac.za Sat Jan 5 09:14: Return-Path: <postmaster@collab.sakaiproject.org> Date: Sat, 5 Jan :12: To: source@collab.sakaiproject.org From: stephen.marquard@uct.ac.za Subject: [sakai] svn commit: r content/branches/ Details: 13
11 File Processing A text file has newlines at the end of each line From stephen.marquard@uct.ac.za Sat Jan 5 09:14: \n Return-Path: <postmaster@collab.sakaiproject.org>\n Date: Sat, 5 Jan :12: \n To: source@collab.sakaiproject.org\n From: stephen.marquard@uct.ac.za\n Subject: [sakai] svn commit: r content/branches/\n \n Details: 14
12 File Handle as a Sequence A file handle open for read can be treated as a sequence of strings where each line in the file is a string in the sequence We can use the for statement to iterate through a sequence xfile = open('mbox.txt') for cheese in xfile: print cheese Remember - a sequence is an ordered set 15
13 Counting Lines in a File Open a file read-only Use a for loop to read each line Count the lines and print out the number of lines fhand = open('mbox.txt') count = 0 for line in fhand: count = count + 1 print 'Line Count:', count $ python open.py Line Count:
14 We Can Convert the Contents of a File Into a String Reading the *Whole* File We can read the whole file (newlines and all) into a single string >>> fhand = open('mbox-short.txt') >>> inp = fhand.read() >>> print len(inp) >>> print inp[:20] From stephen.marquar 17
15 Searching Through a File We can put an if statement in our for loop to only print lines that meet some criteria fhand = open('mbox-short.txt') for line in fhand: if line.startswith('from:') : print line 18
16 OOPS! What are all these blank lines doing here? From: From: From: From: 19
17 Remember: Each Line Ends with a Newline (\n) OOPS! What are all these blank lines doing here? Each line from the file has a newline at the end The print statement adds a newline to each line From: stephen.marquard@uct.ac.za\n \n From: louis@media.berkeley.edu\n \n From: zqian@umich.edu\n \n From: rjlowe@iupui.edu\n \n... 20
18 Searching Through a File (fixed) We can strip the whitespace from the right-hand side of the string using rstrip() from the string library The newline is considered white space and is stripped fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if line.startswith('from:') : print line From: stephen.marquard@uct.ac.za From: louis@media.berkeley.edu From: zqian@umich.edu From: rjlowe@iupui.edu... 21
19 Using in to select lines We can look for a string anywhere in a line as our selection criteria fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if not '@uct.ac.za' in line : continue print line From stephen.marquard@uct.ac.za Sat Jan 5 09:14: X-Authentication-Warning: set sender to stephen.marquard@uct.ac.za using f From: stephen.marquard@uct.ac.za Author: stephen.marquard@uct.ac.za From david.horwitz@uct.ac.za Fri Jan 4 07:02: X-Authentication-Warning: set sender to david.horwitz@uct.ac.za using -f... Why Is That Code a Bit Wasteful? 22
20 fname = raw_input('enter the file name: ') fhand = open(fname) count = 0 for line in fhand: if line.startswith('subject:') : count = count + 1 print 'There were', count, 'subject lines in', fname Prompt for File Name Enter the file name: mbox.txt There were 1797 subject lines in mbox.txt Enter the file name: mbox-short.txt There were 27 subject lines in mbox-short. txt What Would We Do to Protect Our Code from a Bad Filename? 23
21 Bad File Names fname = raw_input('enter the file name: ') try: fhand = open(fname) except: print 'File cannot be opened:', fname exit() count = 0 for line in fhand: if line.startswith('subject:') : count = count + 1 print 'There were', count, 'subject lines in', fname Enter the file name: mbox.txt There were 1797 subject lines in mbox.txt Enter the file name: na na boo boo File cannot be opened: na na boo boo 24
22 Lists: A Refresher & More A list allows us to put multiple values in a single variable A list is convenient, because it can store multiple values in a single package We ve seen and used lists: friends = ['Joseph', 'Glenn', 'Sally'] clothes = ['sock', 'shirt', 'pants'] 25
23 List Constants List constants are surrounded by square brackets and the elements in the list are separated by commas A list element can be any Python object - even another list A list can be empty >>> print [1, 24, 76] [1, 24, 76] >>> print ['red', 'yellow', 'blue'] ['red', 'yellow', 'blue'] >>> print ['red', 24, 98.6] ['red', 24, ] >>> print [ 1, [5, 6], 7] [1, [5, 6], 7] >>> print [] [] 26
24 We already use lists! for i in [5, 4, 3, 2, 1] : print i print 'Blastoff!' Blastoff! 27
25 Lists and definite loops - best pals friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends : print 'Happy New Year:', friend print 'Done!' Happy New Year: Joseph Happy New Year: Glenn Happy New Year: Sally Done! 28
26 Looking Inside Lists Just like strings, we can get at any single element in a list using an index specified in square brackets Joseph 0 Glenn 1 Sally 2 >>> friends = [ 'Joseph', 'Glenn', 'Sally' ] >>> print friends[1] Glenn >>> 29
27 Lists are Mutable Strings are immutable - we cannot change the contents of a string - we must make a new string to make any change Lists are mutable - we can change an element of a list using the index operator >>> fruit = 'Banana' >>> fruit[0] = 'b' Traceback TypeError: 'str' object does not support item assignment >>> x = fruit.lower() >>> print x banana >>> lotto = [2, 14, 26, 41, 63] >>> print lotto [2, 14, 26, 41, 63] >>> lotto[2] = 28 >>> print lotto [2, 14, 28, 41, 63] 30
28 How Long is a List? The len() function takes a list as a parameter and returns the number of elements in the list Actually len() tells us the number of elements of any set or sequence (such as a string...) >>> greet = 'Hello Bob' >>> print len(greet) 9 >>> x = [ 1, 2, 'joe', 99] >>> print len(x) 4 >>> 31
29 Using the range function The range function returns a list of numbers that range from zero to one less than the parameter We can construct an index loop using for and an integer iterator >>> print range(4) [0, 1, 2, 3] >>> friends = ['Joseph', 'Glenn', 'Sally'] >>> print len(friends) 3 >>> print range(len(friends)) [0, 1, 2] >>> 32
30 These Two Loops Do the Same Thing A tale of two loops... friends = ['Joseph', 'Glenn', 'Sally'] for friend in friends : print 'Happy New Year:', friend for i in range(len(friends)) : friend = friends[i] print 'Happy New Year:', friend >>> friends = ['Joseph', 'Glenn', 'Sally'] >>> print len(friends) 3 >>> print range(len(friends)) [0, 1, 2] >>> Happy New Year: Joseph Happy New Year: Glenn Happy New Year: Sally 33
31 Just Like With Strings! Concatenating lists using + We can create a new list by adding two existing lists together >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> print c [1, 2, 3, 4, 5, 6] >>> print a [1, 2, 3] 34
32 Just Like With Strings! Lists can be sliced using : >>> t = [9, 41, 12, 3, 74, 15] >>> t[1:3] [41,12] >>> t[:4] [9, 41, 12, 3] >>> t[3:] [3, 74, 15] >>> t[:] [9, 41, 12, 3, 74, 15] Remember: Just like in strings, the second number is up to but not including 35
33 List Methods >>> x = list() >>> type(x) <type 'list'> >>> dir(x) ['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> 36
34 37
35 Building a List from Scratch We can create an empty list and then add elements using the append method The list stays in order and new elements are added at the end of the list >>> stuff = list() >>> stuff.append('book') >>> stuff.append(99) >>> print stuff ['book', 99] >>> stuff.append('cookie') >>> print stuff ['book', 99, 'cookie'] 38
36 Is Something in a List? Python provides two operators that let you check if an item is in a list These are logical operators that return True or False They do not modify the list >>> some = [1, 9, 21, 10, 16] >>> 9 in some True >>> 15 in some False >>> 20 not in some True >>> 39
37 A List is an Ordered Sequence A list can hold many items and keeps those items in the order until we do something to change the order A list can be sorted (i.e., change its order) >>> friends = [ 'Joseph', 'Glenn', 'Sally' ] >>> friends.sort() >>> print friends ['Glenn', 'Joseph', 'Sally'] >>> print friends[1] Joseph >>> The sort method (unlike in strings) means sort yourself 40
38 Built-in Functions and Lists There are a number of functions built into Python that take lists as parameters Remember the loops we built? These are much simpler. >>> nums = [3, 41, 12, 9, 74, 15] >>> print len(nums) 6 >>> print max(nums) 74 >>> print min(nums) 3 >>> print sum(nums) 154 >>> print sum(nums)/len(nums) 25 41
39 total = 0 count = 0 while True : inp = raw_input('enter a number: ') if inp == 'done' : break value = float(inp) total = total + value count = count + 1 average = total / count print 'Average:', average Enter a number: 3 Enter a number: 9 Enter a number: 5 Enter a number: done Average: numlist = list() while True : inp = raw_input('enter a number: ') if inp == 'done' : break value = float(inp) numlist.append(value) average = sum(numlist) / len(numlist) print 'Average:', average 42
40 Best Friends: Strings and Lists >>> abc = 'With three words' >>> stuff = abc.split() >>> print stuff ['With', 'three', 'words'] >>> print len(stuff) 3 >>> print stuff[0] With >>> print stuff ['With', 'three', 'words'] >>> for w in stuff :... print w... With Three Words >>> Split breaks a string into parts and produces a list of strings. We think of these as words. We can access a particular word or loop through all the words. The Default Argument for split is <space>. See Examples 43
41 >>> line = 'A lot of spaces' >>> etc = line.split() >>> print etc ['A', 'lot', 'of', 'spaces'] >>> >>> line = 'first;second;third' >>> thing = line.split() >>> print thing ['first;second;third'] >>> print len(thing) 1 >>> thing = line.split(';') >>> print thing ['first', 'second', 'third'] >>> print len(thing) 3 >>> When you do not specify a delimiter, multiple spaces are treated like one delimiter You can specify what delimiter character to use in the splitting 44
42 From Sat Jan 5 09:14: fhand = open('mbox-short.txt') for line in fhand: line = line.rstrip() if not line.startswith('from ') : continue words = line.split() print words[2] Sat Fri Fri Fri... >>> line = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14: >>> words = line.split() >>> print words ['From', 'stephen.marquard@uct.ac.za', 'Sat', 'Jan', '5', '09:14:16', '2008'] >>> 45
43 The Double Split Pattern Sometimes we split a line one way, and then grab one of the pieces of the line and split that piece again From stephen.marquard@uct.ac.za Sat Jan 5 09:14: words = line.split() = words[1] print pieces[1] ['stephen.marquard', 'uct.ac.za'] 46
44 The Double Split Pattern Sometimes we split a line one way, and then grab one of the pieces of the line and split that piece again From stephen.marquard@uct.ac.za Sat Jan 5 09:14: words = line.split() = words[1] print pieces[1] stephen.marquard@uct.ac.za 47
45 The Double Split Pattern Sometimes we split a line one way, and then grab one of the pieces of the line and split that piece again From stephen.marquard@uct.ac.za Sat Jan 5 09:14: words = line.split() = words[1] pieces = .split('@') print pieces[1] stephen.marquard@uct.ac.za ['stephen.marquard', 'uct.ac.za'] 48
46 The Double Split Pattern Sometimes we split a line one way, and then grab one of the pieces of the line and split that piece again From stephen.marquard@uct.ac.za Sat Jan 5 09:14: words = line.split() = words[1] pieces = .split('@') print pieces[1] print pieces[1] stephen.marquard@uct.ac.za ['stephen.marquard', 'uct.ac.za'] 'uct.ac.za' 49
Reading Files. Chapter 7. Python for Informatics: Exploring Information
Reading Files Chapter 7 Python for Informatics: Exploring Information www.pythonlearn.com Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0
More informationReading Files. Chapter 7. Python for Everybody
Reading Files Chapter 7 Python for Everybody www.py4e.com Software What Next? It is time to go find some Data to mess with! Input and Output Devices Central Processing Unit if x < 3: print Secondary Memory
More informationPython Lists. What is not a Collection. A List is a kind of Collection. friends = [ 'Joseph', 'Glenn', 'Sally' ]
Python Lists Chapter 8 Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution.0 License. http://creativecommons.org/licenses/by/.0/. Copyright 2010,
More informationSpring INF Principles of Programming for Informatics. Manipulating Lists
Manipulating Lists Copyright 2017, Pedro C. Diniz, all rights reserved. Students enrolled in the INF 510 class at the University of Southern California (USC) have explicit permission to make copies of
More informationPython for Informatics
Python for Informatics Exploring Information Version 0.0.6 Charles Severance Chapter 6 Strings 6.1 A string is a sequence A string is a sequence of characters. You can access the characters one at a time
More informationSpring INF Principles of Programming for Informatics. Manipulating Files
Manipulating Files Copyright 2017, Pedro C. Diniz, all rights reserved. Students enrolled in the INF 510 class at the University of Southern California (USC) have explicit permission to make copies of
More informationPython for Informatics
Python for Informatics Exploring Information Version 2.7.2 Charles Severance Chapter 8 Lists 8.1 A list is a sequence Like a string, a list is a sequence of values. In a string, the values are characters;
More informationPython for Everybody. Exploring Data Using Python 3. Charles R. Severance
Python for Everybody Exploring Data Using Python 3 Charles R. Severance 8.14. DEBUGGING 103 In this example you could also use the built-in function sorted, which returns a new, sorted list and leaves
More informationDictionaries, Text, Tuples
Dictionaries, Text, Tuples 4 We re Familiar with Lists [2, 3, 51, 0] [[ a, 151], [ z, 23], [ i, -42.3]] [2, BBC, KCRW, [ z, 23]] Lists enable us to store multiple values in one variable Lists are ordered,
More informationStrings. Chapter 6. Python for Everybody
Strings Chapter 6 Python for Everybody www.py4e.com String Data Type A string is a sequence of characters A string literal uses quotes 'Hello' or "Hello" For strings, + means concatenate When a string
More informationCSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray
CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray 01-c: Python review 2 python review: lists strings 3 Strings lists names = "John, Paul, Megan, Bill, Mary" names
More informationCMSC201 Computer Science I for Majors
CMSC201 Computer Science I for Majors Lecture 09 Strings Last Class We Covered Lists and what they are used for Getting the length of a list Operations like append() and remove() Iterating over a list
More informationTopic 7: Lists, Dictionaries and Strings
Topic 7: Lists, Dictionaries and Strings The human animal differs from the lesser primates in his passion for lists of Ten Best H. Allen Smith 1 Textbook Strongly Recommended Exercises The Python Workbook:
More informationCMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries
CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries Assignment: Lab 12 Tuples and Dictionaries Due Date: During discussion, November 30 th through December 3 rd Value: 1% of final grade Part 1: Data Types
More informationData Structures. Lists, Tuples, Sets, Dictionaries
Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,
More informationSequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python
Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted
More informationCollections. Lists, Tuples, Sets, Dictionaries
Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again
More informationUNIVERSITÀ DI PADOVA. < 2014 March >
UNIVERSITÀ DI PADOVA < 2014 March > Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. Easy-to-read: Python code is much more clearly defined and visible
More informationPython workshop. Week 4: Files and lists.
Python workshop Week 4: Files and lists barbera@van-schaik.org Overview of this workshop series Week 1: Writing your first program Week 2: Make choices and reuse code Week 3: Loops and strings Week 4:
More informationIntroduction to Python
Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions
More informationIntroduction to Python Code Quality
Introduction to Python Code Quality Clarity and readability are important (easter egg: type import this at the Python prompt), as well as extensibility, meaning code that can be easily enhanced and extended.
More informationThe Big Python Guide
The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String
More information1 Strings (Review) CS151: Problem Solving and Programming
1 Strings (Review) Strings are a collection of characters. quotes. this is a string "this is also a string" In python, strings can be delineated by either single or double If you use one type of quote
More informationPython for Non-programmers
Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013
More informationFile Processing. CS 112: Introduction to Programming: File Processing Sequence. File Processing. File IO
File Processing CS 112: Introduction to Programming: File IO Coming up: File Processing 1 File Processing Sequence 1. Open the file 2. Read from the file 3. Close the file In some cases, not properly closing
More informationCPSC 217-T03/T08. Functions Ruting Zhou
CPSC 217-T03/T08 Functions Ruting Zhou STORED (AND REUSED) STEPS def hello(): Program: print 'Hello' hello() print Zip print 'Fun' def hello(): print('hello ) print('fun ) hello() Print( 'Zip'hello())
More informationCMSC201 Computer Science I for Majors
CMSC201 Computer Science I for Majors Lecture 09 Strings Last Class We Covered Lists and what they are used for Getting the length of a list Operations like append() and remove() Iterating over a list
More informationAccelerating Information Technology Innovation
Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 1 Introduction to Python Agenda What is Python? and Why Python? Basic Syntax Strings User Input Useful
More informationCMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi All of the variables that we have used have held a single item One integer, floating point value, or string often you find that you want
More informationProgramming Fundamentals and Python
Chapter 2 Programming Fundamentals and Python This chapter provides a non-technical overview of Python and will cover the basic programming knowledge needed for the rest of the chapters in Part 1. It contains
More informationCSc 120. Introduc/on to Computer Programing II. 01- b: Python review. Adapted from slides by Dr. Saumya Debray
CSc 120 Introduc/on to Computer Programing II Adapted from slides by Dr. Saumya Debray 01- b: Python review Lists of Lists x = [ [1,2,3], [4], [5, 6]] x [[1, 2, 3], [4], [5, 6]] y = [ ['aa', 'bb', 'cc'],
More information18.1. CS 102 Unit 18. Python. Mark Redekopp
18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two
More informationStored (and reused) Steps
Python - Functions Stored (and reused) Steps def hello(): Program: hello() print Zip print 'Hello' print 'Fun' def hello(): print 'Hello print 'Fun hello() print 'Zip hello() Output: Hello Fun Zip Hello
More informationPython Review IPRE
Python Review 2 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
More informationCS2304: Python for Java Programmers. CS2304: Sequences and Collections
CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for
More informationAccelerating Information Technology Innovation
Accelerating Information Technology Innovation http://aiti.mit.edu/program/philippines-summer-2012/ Philippines Summer 2012 Lecture 1 Introduction to Python June 19, 2012 Agenda About the Course What is
More informationCMSC 201 Spring 2016 Lab 08 Strings and File I/O
CMSC 201 Spring 2016 Lab 08 Strings and File I/O Assignment: Lab 08 Strings and File I/O Due Date: During discussion, April 4 th through April 7 th Value: 10 points Part 1: File Input Using files as input
More informationAt full speed with Python
At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3
More informationLists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10
Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Administrative Homework #5 is due today Homework #6 is out and DUE on MONDAY (3/5)
More informationSlicing. Open pizza_slicer.py
Slicing and Tuples Slicing Open pizza_slicer.py Indexing a string is a great way of getting to a single value in a string However, what if you want to use a section of a string Like the middle name of
More information(Refer Slide Time: 01:12)
Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #22 PERL Part II We continue with our discussion on the Perl
More informationThe Practice of Computing Using PYTHON
The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures 2 Data Structures
More informationChapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationPython Intro GIS Week 1. Jake K. Carr
GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes
More informationPython Review IPRE
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
More informationCMSC201 Computer Science I for Majors
CMSC201 Computer Science I for Majors Lecture 16 File I/O All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted Last Class We Covered Using for loops Syntax Using it to iterate over
More informationChapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments
Chapter 6: List What we will learn: List definition Syntax for creating lists Selecting elements of a list Selecting subsequence of a list What you need to know before: Data types Assignments List Sub-list
More informationPython I. Some material adapted from Upenn cmpe391 slides and other sources
Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics
More informationAll programs can be represented in terms of sequence, selection and iteration.
Python Lesson 3 Lists, for loops and while loops Suffolk One, Ipswich, 4:30 to 6:00 Tuesday Jan 28 Nicky Hughes All programs can be represented in terms of sequence, selection and iteration. 1 Computational
More informationChapter 10: Creating and Modifying Text Lists Modules
Chapter 10: Creating and Modifying Text Lists Modules Text Text is manipulated as strings A string is a sequence of characters, stored in memory as an array H e l l o 0 1 2 3 4 Strings Strings are defined
More informationInteractive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D
1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.
More informationInteractive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D
1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.
More informationPython - 2. Jim Eng
Python - 2 Jim Eng jimeng@umich.edu Lists Dictionaries Try... except Methods and Functions Classes and Objects Midterm Review Overview Patterns in programming - 1 Sequential steps Conditional steps Repeated
More informationMULTIPLE CHOICE. Chapter Seven
Chapter Seven MULTIPLE CHOICE 1. Which of these is associated with a specific file and provides a way for the program to work with that file? a. Filename b. Extension c. File object d. File variable 2.
More informationPython for Non-programmers
Python for Non-programmers A Gentle Introduction 2 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013
More informationCPD for GCSE Computing: Practical Sheet 6 February 14
Aims Programming Sheet 6 Arrays in Python Section Aim 1 Arrays A variable with many values Understand the idea of an array as a way to combine many values that are assigned to as single variable. 2 While
More informationPython Programming: An Introduction to Computer Science
Python Programming: An Introduction to Computer Science Chapter 4 (End of Chapter) File IO Coming up: File Processing 1 File Processing! The process of opening a file involves associating a file on disk
More informationCSC326 Python Sequences i. CSC326 Python Sequences
i CSC326 Python Sequences ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME 1.0 2011-09 JZ iii Contents 1 Agenda 1 2 while Statement 1 3 Sequence Overview 2 4 String 2 5 Lists 4 6 Dictionary 5 7 Tuples
More informationCS Summer 2013
CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or
More informationUnit 2. Srinidhi H Asst Professor
Unit 2 Srinidhi H Asst Professor 1 Iterations 2 Python for Loop Statements for iterating_var in sequence: statements(s) 3 Python for While Statements while «expression»: «block» 4 The Collatz 3n + 1 sequence
More informationCS 11 python track: lecture 3. n Today: Useful coding idioms
CS 11 python track: lecture 3 Today: Useful coding idioms Useful coding idioms "Idiom" Standard ways of accomplishing a common task Using standard idioms won't make your code more correct, but more concise
More informationDM550/DM857 Introduction to Programming. Peter Schneider-Kamp
DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ TUPLES 2 Tuples as Immutable Sequences tuple =
More informationLists, loops and decisions
Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence
More informationProgramming in Python
3. Sequences: Strings, Tuples, Lists 15.10.2009 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python
More informationCompound Data Types 1
Compound Data Types 1 Chapters 8, 10 Prof. Mauro Gaspari: mauro.gaspari@unibo.it Compound Data Types Strings are compound data types: they are sequences of characters. Int and float are scalar data types:
More informationUniversity of Texas at Arlington, TX, USA
Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA Part of the science in computer science is the design and use of data structures and algorithms. As you go on in CS,
More informationIntro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming
Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals
More informationCS 115 Lecture 13. Strings. Neil Moore. Department of Computer Science University of Kentucky Lexington, Kentucky
CS 115 Lecture 13 Strings Neil Moore Department of Computer Science University of Kentucky Lexington, Kentucky 40506 neil@cs.uky.edu 29 October 2015 Strings We ve been using strings for a while. What can
More informationStrings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break
Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break Strings Upsorn Praphamontripong CS 1111 Introduction to Programming Spring 2018 Strings Sequence of characters
More informationIntroduction to String Manipulation
Introduction to Computer Programming Introduction to String Manipulation CSCI-UA.0002 What is a String? A String is a data type in the Python programming language A String can be described as a "sequence
More informationIn addition to numbers and strings, Python also lets us represent lists of things (just like in AppInventor).
Python Part 2 h Lists In addition to numbers and strings, Python also lets us represent lists of things (just like in AppInventor). Syntax of lists: the listed is delimited by square brackets: [ ] list
More informationIndian Institute of Technology Kharagpur. PERL Part III. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T.
Indian Institute of Technology Kharagpur PERL Part III Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T. Kharagpur, INDIA Lecture 23: PERL Part III On completion, the student will be able
More informationCMSC201 Computer Science I for Majors
CMSC201 Computer Science I for Majors Lecture 16 File I/O (continued) All materials copyright UMBC unless otherwise noted Last Class We Covered Escape sequences Uses a backslash (\) File I/O Input/Output
More informationSequence of Characters. Non-printing Characters. And Then There Is """ """ Subset of UTF-8. String Representation 6/5/2018.
Chapter 4 Working with Strings Sequence of Characters we've talked about strings being a sequence of characters. a string is indicated between ' ' or " " the exact sequence of characters is maintained
More informationPart III Appendices 165
Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.
More information\n is used in a string to indicate the newline character. An expression produces data. The simplest expression
Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of
More informationLoops and Iteration. Chapter 5. Python for Informatics: Exploring Information
Loops and Iteration Chapter 5 Python for Informatics: Exploring Information www.pythonlearn.com Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution
More informationWhat we already know. more of what we know. results, searching for "This" 6/21/2017. chapter 14
What we already know chapter 14 Files and Exceptions II Files are bytes on disk. Two types, text and binary (we are working with text) open creates a connection between the disk contents and the program
More informationConverting File Input
Converting File Input As with the input func.on, the readline() method can only return strings If the file contains numerical data, the strings must be converted to the numerical value using the int()
More informationDecision Structures Zelle - Chapter 7
Decision Structures Zelle - Chapter 7 Charles Severance - www.dr-chuck.com Textbook: Python Programming: An Introduction to Computer Science, John Zelle x = 5 print "Before 5 if ( x == 5 ) : print "Is
More informationCMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi
CMPT 120 Basics of Python Summer 2012 Instructor: Hassan Khosravi Python A simple programming language to implement your ideas Design philosophy emphasizes code readability Implementation of Python was
More informationUNIT 5. String Functions and Random Numbers
UNIT 5 String Functions and Random Numbers DAY 1 String data type String storage in data String indexing I can.. Explain the purpose of the string variable type and how it is stored in memory. Explain
More informationMITOCW watch?v=rvrkt-jxvko
MITOCW watch?v=rvrkt-jxvko The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To
More informationWorking with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.
Working with Strings Husni "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc. Sequence of characters We've talked about strings being a sequence of characters.
More informationWorksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords
Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long
More informationNotebook. March 30, 2019
Notebook March 30, 2019 1 Complex Data Types Some kinds of data can store other kinds of data. 1.1 Lists We ve actually seen the most common complex data type a few times before, I just haven t pointed
More informationPart I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming
2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float
More informationPython Working with files. May 4, 2017
Python Working with files May 4, 2017 So far, everything we have done in Python was using in-memory operations. After closing the Python interpreter or after the script was done, all our input and output
More informationModule 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists
Module 04: Lists Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10 1 Consider the string method split >>> name = "Harry James Potter" >>> name.split() ['Harry',
More informationCS 1110: Introduction to Computing Using Python Lists and Sequences
CS : Introduction to Computing Using Python Lecture Lists and Sequences [Andersen, Gries, Lee, Marschner, Van Loan, White] Prelim Lecture Announcements Date: Tuesday, March 4th, 7:3 pm to 9: pm Submit
More information2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1
2.1 Indefinite Loops The final kind of control flow is Python s indefinite loop, the while loop. It functions much like the for loop in that it repeatedly executes some body of statements. The difference
More informationIntroduction to Python
Introduction to Python Development Environments what IDE to use? 1. PyDev with Eclipse 2. Sublime Text Editor 3. Emacs 4. Vim 5. Atom 6. Gedit 7. Idle 8. PIDA (Linux)(VIM Based) 9. NotePad++ (Windows)
More informationAPPM 2460 Matlab Basics
APPM 2460 Matlab Basics 1 Introduction In this lab we ll get acquainted with the basics of Matlab. This will be review if you ve done any sort of programming before; the goal here is to get everyone on
More informationPython - Loops and Iteration
Python - Loops and Iteration n = 5 Repeated Steps No n > 0? Yes Program: Output: print 'Blastoff' print n n = n -1 n = 5 while n > 0 : print n n = n 1 print 'Blastoff!' print n 5 4 3 2 1 Blastoff! Loops
More informationGenome 373: Intro to Python II. Doug Fowler
Genome 373: Intro to Python II Doug Fowler Review string objects represent a sequence of characters characters in strings can be gotten by index, e.g. mystr[3] substrings can be extracted by slicing, e.g.
More informationLists How lists are like strings
Lists How lists are like strings A Python list is a new type. Lists allow many of the same operations as strings. (See the table in Section 4.6 of the Python Standard Library Reference for operations supported
More informationIntroduction to Computer Programming for Non-Majors
Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 11 Part 1 Instructor: Long Ma The Department of Computer Science Chapter 11 Data Collections Objectives: To understand the
More informationSome material adapted from Upenn cmpe391 slides and other sources
Some material adapted from Upenn cmpe391 slides and other sources History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics
More informationSequence Types FEB
Sequence Types FEB 23-25 2015 What we have not learned so far How to store, organize, and access large amounts of data? Examples: Read a sequence of million numbers and output these in sorted order. Read
More informationCIS192 Python Programming
CIS192 Python Programming Data Types Joseph Cappadona University of Pennsylvania September 03, 2015 Joseph Cappadona (University of Pennsylvania) CIS 192 September 03, 2015 1 / 32 Outline 1 Data Types
More information