300 likes | 532 Vues
Guide to Programming with Python. Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game . Objectives. Data type: sequences (containers) Strings (a sequence of letters) Tuples (a sequence of elements of any type; immutable) Lists (a sequence of elements of any type; mutable)
E N D
Guide to Programming with Python Chapter Four Strings, and Tuples; for Loops: The Word Jumble Game
Objectives • Data type: sequences (containers) • Strings (a sequence of letters) • Tuples (a sequence of elements of any type; immutable) • Lists (a sequence of elements of any type; mutable) • Create sequences • Assignment statement s, t = "sword", ("sword", "armor”) • Use the range() function to create a sequence of integers • Use for loops to move through a sequence, in order • Index and slice sequences (any sequence) • Use sequence functions and operators Guide to Programming with Python
Understanding Sequence • Sequence: An ordered list of elements (compared to dictionary) • Element: A single item in a sequence • Iterate: To move through a sequence, in order (using for loops) • 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
Using for Loop to Iterate Over a Sequence • 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 • A string is a sequence of characters; So loop iterates over letters in the string (e.g., word below) • for letter in word: • print letter sequence loop variable Guide to Programming with Python
Combining for and range() for letter in word: print letter Can be transformed into: for idx in range(len(word)): letter = word[idx] print letter • Combine for loop with range() function, and len() function Guide to Programming with Python
The range() Function >>> range(5) [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 toj - 1, step k Guide to Programming with Python
Counting Forward, By Fives, and Backwards # counting forward for i in range(10): print i, # counting by fives for i in range(0, 50, 5): print i, # counting backwards for i in range(10, 0, -1): print i, Guide to Programming with Python
Comparing for and while Loops • for loop • Likewhile 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
Indexing Sequence • Sequential access: Access in order (see for loops) • Indexing: Process used to access a specific element of a sequence • Random access: Direct access to any element • Element/Member: An element of a sequence • Python allows for random access to sequences (such as strings) via indexing Guide to Programming with Python
Working with Positive and Negative Position Numbers • Use brackets and position number to index "index"[3] • Positive position numbers: starts at 0; ends with the length of a sequence - 1 • Negative position numbers: starts at the end of sequence with position number: –1 • Attempt to access beyond last position results in error Guide to Programming with Python
Slicing >>> word = "pizza" >>> print word[0:5] pizza >>> print word[1:3] iz >>> print word[-4:3] iz • Slice: Copy of continuous section of a sequence • Can give start and end position • Slicing shorthand (by omitting the start, end, or both points) word[:4] word[2:] word[:] • Slice is a brand-new sequence Guide to Programming with Python
indexing_nd_slicing.py import random word = "pizza" wlen = len(word) print word[1] print word[-1] rd = random.randrange(wlen) print word[rd] print word[0:wlen] print word[:] print word[:3] print word[-wlen] print word[wlen] ? Guide to Programming with Python
Using Sequence Operators and Functions • Python has functions and operators that work with sequences • Can tell you things such as • Length of sequence e.g., len(“abcd”) • If contains specific element e.g., “a” in “abcd” Guide to Programming with Python
Using the len() function >>> len("Game Over!") 10 • Takes a sequence (e.g., string – a sequence of letters) • Returns the number of elements • In strings, every character counts – spaces and punctuation Guide to Programming with Python
Using the in Operator >>> "e" in "Game Over" True • Tests for element membership • Returns True if element is in sequence • Returns False otherwise • Using in with index (see index_demo.py) alphabet = "abcdefghijklmnopqrstuvwxyz" letter = "a" if letter in alphabet: idx = alphabet.index(letter) Guide to Programming with Python
Immutable vs Mutable Sequences >>> word = "game" >>> word[0] = "l" TypeError: object does not support item assignment • Mutable: Changeable • Immutable: Unchangeable • String immutability -- Strings are immutable sequences; can’t be changed • Tuples are immutable too; Lists are mutable! • But can create new strings from existing ones (like through concatenation) Guide to Programming with Python
String Immutability • Cannot modify an existing string • But can "build" (create) a new string with concatenation operator • The following do NOT work word = "game" word[0] = "G” • The following work word = "game" word = "Game" Guide to Programming with Python
The No Vowels Program • VOWELS = "aeiou" • Constant: Name associated with value not meant to be changed • Convention is to use all uppercase variable names • Can make programs clearer • No true constants in Python 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
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 a = ("Monday", 3, 4.5) Guide to Programming with Python
Tuple Basics • Creating an Empty Tuple 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") • 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
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 & Slicing Tuples inventory = ("sword", "armor", "shield", "healing potion") inventory[0] ? inventory[0][1]? inventory[0:2]? Guide to Programming with Python
Tuple Immutability >>> 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 • The Hero’s Inventory Game (to demo creating, indexing, slicing, and concatenating tuples) 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
Planning the Word Jumble Game The jumble creation section was planned first in pseudocode Create an empty jumble word While the chosen word has letters in it extract a random letter from the chosen word add the random letter to the jumble word Guide to Programming with Python
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? • True • 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