Guide to Programming with Python

Slides:



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

Container Types in Python
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
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.
Guide to Programming with Python
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
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.
Lists Introduction to Computing Science and Programming I.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
COMPUTER SCIENCE FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
Lists in Python.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
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.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
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.
Built-in Data Structures in Python An Introduction.
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Lecture 19 - More on Lists, Slicing Lists, List Functions COMPSCI 101 Principles of Programming.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 8: Fun with strings.
More about Strings. String Formatting  So far we have used comma separators to print messages  This is fine until our messages become quite complex:
Introduction to Strings Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg 1.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
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.
Python Strings. String  A String is a sequence of characters  Access characters one at a time with a bracket operator and an offset index >>> fruit.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 3: Built-in functions.
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.
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game.
Unit 4 – Chapter 4 Strings and Tuples. len() Function You can pass any sequence you want to the len() function and it will return the length of the sequence.
Section06: Sequences Chapter 4 and 5. General Description "Normal" variables x = 19 – The name "x" is associated with a single value Sequence variables:
String and Lists Dr. José M. Reyes Álamo.
Generating Random Numbers
Tuples and Lists.
Python - Lists.
Chapter 4 Strings & Tuples
CS 115 Lecture 8 Structured Programming; for loops
Strings Part 1 Taken from notes by Dr. Neil Moore
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Lists in Python.
Bryan Burlingame Halloween 2018
CHAPTER THREE Sequences.
Guide to Programming with Python
Data types Numeric types Sequence types float int bool list str
CEV208 Computer Programming
String and Lists Dr. José M. Reyes Álamo.
Ruth Anderson UW CSE 160 Winter 2017
Topics Sequences Introduction to Lists List Slicing
15-110: Principles of Computing
For loops Taken from notes by Dr. Neil Moore
Topics Basic String Operations String Slicing
CHAPTER 4: Lists, Tuples and Dictionaries
Bryan Burlingame Halloween 2018
Topics Sequences Introduction to Lists List Slicing
Python Review
Ruth Anderson UW CSE 160 Spring 2018
Topics Basic String Operations String Slicing
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Basic String Operations String Slicing
Tuple.
Introduction to Computer Science
Presentation transcript:

Guide to Programming with Python Chapter Four for Loops, Strings, and Tuples: The Word Jumble Game

Objectives Construct for loops to move through a sequence Use the range() function to create a sequence of integers Treat strings as sequences Use tuples to harness the power of sequences Use sequence functions and operators Index and slice sequences Guide to Programming with Python

The Word Jumble Game Figure 4.1: Sample run of the Word Jumble game This jumble looks “difficult.” Guide to Programming with Python

Using for Loops Like while loop, repeats a loop body Unlike while loop, doesn’t repeat based on condition Repeats loop body for each element in a sequence Ends when it reaches end of the sequence e.g., go through sequence of game titles and print each Guide to Programming with Python

The Loopy String Program Figure 4.2: Sample run of the Loopy String program A for loop goes through a word, one character at a time. Guide to Programming with Python

Understanding for Loops Sequence: An ordered list of elements Element: A single item in a sequence Iterate: To move through a sequence, in order List of your top-ten movies A sequence Each element is a movie title To iterate over would be to go through each title, in order Guide to Programming with Python

Understanding for Loops (continued) for loop iterates over a sequence; performs loop body for each element During each iteration, loop variable gets next element In loop body, something usually done with loop variable Guide to Programming with Python

Understanding for Loops (continued) for letter in word: print letter A string is a sequence of characters So loop iterates over letters in string word Loop body simply prints each element (character) Guide to Programming with Python

Counting with a for Loop Can use for loop to count Can use in combination with range() function Guide to Programming with Python

The Counter Program Figure 4.3: Sample run of the Counter program Using a for loop, counts forward, by fives, and backward. Guide to Programming with Python

The range() Function Returns a sequence of integers in range [0, 1, 2, 3, 4] >>> range(0, 50, 5) [0, 5, 10, 15, 20, 25, 30, 35, 40, 45] Returns a sequence of integers in range range(i) returns sequence 0 through i – 1 range(i, j) returns sequence i through j – 1 range(i, j, k) returns sequence i to j - 1, step k Guide to Programming with Python

Counting Forward, By Fives, and Backwards for i in range(10): print i, # counting by fives for i in range(0, 50, 5): # counting backwards for i in range(10, 0, -1): Guide to Programming with Python

Using Sequence Operators and Functions with Strings Python has functions and operators that work with sequences Can tell you things such as Length of sequence If contains specific element Guide to Programming with Python

The Message Analyzer Program Figure 4.4: Sample run of the Message Analyzer program len() function and in operator produce information about a message. Guide to Programming with Python

Using the len() function >>> len("Game Over!") 10 Takes a sequence Returns the number of elements In strings, every character counts – spaces and punctuation Guide to Programming with Python

Using the in Operator Tests for element membership >>> "e" in "Game Over" True Tests for element membership Returns True if element is in sequence Returns False otherwise Guide to Programming with Python

Indexing Strings Sequential access: Access in order Random access: Direct access to any element Indexing: Process used to access a specific element of a sequence Member: An element of a sequence Python allows for random access to sequences (such as strings) via indexing Guide to Programming with Python

The Random Access Program Figure 4.5: Sample run of the Random Access program You can directly access any character in a string through indexing. Guide to Programming with Python

Working with Positive Position Numbers >>> word = "index" >>> word[3] 'e' Use brackets and position number to index Indexing for positive position numbers starts at 0 Length of sequence minus one is last position Attempt to access beyond last position results in error Guide to Programming with Python

Working with Negative Position Numbers >>> word = "index" >>> word[-2] 'e' Can use negative position numbers Start at end of sequence with position number: –1 End at first element, with position number: negative sequence length Guide to Programming with Python

