ANL252_SU2_Jul2024.pdf
Document Details
Uploaded by Deleted User
Tags
Full Transcript
Study Unit 2 Data Types and Functions Tuples Define Tuples A collection of values written as comma-separated items between a pair of round brackets. tuple_name = (element1, element2, …) Tuples are not specifically designed for mathematical operations. A tup...
Study Unit 2 Data Types and Functions Tuples Define Tuples A collection of values written as comma-separated items between a pair of round brackets. tuple_name = (element1, element2, …) Tuples are not specifically designed for mathematical operations. A tuple is like a database record Example: employee_A1 = ("Jimmy Chow", "Engineer", "Grade 2") The items in a tuple can be numeric, string, or a mixture of both. Useful when sharing data with others but not giving others the permission to edit the contents (aka, Immutable --- the contents cannot be changed) 3 Subset and Index Tuples Use index operator [] to access specific elements in a tuple. The index begins with 0 and ends with the number of elements minus 1. To subset multiple elements, put the start and end indices, connected by a colon in the index operator. tuple_subset = tuple_name[start:end] Important: The end index is NOT included in the subsetting procedure. Apply negative indices to access elements starting from the last element. 4 Example of index Suppose we have a tuple of fruits, named as Fruits fruits = ("Apple", "Orange", "Banana") We can index this tuple using a positive index fruits = ("Apple", "Orange", "Banana") Index 0 Index 1 Index 2 Alternatively, we can refer to elements of this tuple using a negative index fruits = ("Apple", "Orange", "Banana") Index -3 Index -2 Index -1 5 Example of subset Returning to our tuple named as ‘fruits’ fruits = ("Apple", "Orange", "Banana") Creating fruits_subset = fruits[0:2], obtain all elements except index 2 fruits_subset = ("Apple", "Orange") Index 0 Index 1 Create fruits_subset = fruits[-3:-1], obtain all elements except index -1 fruits_subset = ("Apple", "Orange") fruits = ("Apple", "Orange", "Banana") Index -3 Index -2 Index -1 6 Edit and Concatenate Tuples Recall: Tuples are immutable. Values of a tuple cannot be changed. We are also not allowed to add a new value to an existing tuple. 7 Length of Tuples The length of a tuple is the number of elements in it. Use as an index to subset a tuple Control the indexing so that the indices do not get out of range. tuple_length = len(tuple_name) 8 For-Loops and Tuples Tuple elements are can accessible by running a for-loop iteratively. Put the name of the tuple in the for-statement directly. for counter in tuple_name: instructions It is also applicable to lists and dictionaries. 9 Example Program for Students Create two tuples: Tuple 1—The names of three people; Tuple 2—The ages of the three people What are the length of Tuple 1 and Tuple 2, respectively? Length of Tuple 1: 3 Length of Tuple 2: 3 Print the content in Tuple 1 and Tuple 2 with for loops, respectively. Try to concatenate the two tuples. 10 Lists Create Lists A Python list is just like a tuple with two main differences: Data are comma-separated and wrapped by a pair of square brackets. Content is modifiable. We can construct a Python list in a similar fashion like a tuple. list_name = [element1, element2, …] The square brackets are not omittable. Contents can be any type of objects: floats, integer, Booleans, strings, tuples, or even lists. 12 Subset Lists Use index operator [] to access specific elements in a list. All indexing and subsetting techniques for tuples are applicable to lists. list_subset = list_name[start:end] 13 Modify Lists Modify specific list items by subsetting and assigning new values to them. list_name[index] = new value Use multiple indexing to edit multiple items. list_name[start index:end index] = [list with new values] The list of new values will occupy the locations within [start index:end index] loactions on the left-hand side. The list on the left-hand side will expand or shrink accordingly. 14 Examples of modifying lists Index 0 Index 1 Index 2 Replacement Replace & expand 15 Some subtle points fruits[0:1] is a list ["Apple"] To replace a list, we need a list fruits[0:1] = ["Papaya"] fruits is a string, i.e., "Apple" To replace a string, we need a string fruits = "Papaya" 16 Concatenate Lists We can concatenate multiple lists into one by “adding” them together. combined_list = list1 + list2 + … Addition operation “+” is used to concatenate objects such as string, tuples, or lists. Concatenating lists is recommended if content and type of the lists are identical. Even if the nature of the two lists is not identical, it is sometimes quite convenient to store the data in one list for later use. 17 Example of concatenating lists Suppose we have two lists, Fruits and Vegetables fruits = ["Apple", "Orange", "Banana"] vegetables = ["Spinach", "Lettuce", "Cabbage"] Generate combined = fruits + vegetables combined = ["Apple", "Orange", "Banana", "Spinach", "Lettuce", "Cabbage"] 18 Merge Lists Meaning and source of the elements in a concatenated list with different nature of data will become untraceable with time. Merge two lists into a new list without combining the elements together. Each element of the new list is a list and not a single value. Define a new list by putting the list names as elements. list_name = [list1, list2, …] Use index to refer to a whole sub-list. Possible to trace back the origin and meaning of the data in the new list. 19 Example of merging lists Suppose we have two lists, Fruits and Vegetables fruits = ["Apple", "Orange", "Banana"] vegetables = ["Spinach", "Lettuce", "Cabbage"] Now merge the two lists: combined = [fruits, vegetables] 1st element of combined is fruits combined = [ ["Apple", "Orange", "Banana"], ["Spinach", "Lettuce", "Cabbage"] ] 2nd element of combined is vegetables 20 Print Lists Use loops to subset lists and print the items to the screen. Include lists in the for-statement to print the list items instead of using range(). for counter in list_name: instructions 21 Enter Data to Lists User-defined instead of pre-defined values for list items. Let users enter their own data by the input() function. Store the input into a list. Do not limit the number of entries and use a while-loop with appropriate exit condition. 22 Example Program for Students Create two lists: List 1—The names of three people; List 2—The ages of the three people Modify the middle item in List 2. Print the items in List 2 with for loop. Concatenate the two lists. Merge the two lists (including two sub-lists) 23 Dictionaries Define and Access Dictionaries A dictionary is an unordered set of key:value pairs. The keys must be unique within one dictionary. The key:value pairs are separated by commas and wrapped in a pair of braces. dictionary_name = {"key1":value1, "key2":value2, …} Dictionaries are indexed by keys, which are usually strings or numbers. Extract values in a dictionary by the keys. value = dictionary_name["key"] 25 Examples of Dictionaries Let us create a dictionary for the prices of our Fruits list fruits_price = {"Apple": 1.20, "Orange":0.70, "Banana":0.90} To get the price of Apple, we apple_price = fruits_price["Apple"] 26 Print Dictionaries Printing syntax for dictionaries is quite different from tuples and lists. It is possible to use the key to extract a value, but index operator [] cannot refer to the keys. Use.keys() and.values() to extract the dictionary’s keys and values. Apply.item() to extract all keys and values in the same step. dictionary_name.keys() dictionary_name.values() dictionary_name.items() 27 Examples of printing dictionaries Using fruits_price.keys(), we get the dictionary’s keys dict_keys(["Apple", "Orange", "Banana"]) Using fruits_price.values(), we get the dictionary’s values dict_values(["1.20", "0.70", "0.90"]) Using fruits_price.items(), we get the dictionary’s keys and values dict_items([("Apple",1.20), ("Orange", 0.70), ("Banana", 0.90)]) 28 Print Dictionaries Items A dict_items() object contains tuples with keys and values as items. Use a for-loop and the index operator to print the contents. Extend the for-loop so that indices are omitted when referring to dictionary items. for element1, element2 in list(dictionary_name.items()): instructions The for-loop can also iterate through any list created from a dictionary. Two temporary storage variables instead of one are in the for-loop: one for the key, one for the value. 29 Example of printing dictionary items Printing the items of our fruits_price dictionary 30 Edit Dictionaries Change a value of a dictionary by assigning a new value to a certain key. The value can be a numeric value, a character string, a tuple, or a list. dictionary_name["key"] = value 31 Example of editing dictionary Let us change the price of Apple from 1.20 to 120. fruits_price["Apple"] = 120 Verify that the price of Apple is 120 in Fruits_Price. 32 Change Dictionary Keys Editing a key in a dictionary is not straightforward. The keys are immutable and cannot be changed directly. Instead, we can create a new key in a dictionary, take over the values from the old key, and then delete the old key. The syntax del deletes an object in Python, including a dictionary key. del object Once an object is deleted, it will no longer be available in the program. 33 Example of deleting Delete the key, Apple, in fruits_price Verify the key, Apple, is deleted from fruits_price 34 Add Items to Dictionary To add a dictionary key, we simply assign a value to a new key. dictionary_name["new key"] = value The syntax is just the same as the syntax to edit an existing key. The only difference is that the key in the index operator must be a new one here, and an existing one for editing. 35 Merge Dictionaries To merge two dictionaries, Python offers two options. Syntax for Python version 3.9 onwards uses the “Bitwise Or” operator “|” to merge two dictionaries: new_dictionary = dictionary1 | dictionary2 Syntax for Python version 3.5 onwards: new_dictionary = {**dictionary1, **dictionary2} 36 Example Program for Students Create one dictionary: Keys—The names of three people; Values—The ages of the three people Print the keys of the dictionary Print the values of the dictionary Extract all keys and values of the dictionary at the same time Print dictionary items line by line with for loops 37 Example Program for Students Modify the value of the middle item in the dictionary Delete the middle item in the dictionary Add another item ('name':age) to the dictionary Create a new ('name':age) dictionary with two items Merge the two dictionaries 38 Integrated Methods and Functions Functions Functions are routine programs for value processing. Values are passed on to functions as arguments/parameters and results will be returned as output to the user. E.g., int() removes all decimal digits of a value and returns an integer as result. 40 Built-In Functions Built-in functions are integrated in Python, e.g., print(), input(). Here is a list of all Python built-in functions in alphabetical order. abs() all() any() ascii() bin() bool() breakpoint() bytearray() bytes() callable() chr() classmethod() compile() complex() delattr() dict() dir() divmod() enumerate() eval() exec() filter() float() format() frozenset() getattr() globals() hasattr() hash() help() hex() id() input() int() isinstance() issubclass() iter() len() list() locals() map() max() memoryview() min() next() object() oct() open() ord() pow() print() property() range() repr() reversed() round() set() setattr() slice() sorted() staticmethod() str() sum() super() tuple() type() vars() zip() __import__() (Source: https://docs.python.org/3/library/functions.html) 41 Built-In Methods in Python Methods are routines that are applied to the objects they are attached to. E.g.,.format() for formatting string,.keys(),.values() and.items() for dictionaries. Methods return results to the program once they are applied on defined objects during runtime. Each method is only applicable to certain object types. The list of some common methods can be found on: https://www.w3schools.com/python/python_ref_tuple.asp https://www.w3schools.com/python/python_ref_list.asp https://www.w3schools.com/python/python_ref_dictionary.asp https://www.w3schools.com/python/python_ref_string.asp 42 Discussion How can we get the information on the components of a built-in function or method before applying them in our program? Can we avoid the use of functions or methods and write such routines by ourselves? 43 User-Defined Functions User-defined functions are functions that we write to suit our own needs. They will only be executed when they are called from the main program. A function usually consists of four parts: 1. Function name 2. Arguments 3. Instructions 4. Output object (or value) 44 Correct Use of User-Defined Functions No “outsourcing” of main program parts to functions because of “program cleanliness”. Debugging is challenging if the code jumps between main program and functions. Rules of thumb for using user-defined functions: 1. Same routine appears more than once in main program. 2. Combination of various functions is used on multiple occasions. 3. Increase of main program’s efficiency. 45 Syntax of User-Defined Functions The def-syntax indicates the definition of a function: def function_name(argument1, argument2, …): instructions return object Functions are called in the main program by integrating the function name with the arguments at an appropriate place. … (Main program) y = function_name(argument1 = object1, argument2 = object2, …) print(y) … (Continue with main program) 46 Example: user-defined functions 47 Example Program for Students Please write user-defined functions that enable users to perform addition, subtraction, multiplication, and division with two input integers. Call the user-defined functions in your main programme and display the results. 48 Discussion When is it appropriate for us to write a user-defined function? 49 Modules, Packages and Libraries (This section is for your information only because you are using Anaconda3) Modules, Packages, Libraries Python packages are like directories of Python scripts, or modules. Modules specify functions, methods, and object types to solve certain tasks. Packages may contain sub-packages or regular modules. Packages of standard libraries are already installed in Python. Library is a collection of codes to perform specific tasks without writing our own code. 51 Import Packages and Modules In Python, we can choose to import the entire package or a specific module of the package. import package_name as package_alias from package_name import module_name as module_alias Use an alias to refer to a specific package or module from thereon in the program. Alias is advantageous if the package or module has a very long name. 52 Install Packages with pip/pip3 More Python packages are available on the internet. Download and install them by the pip or pip3 Python package. Use PowerShell or Command Prompt as well (or similar terminal apps from other operation systems) to execute the following command: > pip install package_name > pip3 install package_name “pip3” is a newer version of “pip”. Use either one for the installation. 53 Upgrade and Uninstall Packages To update/upgrade a package, we need to type the following syntax in the terminal apps. > pip install package_name --upgrade > pip3 install package_name --upgrade Uninstall a package by the command: > pip uninstall package_name > pip3 uninstall package_name 54 Common Packages in Python Here are some common packages for data analytics in Python. Package Description matplotlib Creates data visualisation NumPy Manages multi-dimensional arrays pandas Handles two-dimensional data tables pendulum Provides complex coding for dates and times requests Sends HTTP requests from Python code scikit-learn Provides tools of data analytics scipy Carries out scientific and technical computations sqlite3 Manages SQL database in Python 55 Online Learning Platform (Optional) Tuple: https://www.w3schools.com/python/python_tuples.asp List: https://www.w3schools.com/python/python_lists.asp Dictionary: https://www.w3schools.com/python/python_dictionaries.asp Functions: https://www.w3schools.com/python/python_dictionaries.asp 56