Seminar 5: Data Types 1 Learning Objectives In this lecture, you will learn ● Strings ● Numbers ● List ● Dictionary 2 2 Strings • • • • Sequence of characters It can contains text, symbols and numbers Numbers will be treated as text. Embedded within: – Single quote (for single line): ‘ ’ – Double quote (for single line): “ “ • Double quote is preferred. – Triple quote (for multi lines): “”” ””” • Triple quote preserves the original formatting including line breaks. 3 3 Strings Examples – Single quote (for single line): ‘ ’ • str1 = ‘this is sentence 1.’ – Double quote (for single line): “ “ • str2 = “this is sentence 2.” – Triple quote (for multi lines): “”” ””” • str3 = “””this is sentence 3. the is second line. this is the third line. “”” 4 4 String sequence • String associates each character with an index number. • Index number starts from 0. • Use square bracket to embed index number. • To refer to a particular character, refer to it using the format: – string_var_name[index] 5 5 String reverse indexing • Default indexing starts from the left. • Reverse indexing starts from the right, using the notation of negative. • To refer to a particular character, refer to it using the format: – string_var_name[-index] 6 6 String slicing • Slicing extracts a subset of string sequence. • Syntax as follows: – string_var_name[start: stop] – start: starting index of extraction – stop: stopping index of extraction, excluding last position 7 7 String slicing • The default index for start is 0. • The default index for ending if not specified is assumed to be till the end of string. • Slicing also works for step change, syntax as follows: – string_var_name[start: stop: step] 8 8 String functions • Python default package consists of rich set of functions supporting string. • We will learn a few important ones. 9 9 String functions • Function like capitalize returns a string that capitalize the string given, in this case the string given is text. • Other types of function like isXxxx() returns Boolean value indicating if the given string is for example a kind of digit or alphabet. 10 10 String formatting • Strings can be combined using concatenation: – Syntax: • new_string = string1 + string2 + …. – Example: 11 11 String format • String formatting using .format() allows for greater flexibility and better presentation. • Syntax: – ”Text {:formatting for variable} other text ”.format(matching variable/ value) • In the above syntax, the expression started with a pair of double quote which contains the desired output string. • The {} within the output string contains the formatting method, formatting can indicate whether it is a string (s), integer (d), float (f). • It can also contain width (in numbers) and alignment information. Left align (<), right align (>) and center align (^). 12 12 String format • • See the following example. The first curly bracket formats the first string variable text1 to have 10 spaces in total, aligned to center. • Second formatting doesn’t add additional spaces or instruction. • Third one will shift the text3 variable to be right aligned. • Last variable is an integer variable. 13 13 Formatting numbers • The number of precision can be specified in {} with .2 for 2 decimal point. 14 14 Using f”…{var}…” for string formatting 15 15 List • For the data types we have learnt thus far, a single variable is used to store single value. • To store multiple values in one single variable name, we use data structures. • List is one form of the data structure. • Syntax: – listname = [value1, value2, value3…] • value can be of number, string, or other object. 16 16 List • Defining list with defined values. • Add in more values by using append() function from list. 17 17 List • List is similar to strings. – Can access individual component using index. • Eg. employee_names[0] – List can be concatenated using + – List can be sliced in a similar manners as string – len() can be used to get the size of list. • Eg. len(employee_names) 18 18 List functions • len(list_name): returns the size of list • min(list_name): returns the minimum value in the list • max(list_name): returns the maximum value in the list • sum(list_name): returns the sum of all numbers in the list 19 19 List iteration • for-loop can be applied to string or list variables to provide access to individual elements. • This often allows for greater usability to manipulate the contents. • The first for-loop iterate the list and store each value of list into a temporary variable called element. 20 20 Other list functions • These methods should be applied to list name. It will change the original list. – – – – • append() insert() sort() reverse() Example: 21 21 split() • split() is a string function that is used to decompose the contents of split. • A string can be split according to the delimiter. • After split, it returns a list contains all the split values. 22 22 Tuple • Sequence of data stored in one single variable name. • Tuple is immutable, value remains the same. • Data can be different types of Python objects like numbers, string, or other objects. • Objects in tuple can be different types. • Similar to List, it is accessed via index. • Different from List, it uses brackets instead of square brackets. • Syntax: – tuple_name = (value1, value2, value3…) 23 23 Tuple • Defining list with defined values. • When function returns multiple values, it’s in tuple form. 24 24 Tuple functions • The immutable tuples do not come with functions like list that changes the data. • tuple_name.count(“a”): returns the number of items whose content matches with “a”. • tuple_name.index(“a”): returns the index number of first “a” in tuple_name. • Other functions which are applicable to tuple: – enumerate(), len(), max(), min(), sorted(), sum(), – tuple() # convert a data type to tuple form. 25 25 Dictionary • A type of data structure that creates key and value pair. • Each key can be used to retrieve its corresponding value. • Key acts as an index to find its associative value. • It is similar to how you look up the dictionary where the word is the key. The definition is the value. • Dictionary is created using curly bracket { } • Within the { } are pairs of keys and values. Key and value are separated by colon, and each pair is separated by comma. 26 26 Dictionary • The general structure is as follows: dict_name = { “key1”: value1, “key2”: value2} dict_name key1 value1 key2 value2 27 27 Dictionary • Key must be unique. It can be of type string or integer. • Value can be string, integer, list and etc. • It is different from list which goes by sequential index. 28 28 Dictionary • Start with declaring an empty dictionary variable. • Then add in record one by one. • To retrieve the value corresponds to the key, use square bracket. 29 29 Value in dictionary • See the following example that stores list of customer details. • Accessing individual list value is the same approach as list using square bracket denoting the index number. 30 30 Useful methods for dict. • len(dict_name) # returns the number of items in this dictionary. • dict_name.clear() # to empty the dictionary • dict_name.items() # returns pairs of key value • dict_name.keys() # returns all keys in the dictionary • dict_name.values() # returns all values in the dictionary 31 31 Iterating dictionary • Iterating through the variable directly: for each in dict_name: # each will store the one key for each iteration 32 32 Iterating dictionary • Iterating through items: for key, value in dict_name.items(): # key and value can be called directly within for loop. # key and value change for each iteration • Iterating through values: for value in dict_name.values(): # this keeps just the value for each iteration 33 33 You have learnt... 1. To use strings and its function. 2. To format the presentation of strings and numbers. 3. About list and use it to store multiple data of the same type. 4. How to use dictionary to store key and value pairs. 34 34