Positive and Negative Position Numbers Figure 4.6: Sequence Indexing Guide to Programming with Python

String Immutability Mutable: Changeable Immutable: Unchangeable >>> word = "game" >>> word[0] = "l" TypeError: object does not support item assignment Mutable: Changeable Immutable: Unchangeable Strings are immutable sequences; can’t be changed But can create new strings from existing ones (like through concatenation) Guide to Programming with Python

String Immutability (continued) Figure 4.7: Demonstration of string immutability Guide to Programming with Python

Building a New String Can't modify an existing string But can "build" (create) a new string with concatenation operator Guide to Programming with Python

The No Vowels Program Figure 4.8: Sample run of No Vowels program New strings are created through concatenation. Guide to Programming with Python

Constants Constant: Name associated with value not meant to be changed VOWELS = "aeiou" Constant: Name associated with value not meant to be changed Convention is to use all uppercase variable names Can make programs clearer Saves retyping (and possibly errors from typos) No true constants in Python Guide to Programming with Python

Creating New Strings from Existing Ones new_message += letter Concatenation creates brand-new string Remember, strings are immutable So, new_message becomes the newly created string resulting from concatenation Guide to Programming with Python

Slicing Strings Slice: Copy of continuous section of a sequence Can make slices (copies) of continuous sections of sequence elements Can slice one element or multiple, continuous part of sequence Can even create a slice that is copy of entire sequence Guide to Programming with Python

The Pizza Slicer Program Figure 4.9: Sample run of the Pizza Slicer program Fresh, hot slices of "pizza", made just the way you asked. Guide to Programming with Python

None Representing nothing Makes a good placeholder for a value Evaluates to False when treated as a condition Guide to Programming with Python

Slicing Figure 4.10: Slicing end points An example of slicing end point numbers for the string "pizza". Guide to Programming with Python

Slicing (continued) Can give start and end position >>> word = "pizza" >>> print word[0:5] pizza >>> print word[1:3] iz >>> print word[-4:3] Can give start and end position Slice is a brand-new sequence Guide to Programming with Python

Slicing (continued) Can omit the beginning point >>> word = "pizza" >>> word[:4] 'pizz' >>> word[2:] 'zza' >>> word[:] 'pizza' Can omit the beginning point Can omit the ending point sequence[:] is copy of sequence Guide to Programming with Python

Creating Tuples Tuple: Immutable sequence of values of any type Could have tuple of integers for a high score list, for example Tuples elements don't need to all be of same type Guide to Programming with Python

The Hero’s Inventory Program Figure 4.11: Sample run of the Hero’s Inventory Program The hero’s inventory is represented by a tuple of strings. Guide to Programming with Python

Tuple Basics Creating an Empty Tuple Treating a Tuple as a Condition inventory = () Treating a Tuple as a Condition if not inventory: print "You are empty-handed." Creating a Tuple with Elements inventory = ("sword", "armor", "shield", "healing potion") Guide to Programming with Python

Tuple Basics (continued) Printing a tuple print "\nThe tuple inventory is:\n", inventory Looping through a tuple’s elements for item in inventory: print item Guide to Programming with Python

Using Tuples Tuples are a kind of sequence (like strings) so can: Get length with len() Iterate through elements with for loop Test for element membership with in Index, slice, and concatenate Guide to Programming with Python

The Hero’s Inventory 2.0 Figure 4.12: Sample run of the Hero’s Inventory program Demonstrates indexing, slicing, and concatenating tuples Guide to Programming with Python

Using len() and in with Tuples The len() function with tuples Just as with strings, returns number of elements print "You have", len(inventory), "items." The in operator with tuples Just as with strings, tests for element membership if "healing potion" in inventory: print "You will live to fight another day." Guide to Programming with Python

Indexing Tuples Figure 4.13: Each element has a corresponding position number. Each string is a single element in the tuple. Guide to Programming with Python

Slicing Tuples Figure 4.14: Slicing positions defined between elements Tuple slicing works much like string slicing. Guide to Programming with Python

Tuple Immutability Tuples are immutable >>> inventory = ("sword", "armor", "shield", "healing potion") >>> inventory[0] = "battleax" TypeError: object doesn't support item assignment Tuples are immutable But can create new tuples from existing ones Guide to Programming with Python

Concatenating Tuples >>> inventory = ("sword", "armor", "shield", "healing potion") >>> chest = ("gold", "gems") >>> inventory += chest >>> print inventory ('sword', 'armor', 'shield', 'healing potion', 'gold', 'gems') Concatenation operator, +, works with tuples just like with strings Guide to Programming with Python

Review word_jumble.py Guide to Programming with Python 45 45

Summary An ordered list of elements is called what? A sequence To move through a sequence, in order, is called what? Iterate When a for loop iterates over a sequence, how many times does it perform its loop body? As many times as there are elements in the sequence What would range(20,10,-2) return? [20, 18, 16, 14, 12] What would len(range(20,10,-2)) return? 5 Guide to Programming with Python

Summary (continued) If I use the in operator to test for element membership in a tuple, what does it return if the element is there? True What is the name of the technique used to access a specific element of a sequence? Indexing Match the following pairs of words: mutable unchangeable immutable changeable Strings are immutable sequences, true or false? Constants are values that are meant to change, true or false? False Guide to Programming with Python

Summary (continued) String concatenation adds onto an existing string, true or false? False, it creates brand-new strings What does None evaluate to when treated as a condition? False Slicing creates a copy of a discontinuous collection of elements from a sequence, true or false? False, it only copies a continuous segment of elements from a sequence A tuple is an immutable sequence of elements of what variable type? Any! The concatenation operator, +, works with tuples just like with strings, true or false? True Guide to Programming with Python