Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 4 Strings & Tuples

Similar presentations


Presentation on theme: "Chapter 4 Strings & Tuples"— Presentation transcript:

1 Chapter 4 Strings & Tuples
Part II

2 Creating Tuples Tuples are a type of sequence that can contain elements of any type (unlike a string which can only contain characters) Tuple elements don’t have to all be the same type. Ex. Could be both strings and numbers combined Ex. Could be a sequence of graphic images or sound files. Whatever you can assign to a variable, you can group together and store as a sequence in a tuple.

3 Creating Tuples Continued
To create a tuple, you surround a sequence of values, separated by commas, with parentheses. Ex. Inventory = (“sword”, “armor”, shield”, “healing potion”) If you don’t put anything inside the parenthesis it is an empty tuple Ex. Inventory = ( ) You can write a tuple on one line or span it across multiple lines, as long as you end each line with a comma.

4 Tuples Continued Tuples can be treated as conditions just like any other value. Ex. If not inventory: print(“You are empty handed”) As a condition, an empty tuple is False and a tuple with at least one element is True.

5 Printing Tuples Though a tuple can contain many elements, you can print the entire tuple just like you would any single value. Ex. grocerylist = (“bread”, “milk”, “eggs”) print(grocerylist) This will print (‘bread’, ‘milk’, ‘eggs’) You can also loop through a tuple so that every element is printed individually Ex. for item in grocerylist: print(item) This will print: bread milk eggs

6 Using Tuples Note: Other programming languages offers structures similiar to tuples, however in those languages you can’t mix elements of different types in the sequences. For example, you couldn’t mix strings and numbers. You can do anything with a tuple that you can with a string Get length Print each element with a for loop Use the in operator to test if an element is a tuple Index, slice, and concatenate

7 Using the len() function
Ex. print(“You have”, len(grocerylist), “items on your list.” This will print “You have 3 items on your list” Using the in Operator Ex. If “eggs” in grocerylist: print(“You can make an omelet this week”) Slicing Tuples Every element in the tuple corresponds to a position Tuples can be sliced just like other strings Ex. print(grocerylist[0,2]) would print “bread” and “milk”

8 Tuple Immutability Just like strings, tuples are immutable (you can’t change them Even though you can’t change them you can build on them by concatentating Ex. forgottenitems =(“PB”, “Jelly”) grocerylist +=forgottenitems Your grocery list would now include: bread, milk, eggs, PB, Jelly


Download ppt "Chapter 4 Strings & Tuples"

Similar presentations


Ads by Google