Python Programming Lists Lecture Notes PDF

Document Details

LuckiestOganesson

Uploaded by LuckiestOganesson

Dr. Ahmed Alnasheri

Tags

python programming lists data structures programming languages

Summary

These notes cover Python programming, specifically details about lists. Topics include creating lists, accessing elements, list mutability, traversing lists, deleting elements, list operators (concatenation, repetition, and membership), and indexing.

Full Transcript

PYTHON PROGRAMMING LISTS Unit 5: Lists Python Programming : Lecture Five Dr. Ahmed Alnasheri 1 Outline of This Lecture 6.1 Objectives 6.1.1 Creating Lists 6.2 Values an...

PYTHON PROGRAMMING LISTS Unit 5: Lists Python Programming : Lecture Five Dr. Ahmed Alnasheri 1 Outline of This Lecture 6.1 Objectives 6.1.1 Creating Lists 6.2 Values and Accessing Elements 6.3 Lists are mutable 6.4 Traversing a List 6.5 Deleting elements from List 6.6 Built-in List Operators 6.7 Concatenation 6.8 Repetition 6.9 In Operator 6.10 Built-in List functions and methods 6.11 Summary 6.12 Exercise 6.13 References Python Programming : Lecture Five Dr. Ahmed Alnasheri 2 Lecture Objectives After reading through this chapter, you will be able to : 1. To learn how python uses lists to store various data values. 2. To study usage of the list index to remove, update and add items from python list. 3. To understand the abstract data types queue, stack and list. 4. To understand the implementations of basic linear data structures. 5. To study the implementation of the abstract data type list as a linked list using the node. Python Programming : Lecture Five Dr. Ahmed Alnasheri 3 A LIST IS A SEQUENCE While strings are always sequences of characters, lists (or arrays as denoted in other languages) can be sequences of arbitrary objects Hence, they are more general than strings. The list is most likely versatile data type available in the Python which is can be written as a list of comma-separated values between square brackets. The Important thing about a list is that items in the list need not be of the same type. Creating a list is as very simple as putting up different comma- separated by values between square brackets. For example : list1 = ['jack', 'nick', 1997, 5564]; list2 = [1, 2, 3, 4]; list3 = ["a", "b", "c", "d"]; Python Programming : Lecture Five Dr. Ahmed Alnasheri 4 Creating List In general, we can create lists via putting a number of expressions in square brackets List = [] List = [expression, …] E.g., List = [1+2, 7, “Eleven”] List = [expression for variable in sequence], where expression is evaluated once for every element in the sequence (this is called ”list comprehension”) E.g., List1 = [x for x in range(10)] E.g., List2 = [x + 1 for x in range(10)] E.g., List3 = [x for x in range(10) if x % 2 == 0] Python Programming : Lecture Five Dr. Ahmed Alnasheri 5 Creating List We can also use the built-in list type object to create lists: L = list() #This creates an empty list L = list([expression, …]) L = list(expression for variable in sequence) >>> l1 = list() >>> l1 [] >>> type(l1) >>> l2 = list(["A", 2.3]) >>> l2 ['A', 2.3] Python Programming : Lecture Five Dr. Ahmed Alnasheri 6 TRAVERSAL AND THE FOR LOOP: BY ITEM We can also use the built-in list type object to create lists: L = list() #This creates an empty list L = list([expression, …]) L = list(expression for variable in sequence) >>> type(l2) >>> l3 = list(x for x in range(10)) >>> l3 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> type(l3) >>> Python Programming : Lecture Five Dr. Ahmed Alnasheri 7 Creating List Python creates a single new list every time we use [] >>> L1 = [1, 2, 3] >>> L3 = L4 = [1, >>> L2 = [1, 2, 3] 2, 3] >>> L1 == L2 >>> L3 == L4 True True >>> L1 is L2 >>> L3 is L4 False True >>> >>> L1 and L2 have the same values but they are L3 and L4 point to the same list independent lists (i.e., they do not point to the same list) Python Programming : Lecture Five Dr. Ahmed Alnasheri 8 VALUES AND ACCESSING ELEMENTS To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example: list1 =['jack','nick',1997,5564]; list2 =[1,2,3,4,5,6,7]; print"list1: ", list1 print"list2[1:5]: ", list2[1:5] output : list1: jack list2[1:5]: [2, 3, 4, 5] Python Programming : Lecture Five Dr. Ahmed Alnasheri 9 LISTS ARE MUTABLE lists is mutable. This means we can change a item in a list by accessing it directly as part of the assignment pf statement. Using the indexing operator (square brackets) on the left of side an assignment, we can update one of the list item. Example: color = ["red", "white", "black"] print(color) color = "orange" color [-1] = "green" print(color) Output: ["red", "white", "black"] ["orange ", "white", "green "] Python Programming : Lecture Five Dr. Ahmed Alnasheri 10 TRAVERSING A LIST The mostly common way to traverse the elements of list with for loop. The syntax is the same as for strings: color = ["red", "white", "blue", "green"] for x in color : print(x) This works well if you only need to read the element of list. But if you want to do write or update the element, you need the indices. A common way to do that is to combine the functions range and len: for i in range(len(number)): number [i] = number[i] * 2 Output: red white blue green Python Programming : Lecture Five Dr. Ahmed Alnasheri 11 DELETING ELEMENTS FROM LIST To delete a list element, you can use either the del statement, del removes the item at a specific index, if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example: list1 = [‘red’, ‘green’, 5681, 2000,]; print(list1) del list print(“After deleting element at index 2 :”); print(list1) output [‘red’, ‘green’, 5681, 2000,] After deleting element at index 2 : [‘red’, ‘green’ , 2000,] Python Programming : Lecture Five Dr. Ahmed Alnasheri 12 DELETING ELEMENTS FROM LIST Example2: numbers = [50, 60, 70, 80] del numbers[1:2] print(numbers) output [50, 70, 80] One other method from removing elements from a list is to take a slice of the list, which excludes the index or indexes of the item or items you are trying to remove. For instance, to remove the first two items of a list, you can do: list = list[2:] Python Programming : Lecture Five Dr. Ahmed Alnasheri 13 BUILT-IN LIST OPERATORS In this lesson we will learn about built-in list operators: Python Programming : Lecture Five Dr. Ahmed Alnasheri 14 BUILT-IN LIST OPERATORS Concatenation Concatenation or joining is a process in which multiple sequence / lists can be combined together. ‘+’ is a symbol concatenation operator. Example: list1 = [10, 20, 30] list2 = [40, 50, 60] print(list1 + list2) Output: [10, 20, 30, 40, 50, 60] Python Programming : Lecture Five Dr. Ahmed Alnasheri 15 BUILT-IN LIST OPERATORS Repetition / Replication / Multiply This operator replication the list for a specified number of times and creates a new list. ‘*’ is a symbol of repletion operator. Example: list1 = [10, 20, 30] list2 = [40, 50, 60] print(list1 * list2 Output: [10, 20, 30,10, 20, 30,10, 20, 30,]) Python Programming : Lecture Five Dr. Ahmed Alnasheri 16 BUILT-IN LIST OPERATORS Membership Operator This operator used to check or test whether a particular element or item is a member of any list or not. ‘in’ And ‘not in’ are the operators for membership operator. Example: list1 = [10, 20, 30] list2 = [40, 50, 60] print(50 in list1) #false print(20 in list1) #true print(50 not in list1) #true print(20 not in list1) #false Output: False True True False Python Programming : Lecture Five Dr. Ahmed Alnasheri 17 BUILT-IN LIST OPERATORS Indexing Indexing is nothing but there is an index value for each tem present in the sequence or list. Example list1 = [10, 20, 30, 40, 50, 60, 70] print(list1) Output 50 Python Programming : Lecture Five Dr. Ahmed Alnasheri 18 BUILT-IN LIST OPERATORS Slicing operator This operator used to slice a particular range of a list or a sequence. Slice is used to retrieve a subset of values. Syntax list1[start:stop:step] Example list1 = [10, 20, 30, 40, 50, 60, 70] print(list1[3:7]) Output [40, 50, 60, 70] Python Programming : Lecture Five Dr. Ahmed Alnasheri 19 CONCATENATION In this we will learn different methods to concatenate lists in python. Python list server the purpose of storing homogenous elements and perform manipulations on the same. In general, Concatenation is the process of joining the elements of a particular data-structure in an end-to-end manner. The following are the 4 ways to concatenate lists in python. (1) Concatenation (+) operator The '+' operator can be used to concatenate two lists. It appends one list at the end of the other list and results in a new list as output. Python Programming : Lecture Five Dr. Ahmed Alnasheri 20 CONCATENATION Example list1 =[10, 11, 12, 13, 14] list2 =[20, 30, 42] result =list1 +list2 print(str(result)) Output: [10, 11, 12, 13, 14, 20, 30, 42] (2) Naive method In the Naive method, a for loop is used to be traverse the second list. After this, the elements from the second list will get appended to the first list. The first list of results out to be the concatenation of the first and the second list. Python Programming : Lecture Five Dr. Ahmed Alnasheri 21 CONCATENATION Example list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] print(“Before Concatenation:” + str(list1)) for x in list2 : list1.append(x) print (“After Concatenation:” + str(list1)) Output Before Concatenation: [10, 11, 12, 13, 14] After Concatenation: [10, 11, 12, 13, 14, 20, 30, 42] Python Programming : Lecture Five Dr. Ahmed Alnasheri 22 CONCATENATION List comprehension Python list comprehension is an the alternative method to concatenate two lists in python. List comprehension is basically the process of building / generating a list of elements based on an existing list. It uses the for loop to process and traverses a list in the element-wise fashion. The below inline is for-loop is equivalent to a nested for loop. Example Output: list1 = [10, 11, 12, 13, 14] Concatenated list: list2 = [20, 30, 42] [10, 11, 12, 13, 14, 20, 30, 42] result = [j for i in [list1, list2] for j in i] print ("Concatenated List:\n"+ str(result)) Python Programming : Lecture Five Dr. Ahmed Alnasheri 23 CONCATENATION Extend() method Python extend() method can be used to concatenate two lists in python. The extend() function does iterate over the password parameter and add the item to the list, extending the list in a linear fashion. Syntax Output: list.extend(iterable) list1 before concatenation: [10, 11, 12, 13, 14] Example: Concatenated list i.e ,ist1 after concatenation: list1 = [10, 11, 12, 13, 14] [10, 11, 12, 13, 14, 20, 30, 42] list2 = [20, 30, 42] print("list1 before concatenation:\n" + str(list1)) list1.extend(list2) print ("Concatenated list i.e ,ist1 after concatenation:\n"+ str(list1)) All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output. Python Programming : Lecture Five Dr. Ahmed Alnasheri 24 CONCATENATION (3) ‘*’ operator Python’s '*' operator can be used for easily concatenate the two lists in Python. The ‘*’ operator in Python basically unpacks the collection of items at the index arguments. For example Consider a list list = [1, 2, 3, 4]. The statement *list would replace by the list with its elements on the index positions. So, it unpacks the items of the lists. Example: list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = [*list1, *list2] print ("Concatenated list:\n " + str(res)) Python Programming : Lecture Five Dr. Ahmed Alnasheri 25 CONCATENATION Output In the above snippet of code, the statement res = [*list1, *list2] replaces the list1 and list2 with the items in the given order i.e. elements of list1 after elements of list2. This performs concatenation and results in the below output. Output Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] Python Programming : Lecture Five Dr. Ahmed Alnasheri 26 CONCATENATION Itertools.chain() method Python itertools modules’ itertools.chain() function can also be used to concatenate lists in Python. The itertools.chain() function accepts different iterables such as lists, string, tuples, etc as parameters and gives a sequence of them as output. It results out to be a linear sequence. The data type of the elements doesn’t affect the functioning of the chain() method. For example: The statement itertools.chain([1, 2], [‘John’, ‘Bunny’]) would produce the following output: 1 2 John Bunny Python Programming : Lecture Five Dr. Ahmed Alnasheri 27 CONCATENATION Example: import itertools list1 = [10, 11, 12, 13, 14] list2 = [20, 30, 42] res = list(itertools.chain(list1, list2)) print ("Concatenated list:\n " + str(res)) Output Concatenated list: [10, 11, 12, 13, 14, 20, 30, 42] Python Programming : Lecture Five Dr. Ahmed Alnasheri 28 REPETITION Now, we are accustomed to using the '*' symbol to represent the multiplication, but when the operand on the left of side of the '*' is a tuple, it becomes the repetition operator. And The repetition of the operator it will makes the multiple copies of a tuple and joins them all together. Tuples can be created using the repetition operator, *. Example: number = (0,) * 5 # we use the comma to denote that this is a single valued tuple and not an ‘#’expression Output print numbers (0, 0, 0, 0, 0) is a tuple with one element, 0. Now repetition of the operator it will makes 5 copies of this tuple and joins them all together into a single tuple. Another example using multiple elements in the tuple. Example: numbers = (0, 1, 2) * 3 Output print numbers (0, 1, 2, 0, 1, 2, 0, 1, 2) Python Programming : Lecture Five Dr. Ahmed Alnasheri 29 IN OPERATOR Python's in operator lets you loop through all the members of a collection (such as a list or a tuple) and check if there's a member in the list that's equal to the given item. Example: my_list = [5, 1, 8, 3, 7] print(8 in my_list) print(0 in my_list) Output True False Note: Note that in operator against dictionary checks for the presence of key. Example my_dict = {'name': 'TutorialsPoint', 'time': '15 years', 'location': 'India'} print('name' in my_dict) Output This will give the output : True Python Programming : Lecture Five Dr. Ahmed Alnasheri 30 BUILT-IN LIST FUNCTIONS AND METHODS Built-in function Python Programming : Lecture Five Dr. Ahmed Alnasheri 31 BUILT-IN LIST FUNCTIONS AND METHODS Built-in method Python Programming : Lecture Five Dr. Ahmed Alnasheri 32 SUMMARY Python lists are commanding data structures, and list understandings are one of the furthermost convenient and brief ways to create lists. In this chapter, we have given some examples of how you can use list comprehensions to be more easy-to-read and simplify your code. The list is the common multipurpose data type available in Python. A list is an ordered collection of items. When it comes to creating lists, Python list are more compressed and faster than loops and other functions used such as, map(), filter(), and reduce().Every Python list can be rewritten in for loops, but not every complex for loop can be rewritten in Python list understanding. Writing very long list in one line should be avoided so as to keep the code user-friendly. So list looks just like dynamic sized arrays, declared in other languages. Lists need not be homogeneous always which makes it a most powerful tool in Python. A single list may contain Datatype’s like Integers, Strings, and Objects etc. List loads all the elements into memory at one time, when the list is too long, it will reside in too much memory resources, and we usually only need to use a few elements. A list is a data-structure that can be used to store multiple data at once. The list will be ordered and there will be a definite count of it. The elements are indexed allowing to a sequence and the indexing is done with 0 as the first index. Each element will have a discrete place in the sequence and if the same value arises multiple times in the sequence. Python Programming : Lecture Five Dr. Ahmed Alnasheri 33 UNIT END EXERCISE 1. Explain List parameters with an example. 2. Write a program in Python to delete first and last elements from a list 3. Write a Python program to print the numbers of a specified list after removing even numbers from it. 4. Write a python program using list looping 5. Write a Python program to check a list is empty or not 6. Write a Python program to multiplies all the items in a list 7. Write a Python program to remove duplicates from a list 8. Write a Python program to append a list to the second list 9. Write a Python program to find the second smallest number in a list. 10. Write a Python program to find common items from two lists Python Programming : Lecture Five Dr. Ahmed Alnasheri 34 REFERENCES 1. https://python.plainenglish.io/python-list-operation-summary- 262f40a863c8?gi=a4f7ce4740e9 2. https://howchoo.com/python/how-to-use-list-comprehension-in-python 3. https://intellipaat.com/blog/tutorial/python-tutorial/python-list- comprehension/ 4. https://programmer.ink/think/summary-of-python-list-method.html 5. https://www.geeksforgeeks.org/python-list/ 6. https://enricbaltasar.com/python-summary-methods-lists/ 7. https://developpaper.com/super-summary-learn-python-lists-just-this- article-is-enough/ 8. https://www.programiz.com/python-programming/methods/list 9. https://www.hackerearth.com/practice/python/working-with- data/lists/tutorial/ 10. https://data-flair.training/blogs/r-list-tutorial/ Python Programming : Lecture Five Dr. Ahmed Alnasheri 35 PYTHON PROGRAMMING TUPLES AND DICTIONARIES Unit 7: TUPLES AND DICTIONARIES Python Programming : Lecture Seven Dr. Ahmed Alnasheri 1 Outline of This Lecture 7.1 Objectives 7.11 Built-in Tuple Functions 7.2 Tuples 7.12 Creating a Dictionary 7.2 Accessing values in Tuples 7.13 Accessing Values in a dictionary 7.3 Tuple Assignment 7.14 Updating Dictionary 7.4 Tuples as return values 7.15 Deleting Elements from Dictionary 7.5 Variable-length argument tuples 7.16 Properties of Dictionary keys 7.6 Basic tuples operations 7.17 Operations in Dictionary 7.7 Concatenation 7.18 Built-In Dictionary Functions 7.8 Repetition 7.19 Built-in Dictionary Methods 7.9 In Operator 7.20 Summary 7.10 Iteration 7.21 Exercise 7.22 References Python Programming : Lecture Seven Dr. Ahmed Alnasheri 2 Lecture Objectives After reading through this chapter, you will be able to : 1. To understand when to use a dictionary. 2. To study how a dictionary allows us to characterize attributes with keys and values 3. To learn how to read a value from a dictionary 4. To study how in python to assign a key-value pair to a dictionary 5. To understand how tuples returns values Python Programming : Lecture Seven Dr. Ahmed Alnasheri 3 TUPLES A tuple in the Python is similar to the list. The difference between the two is that we cannot change the element of the tuple once it is assigned to whereas we can change the elements of a list. The reasons for having immutable types apply to tuples: copy efficiency: rather than copying an immutable object, you can alias it (bind a variable to a reference)... interning: you need to store at most of one copy of any immutable value. There’s no any need to synchronize access to immutable objects in concurrent code. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 4 TUPLES Like lists, tuples can: Contain any and different types of elements Contain duplicate elements (e.g., (1, 1, 2)) Be indexed exactly in the same way (i.e., using the [] brackets) Be sliced exactly in the same way (i.e., using the [::] notation) Be concatenated (e.g., t = (1, 2, 3) + (“a”, “b”, “c”)) Be repeated (e.g., t = (“a”, “b”) * 10) Be nested (e.g., t = ((1, 2), (3, 4), ((“a”, “b”, ”c”), 3.4)) Be passed to a function, but will result in pass-by-value and not pass-by-reference outcome since it is immutable Be iterated over Python Programming : Lecture Seven Dr. Ahmed Alnasheri 5 TUPLES Creating a Tuple: A tuple is created by the placing all the elements inside parentheses '()', separated by commas. The parentheses are the optional and however, it is a good practice to use them. A tuple can have any number of the items and they may be a different types (integer, float, list, string, etc.). Python Programming : Lecture Seven Dr. Ahmed Alnasheri 6 TUPLES Example: Output: () #Different types of tuples (1, 2, 3) tuple = () # Empty tuple (1, 'code', 3.4) ('color', [6, 4, 2], (1, 2, 3)) print(tuple) tuple = (1, 2, 3) # Tuple having integers print(tuple) tuple = (1, "code", 3.4) # tuple with mixed datatypes print(tuple) tuple = ("color ", [6, 4, 2], (1, 2, 3)) # nested tuple print(tuple) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 7 TUPLES Creating a Tuple: A tuple can also be created without using parentheses. This is known as tuple packing. tuple = 3, 2.6, "color" Output: print(tuple) ( 3, 2.6, 'color') 3 # tuple unpacking is also possible 2.6 a, b, c = tuple color print(a) #3 print(b) # 2.6 print(c) # Color Python Programming : Lecture Seven Dr. Ahmed Alnasheri 8 TUPLES This will print the elements of t1 in t1 = ("a", "b", "c") a reversed order, but will not change print(t1[::-1]) t1 itself since it is immutable t2 = ("a", "b", "c") t3 = t1 + t2 This will concatenate t1 and t2 and print(t3) assign the result to t3 (again, t1 and t3 = t3 * 4 t2 will be unchanged since they are print(t3) immutable) This will repeat t3 four times and for i in t3: assign the result to t3. Hence, print(i, end = " ") t3 will be overwritten (i.e., NOT changed in place- because it is immutable- print() , but redefined with a new value) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 9 ACCESSING VALUES IN TUPLES There are various ways in which we can access the elements of a tuple. 1. Indexing: We can use the index operator [] to access an item in a tuple, where the index starts from 0. So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range(6,7,... in this example) will raise an IndexError. The index must be an integer, so we cannot use float or other types. This will result in TypeError. Likewise, nested tuples are accessed using nested indexing, as shown in the example below. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 10 ACCESSING VALUES IN TUPLES Example: # Accessing tuple elements using indexing tuple = ('a','b','c','d','e','f') print(tuple) # 'a' print(tuple) # 'f' # IndexError: list index out of range # print(tuple) # Index must be an integer # TypeError: list indices must be integers, not float Output: a # tuple[2.0] f # nested tuple o tuple = ("color", [6, 4, 2], (1, 2, 3)) 4 # nested index print(tuple) # 'o' print(tuple) # 4 Python Programming : Lecture Seven Dr. Ahmed Alnasheri 11 ACCESSING VALUES IN TUPLES There are various ways in which we can access the elements of a tuple. 2. Negative Indexing: Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on. Example: # Negative indexing for accessing tuple elements tuple = ('a','b','c','d','e','f') print(tuple[-1]) Output: f print(tuple[-6]) a Python Programming : Lecture Seven Dr. Ahmed Alnasheri 12 ACCESSING VALUES IN TUPLES There are various ways in which we can access the elements of a tuple. 3. Slicing We can access the range of items from the tuple by using the slicing operator colon: Example: # Accessing tuple elements using slicing Output: tuple = ('a','b','c','d','e','f','g','h','i') ('b', 'c', 'd') ('a', 'b') print(tuple[1:4]) # elements 2nd to 4th # Output: ('b', 'c', 'd') ('h', 'i') # elements beginning to 2nd # Output: ('a', 'b') ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i') print(tuple[:-7]) # elements 8th to end # Output: ('h', 'i') print(tuple[7:]) # elements beginning to end # Output: ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i') print(tuple[:]) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 13 TUPLE ASSIGNMENT One of the unique syntactic features of the Python language is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when the left side is a sequence. In this example we have a two-element list (which is a sequence) and assign the first and second elements of the sequence to the variables x and y in a single statement. Example: tuple = ('red', 'blue‘) x, y = tuple # Output: x = 'red' y = 'blue' Python Programming : Lecture Seven Dr. Ahmed Alnasheri 14 TUPLE ASSIGNMENT One of the unique syntactic features of the Python language is the ability to have a tuple on the left side of an assignment statement. This allows you to assign more than one variable at a time when the left side is a sequence. In this example we have a two-element list (which is a sequence) and assign the first and second elements of the sequence to the variables x and y in a single statement. Example: tuple = ('red', 'blue‘) x, y = tuple # Output: x = 'red' y = 'blue' Python Programming : Lecture Seven Dr. Ahmed Alnasheri 15 TUPLE ASSIGNMENT It is not magic, Python roughly translates the tuple assignment syntax to be the following (for the previous example): m = [ 'red', 'blue' ] x = m y = m Output: x 'red' y 'blue' Python Programming : Lecture Seven Dr. Ahmed Alnasheri 16 TUPLES AS RETURN VALUES Functions can return tuples as return values. Now we often want to know some batsman’s highest and lowest score or we want to know to find the mean and the standard deviation, or we want to know the year, the month, and the day, or if we’re doing some ecological modeling we may want to know the number of rabbits and the number of wolves on an island at a given time. In each case, a function (which can only return a single value), can create a single tuple holding multiple elements. For example, we could write a function that returns both the area and the circumference of a circle of radius. Example: def cirlce_info(r): #Return (circumference, area) of a circle of radius r c = 2 * 3.14159 * r a = 3.14159 * r * r Output: return (c, a) (62.8318, 314.159) print(cirlce_info(10)) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 17 VARIABLE-LENGTH ARGUMENT TUPLES Functions can take a variable number of arguments. The parameter name that begins with the * gather the argument into the tuple. For example, the print all take any number of the arguments and print them: def printall(*args): print args The gather parameter can have any name you like, but args is conventional. Here’s how the function works: The complement of gather is scatter. If you have the sequence of values and you want to pass it to the function as multiple as arguments, you can use the * operator. For example, divmod take exactly two arguments it doesn’t work with the tuple: t = (7, 3) divmod(t) TypeError: divmod expected 2 arguments, got 1 But if you scatter the tuple, it works: divmod(*t) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 18 BASIC TUPLES OPERATIONS Now, we will learn the operations that we can perform on tuples in Python. 1. Membership: We can apply the ‘in’ and ‘not in’ operator on the items. This tells us whether they belong to the tuple. 'a' in tuple("string") Output: False 'x' not in tuple("string") Output: True 2.Concatenation: Like we’ve previously discussed on several occasions, concatenation is the act of joining. We can join two tuples using the concatenation operator ‘+’. (1,2,3)+(4,5,6) Output: (1, 2, 3, 4, 5, 6) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 19 BASIC TUPLES OPERATIONS 3. Logical: All the logical operators (like >,>=,..) can be applied on a tuple. (1,2,3)>(4,5,6) Output: False (1,2)==('1','2') Output: False 4. Identity: Remember the ‘is’ and ‘is not’ operators we discussed about in our tutorial on Python Operators? Let’s try that on tuples. a=(1,2) (1,2) is a Output: That did not make sense, did it? So what really happened? Now, in Python, two tuples or lists don't have the same identity. In other words, they are two different tuples or lists. As a result, it returns False. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 20 CONCATENATION Now, we will learn 2 different ways to concatenate or join tuples in the python language with code example. We will use ‘+” operator and a built-in sum() function to concatenate or join tuples in python. How to concatenate tuples into single/nested Tuples using sum(): 1 Sum() to concatenate tuples into a single tuple: In our first example, we will use the sum() function to concatenate two tuples and result in a single tuple.Let us jump to example: tupleint= (1,2,3,4,5,6) langtuple = ('C#','C++','Python','Go') #concatenate the tuple tuples_concatenate = sum((tupleint, langtuple), ()) print('concatenate of tuples \n =',tuples_concatenate) Output: concatenate of tuples = (1, 2, 3, 4, 5, 6, 'C#', 'C++', 'Python', 'Go') Python Programming : Lecture Seven Dr. Ahmed Alnasheri 21 CONCATENATION Sum() to concatenate tuple into a nested tuple: Now let us understand how we can sum tuples to make a nested tuple.In this program we will use two tuples which are nested tuples, please note the ‘,’ at the end of each tuples tupleint and langtuple. let us understand example: tupleint= (1,2,3,4,5,6), langtuple = ('C#','C++','Python','Go'), #concatenate the tuple tuples_concatenate = sum((tupleint, langtuple), ()) print('concatenate of tuples \n =',tuples_concatenate) Output: concatenate of tuples = ((1, 2, 3, 4, 5, 6), ('C#', 'C++', 'Python', 'Go')) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 22 CONCATENATION Concatenate tuple Using ‘+’ operator: ‘+’ operator to concatenate two tuples into a single tuple: In our first example, we will use the “+” operator to concatenate two tuples and result in a single tuple.In this example we have two tuple tupleint and langtuple,We are the concatenating these tuples into the single tuple as we can see in output. tupleint= (1,2,3,4,5,6) langtuple = ('C#','C++','Python','Go') #concatenate the tuple tuples_concatenate = tupleint+langtuple print('concatenate of tuples \n =',tuples_concatenate) Output: concatenate of tuples = (1, 2, 3, 4, 5, 6, 'C#', 'C++', 'Python', 'Go') Python Programming : Lecture Seven Dr. Ahmed Alnasheri 23 CONCATENATION Concatenate tuple Using ‘+’ operator: ‘+’ operator with a comma(,) to concatenate tuples into nested Tuples: This example, we have the two tuple tuple int and lang tuple. Now We are using the comma(,) end of the each tuple to the concatenate them into a nested tuple. We are concatenating these tuples into a nested tuple as we can see in the resulting output. # comma(,) after tuple to concatenate nested tuple tupleint= (1,2,3,4,5,6), langtuple = ('C#','C++','Python','Go'), #concatenate the tuple into nested tuple tuples_concatenate = tupleint+langtuple print('concatenate of tuples \n =',tuples_concatenate) Output: concatenate of tuples = ((1, 2, 3, 4, 5, 6), ('C#', 'C++', 'Python', 'Go')) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 24 REPETITION Now, we are going to explain how to use Python tuple repetition operator with basic syntax and many examples for better understanding. Python tuple repetition operator (*) is used to the repeat a tuple, number of times which is given by the integer value and create a new tuple values. Syntax: < tuple_variable_name1 > * N N * < tuple_variable_name1 > Input Parameters: tuple_variable_name1 : The tuples that we want to be repeated. N : where is the number of times that we want that tuple to be repeated ex: 1,2,3,……..n Python Programming : Lecture Seven Dr. Ahmed Alnasheri 25 REPETITION Example: data=(1,2,3,'a','b') # tuple after repetition print('New tuple:', data* 2) Output: New tuple: [1, 2, 3, ‘a’, ‘b’, 1, 2, 3, ‘a’, ‘b’] In the above Example, using repetition operator (*), we have repeated ‘data’ tuple variable 2 times by ‘data* 2’ in print statement and created new tuple as : [1, 2, 3, ‘a’, ‘b’, 1, 2, 3, ‘a’, ‘b’]. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 26 IN OPERATOR The Python in operator lets you loop through all to the members of the collection and check if there's a member in the tuple that's equal to the given item. Example: my_tuple = (5, 1, 8, 3, 7) print(8 in my_tuple) print(0 in my_tuple) Output: True False Python Programming : Lecture Seven Dr. Ahmed Alnasheri 27 ITERATION There are many ways to iterate through the tuple object. For statement in Python has a variant which traverses a tuple till it is exhausted. It is equivalent to for each statement in Java. Its syntax is for var in tuple: stmt1 Output: stmt2 0 10 Example: 1 20 T = (10,20,30,40,50) 2 30 3 40 for var in T: 4 50 print (T.index(var),var) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 28 BUILT-IN TUPLE FUNCTIONS Tuples support the following build-in functions: Comparison: If the elements are of the same type, python performs the comparison and returns the result. If elements are different types, it checks whether they are numbers. If numbers, perform comparison. If either the element is an number, then the other element is a returned. Otherwise, types are sorted alphabetically. If we reached to the end of one of the lists, the longer list is a "larger." If both are list are same it returns 0. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 29 BUILT-IN TUPLE FUNCTIONS Example tuple1 = ('a', 'b', 'c', 'd', 'e') tuple2 = ('1','2','3') tuple3 = ('a', 'b', 'c', 'd', 'e') cmp(tuple1, tuple2) Out: 1 cmp(tuple2, tuple1) Out: -1 cmp(tuple1, tuple3) Out: 0 Python Programming : Lecture Seven Dr. Ahmed Alnasheri 30 BUILT-IN TUPLE FUNCTIONS Tuple Length: len(tuple1) Out: 5 Max of a tuple: The function min returns the item from the tuple with the min value: min(tuple1) Out: 'a' min(tuple2) Out: '1' Convert a list into tuple: The built-in function tuple converts a list into a tuple: list = [1,2,3,4,5] tuple(list) Out: (1, 2, 3, 4, 5) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 31 DICTIONARY Lists and tuples hold elements with only integer indices 45 “Coding” 4.5 7 89 Integer 0 1 2 3 4 Indices So in essence, each element has an index (or a key) which can only be an integer, and a value which can be of any type (e.g., in the above list/tuple, the first element has key 0 and value 45) What if we want to store elements with non-integer indices (or keys)? Python Programming : Lecture Seven Dr. Ahmed Alnasheri 32 A DICTIONARY In Python, you can use a dictionary to store elements with keys of any types (not necessarily only integers like lists and tuples) and values of any types as well 45 “Coding” 4.5 7 89 “NUM” 1000 2000 3.4 “XXX” keys of different types Values of different types The above dictionary can be defined in Python as follows: dic = {"NUM":45, 1000:"coding", 2000:4.5, 3.4:7, "XXX":89} key value Each element is a key:value pair, and elements are separated by commas Python Programming : Lecture Seven Dr. Ahmed Alnasheri 33 DICTIONARY In summary, dictionaries: Can contain any and different types of elements (i.e., keys and values) Can contain only unique keys but duplicate values dic2 = {"a":1, "a":2, "b":2} Output: {'a': 2, 'b': 2} print(dic2) The element “a”:2 will override the element “a”:1 because only ONE element can have key “a” Can be indexed but only through keys (i.e., dic2[“a”] will return 1 but dic2 will return an error since there is no element with key 0 in dic2 above) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 34 DICTIONARY In summary, dictionaries: CANNOT be concatenated CANNOT be repeated Can be nested (e.g., d = {"first":{1:1}, "second":{2:"a"}} Can be passed to a function and will result in a pass-by-reference and not pass-by-value behavior since it is immutable (like lists) def func1(d): d["first"] = [1, 2, 3] Output: {'first': {1: 1}, 'second': {2: 'a'}} dic = {"first":{1:1}, {'first': [1, 2, 3], 'second': {2: 'a'}} "second":{2:"a"}} print(dic) func1(dic) print(dic) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 35 DICTIONARY In summary, dictionaries: Can be iterated over dic = {"first": 1, "second": 2, "third": 3} for i in dic: print(i) first ONLY the keys will be returned. Output: second third How to get the values? Python Programming : Lecture Seven Dr. Ahmed Alnasheri 36 CREATING A DICTIONARY In summary, dictionaries: Can be iterated over dic = {"first": 1, "second": 2, "third": 3} for i in dic: print(dic[i]) 1 Output: 2 Values can be accessed via indexing! 3 Python Programming : Lecture Seven Dr. Ahmed Alnasheri 37 Adding Elements to a Dictionary How to add elements to a dictionary? By indexing the dictionary via a key and assigning a corresponding value dic = {"first": 1, "second": 2, "third": 3} print(dic) dic["fourth"] = 4 print(dic) {'first': 1, 'second': 2, 'third': 3} Output: {'first': 1, 'second': 2, 'third': 3, 'fourth': 4} Python Programming : Lecture Seven Dr. Ahmed Alnasheri 38 Adding Elements to a Dictionary How to add elements to a dictionary? By indexing the dictionary via a key and assigning a corresponding value dic = {"first": 1, "second": 2, "third": 3} print(dic) If the key already exists, dic[”second"] = 4 the value will be overridden print(dic) {'first': 1, 'second': 2, 'third': 3} Output: {'first': 1, 'second’: 4, 'third': 3} Python Programming : Lecture Seven Dr. Ahmed Alnasheri 39 Deleting Elements to a Dictionary How to delete elements in a dictionary? By using del dic = {"first": 1, "second": 2, "third": Output: 3} print(dic) {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second': 2, 'third': 3, 'fourth': 4} dic["fourth"] = 4 {'second': 2, 'third': 3, 'fourth': 4} print(dic) del dic["first"] print(dic) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 40 Deleting Elements to a Dictionary How to delete elements in a dictionary? Or by using the function pop(key) dic = {"first": 1, "second": 2, "third": Output: 3} print(dic) {'first': 1, 'second': 2, 'third': 3} {'first': 1, 'second': 2, 'third': 3, 'fourth': 4} dic["fourth"] = 4 {'second': 2, 'third': 3, 'fourth': 4} print(dic) dic.pop(“first”) print(dic) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 41 Dictionary Functions Many other functions can also be used with dictionaries Function Description dic.clear() Removes all the elements from dictionary dic dic.copy() Returns a copy of dictionary dic dic.items() Returns a list containing a tuple for each key-value pair in dictionary dic dic.get(k) Returns the value of the specified key k from dictionary dic dic.keys() Returns a list containing all the keys of dictionary dic dic.pop(k) Removes the element with the specified key k from dictionary dic Python Programming : Lecture Seven Dr. Ahmed Alnasheri 42 Dictionary Functions Many other functions can also be used with dictionaries Function Description dic.popitem() Removes the last inserted key-value pair in dictionary dic dic.values() Returns a list of all the values in dictionary dic Python Programming : Lecture Seven Dr. Ahmed Alnasheri 43 SUMMARY Tuples: In Python, tuples are structured and accessed based on position. A Tuple is a collection of Python objects separated by commas. In some ways a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is absolute unlike lists that are variable. In Python it is an unordered collection of data values, used to store data values like a map, which unlike other data types that hold only single value as an element. Tuples are absolute lists. Elements of a list can be modified, but elements in a tuple can only be accessed, not modified. The 111 name tuple does not mean that only two values can be stored in this data structure. Dictionaries: Dictionaries in Python are structured and accessed using keys and values. Dictionaries are defined in Python with curly braces { }. Commas separate the key-value pairs that make up the dictionary. Dictionaries are made up of key and/or value pairs. In Python, tuples are organized and accessed based on position. The location of a pair of keys and values stored in a Python dictionary is unrelated. Key value is provided in the dictionary to make it more optimized. A Python dictionary is basically a hash table. In some languages, they might be mentioned to an associative arrays. They are indexed with keys, which can be any absolute type. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 44 Exercises 1. Let list = [’a’, ’b’, ’c’,’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:] 2. State the difference between lists and dictionary 3. What is the benefit of using tuple assignment in Python? 4. Define dictionary with an example 5. Write a Python program to swap two variables 6. Define Tuple and show it is immutable with an example 7. Create tuple with single element 8. How can you access elements from the dictionary 9. Write a Python program to create a tuple with different data types. 10. Write a Python program to unpack a tuple in several variables Python Programming : Lecture Seven Dr. Ahmed Alnasheri 45 REFERENCES 1. https://www.geeksforgeeks.org/differences-and-applications-of-listtuple-set-and-dictionary-in-python/ 2. https://problemsolvingwithpython.com/04-Data-Types-and- Variables/04.05-Dictionaries-and-Tuples/ 3. https://problemsolvingwithpython.com/04-Data-Types-and- Variables/04.05-Dictionaries-and-Tuples/ 4. https://ncert.nic.in/textbook/pdf/kecs110.pdf 5. https://python101.pythonlibrary.org/chapter3_lists_dicts.html 6. https://www.programmersought.com/article/26815189338/ 7. https://www.javatpoint.com/python-tuples 8. https://cloudxlab.com/assessment/displayslide/873/python- dictionaries-and-tuples 9. https://medium.com/@aitarurachel/data-structures-with-lists-tuples- dictionaries-and-sets-in-python- 612245a712af 10. https://www.w3schools.com/python/python_tuples.asp Python Programming : Lecture Seven Dr. Ahmed Alnasheri 46 PYTHON PROGRAMMING FILES AND EXCEPTIONS Unit 8: FILES AND EXCEPTIONS Python Programming : Lecture Seven Dr. Ahmed Alnasheri 1 Outline of This Lecture 8.1 Objective 8.2 Text Files 8.3 The File Object Attributes 8.4 Directories 8.5 Built-in Exceptions 8.6 Handling Exceptions 8.7 Exception with Arguments 8.8 User-defined Exceptions 8.9 Summary 8.10 Exercise 8.11 Reference Python Programming : Lecture Seven Dr. Ahmed Alnasheri 2 Lecture Objectives After reading through this chapter, you will be able to : 1. To study creation and use of read and write commands for files.in python 2. To understand how to open, write and close files in python 3. To understand how python will raise an exception. 4. To create program to catch an exception using a try/except block. 5. To study the Python errors and exceptions. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 3 Files All data that we store in lists, tuples, and dictionaries within any program are lost when the program ends These data structures are kept in volatile memory (i.e., RAM) To save data for future accesses, we can use files, which are stored on non-volatile memory (usually on disk drives) Files can contain any data type, but the easiest files to work with are those that contain text You can think of a text file as a (possibly long) string that happens to be stored on disk! Python Programming : Lecture Seven Dr. Ahmed Alnasheri 4 File Processing In addition, you can specify if the file should be handled as a binary (e.g., image) or text file "t“: This is the default value; It allows handling the file as a text file "b“: It allows handling the file as a binary fine Example: f = open("file1.txt") is equivalent to f = open("file1.txt“, “rt”) When opening a file for reading, make sure it exists, or otherwise you will get an error! Python Programming : Lecture Seven Dr. Ahmed Alnasheri 5 Reading a File The open() function returns a file object, which has a read() method for reading the content of the file f = open("file1.txt", "r") data = f.read() print(data) print(type(data)) The type of data is str, which you can parse as usual! Python Programming : Lecture Seven Dr. Ahmed Alnasheri 6 Reading a File You can also specify how many characters to return from a file using read(x), where x is the first x characters in the file f = open("file1.txt", "r") data = f.read(10) This will return the first print(data) 10 characters in the file print(type(data)) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 7 Reading a File You can also use the function readline() to read one line at a time f = open("file1.txt", "r") This file contains some information about sales str1 = f.readline() print(str1) Total sales today = QAR100,000 str2 = f.readline() print(str2) Sales from PCs = QAR70,000 print(f.readline()) This is the content of the file Python Programming : Lecture Seven Dr. Ahmed Alnasheri 8 Reading a File You can also use the function readline() to read one line at a time f = open("file1.txt", "r") This file contains some information about sales str1 = f.readline() print(str1) Total sales today = QAR100,000 str2 = f.readline() print(str2) Sales from PCs = QAR70,000 print(f.readline()) Note that the string returned by readline() will always end with a newline, hence, two newlines were produced after each sentence, one by readline() and another by print() Python Programming : Lecture Seven Dr. Ahmed Alnasheri 9 Reading a File You can also use the function readline() to read one line at a time f = open("file1.txt", "r") str1 = f.readline() print(str1, end = “”) This file contains some information about sales str2 = f.readline() Total sales today = QAR100,000 print(str2, end = “”) Sales from PCs = QAR70,000 print(f.readline(), end = “”) Only a solo newline will be generated by readline(), hence, the output on the right side Python Programming : Lecture Seven Dr. Ahmed Alnasheri 10 TEXT FILES Now we will learn about various ways to read text files in Python. The following shows how to read all texts from the readme.txt file into a string: with open('readme.txt') as f: lines = f.readlines() To read the text file in the Python, you have to follow these steps: Firstly, you have to open the text file for reading by using the open() method. Second, you have to read the text from the text file using the file read(), readline(), or readlines() method of the file object. Third, you have to close the file using the file close() method. 1) open() function The open() function has many parameters but you’ll be focusing on the first two. open(path_to_file, mode) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 11 TEXT FILES 1) open() function The open() function has many parameters but you’ll be focusing on the first two. open(path_to_file, mode) The path to the file parameter is specifies the path to the text file. If the file is in the same folder as is program, you have just need to specify the file name. Otherwise, you have need to specify the path to the file. Specify the path to the file, you have to use the forward-slash ('/') even if you are working in Windows. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 12 TEXT FILES Example: if the file is in the readme.txt stored in the sample folder as the program, you have need to specify the path to the file as c:/sample/readme.txt A mode is in the optional parameter. This is the string that is specifies the mode in which you want to open the file. The following table shows available modes for opening a text file: Mode Description 'r' Open for text file for reading text ‘w' Open a text file for writing text 'a' Open a text file for appending text Python Programming : Lecture Seven Dr. Ahmed Alnasheri 13 TEXT FILES For example: To open a file whose name is the-zen-of-python.txt stored in the same folder as the program, you use the following code: f = open('the-zen-of-python.txt','r') The open() function returns a file object which you will use to read text from a text file. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 14 TEXT FILES 2) Reading text methods: The file object provides you with three methods for reading text from a text file: read() – read all text from a file into a string. This method is useful if you have a small file and you want to manipulate the whole text of that file. readline() – read the text file line by line and return all the lines as strings. readlines() – read all the lines of the text file and return them as a list of strings. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 15 TEXT FILES 2) Reading text methods: The file object provides you with three methods for reading text from a text file: read() – read all text from a file into a string. This method is useful if you have a small file and you want to manipulate the whole text of that file. readline() – read the text file line by line and return all the lines as strings. readlines() – read all the lines of the text file and return them as a list of strings. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 16 TEXT FILES 3) close() method: The file that you open will remain open until you close it using the close() method. It’s important to close the file that is no longer in use. If you don’t close the file, the program may crash or the file would be corrupted. The following shows how to call the close() method to close the file: f.close() To close the file automatically without calling the close() method, you use the with statement like this: with open(path_to_file) as f: contents = f.readlines() In practice, you’ll use the with statement to close the file automatically Python Programming : Lecture Seven Dr. Ahmed Alnasheri 17 TEXT FILES Reading a text file examples: We’ll use the-zen-of-python.txt file for the demonstration. The following example illustrates how to use the read() method to read all the contents of the the-zen-of-python.txt file into a string: with open('the-zen-of-python.txt') as f: contents = f.read() print(contents) Output: Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 18 TEXT FILES The following example uses the readlines() method to read the text file and returns the file contents as a list of strings: lines = [] with open('the-zen-of-python.txt') as f: lines = f.readlines() count = 0 for line in lines: count += 1 print(f'line {count}: {line}') Output: line 1: Beautiful is better than ugly. line 2: Explicit is better than implicit. line 3: Simple is better than complex. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 19 THE FILE OBJECT ATTRIBUTES Once a file is opened and you have one file object, you can get various information related to that file. Here is a list of all attributes related to file object: Attribute Description file.closed Returns true if file is closed, false otherwise. file.mode Returns access mode with which file was opened. file.name Returns name of the file. file.softspace Returns false if space explicitly required with print, true otherwise. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 20 THE FILE OBJECT ATTRIBUTES Example: # Open a file fo = open(“foo.txt”, “wb”) print “Name of the file: “, fo.name print “Closed or not : “, fo.closed print “Opening mode : “, fo.mode print “Softspace flag : “, fo.softspace This produces the following result: Name of the file: foo.txt Closed or not : False Opening mode : wb Softspace flag : 0 Python Programming : Lecture Seven Dr. Ahmed Alnasheri 21 DIRECTORIES In this Python Directory Example, we will import the OS module to be able to access the methods we will apply. import os How to Get Current Python Directory? To find out which directory in python you are currently in, use the getcwd() method. os.getcwd() Output: ‘E:\Python Programming\mprog\Create’ Cwd is for current working directory in python. This returns the path of the current python directory as a string in Python. To get it as a bytes object, we use the method getcwdb(). os.getcwdb() Python Programming : Lecture Seven Dr. Ahmed Alnasheri 22 DIRECTORIES How to Create Python Directory? We can also create new python directories with the mkdir() method. It takes one argument, that is, the path of the new python directory to create. os.mkdir('Christmas Photos') os.listdir() How to Rename Python Directory?: To rename directories in python, we use the rename() method. It takes two arguments- the python directory to rename, and the new name for it. os.rename('Christmas Photos','Christmas 2017') os.listdir() Python Programming : Lecture Seven Dr. Ahmed Alnasheri 23 BUILT-IN EXCEPTIONS Illegal operations can raise exceptions. There are plenty of built-in exceptions in Python that are raised when corresponding errors occur. We can view all the built-in exceptions using the built-in local() function as print(dir(locals()['__builtins__'])) follows: locals()['__builtins__'] will return a module of built-in exceptions, functions, and attributes. dir allows us to list these attributes as strings. Some of the common built-in exceptions in Python programming along with the error that cause them are listed below: Python Programming : Lecture Seven Dr. Ahmed Alnasheri 24 BUILT-IN EXCEPTIONS Python Programming : Lecture Seven Dr. Ahmed Alnasheri 25 HANDLING EXCEPTIONS If you have some suspicious code that may raise an exception, you can defend your program by placing the suspicious code in a try: block. After the try: block, include an except: statement, followed by a block of code which handles the problem as elegantly as possible. Syntax: Here is simple syntax of try....except...else blocks: try: You do your operations here;...................... except ExceptionI: If there is ExceptionI, then execute this block. except ExceptionII: If there is ExceptionII, then execute this block....................... else: If there is no exception then execute this block. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 26 HANDLING EXCEPTIONS A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions. You can also provide a generic except clause, which handles any exception. After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception. The else-block is a good place for code that does not need the try: block's protection. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 27 HANDLING EXCEPTIONS try: # Code that may raise an exception #... except ExceptionType1: # Code to handle ExceptionType1 #... except ExceptionType2: # Code to handle ExceptionType2 #... except: # Code to handle any other exception #... else: # Code to execute if no exception is raised #... finally: # Code that always executes, regardless of whether an exception is raised or not #... Python Programming : Lecture Seven Dr. Ahmed Alnasheri 28 HANDLING EXCEPTIONS Example: This example opens a file, writes content in the, file and comes out gracefully because there is no problem at all: try: fh = open("testfile", "w") fh.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find file or read data" else: print "Written content in the file successfully" fh.close() This produces the following result: Written content in the file successfully Python Programming : Lecture Seven Dr. Ahmed Alnasheri 29 EXCEPTION WITH ARGUMENTS Why use Argument in Exceptions? Using arguments for Exceptions in Python is useful for the following reasons: It can be used to gain additional information about the error encountered. As contents of an Argument can vary depending upon different types of Exceptions in Python, Variables can be supplied to the Exceptions to capture the essence of the encountered errors. Same error can occur of different causes, Arguments helps us identify the specific cause for an error using the except clause. It can also be used to trap multiple exceptions, by using a variable to follow the tuple of Exceptions. Arguments in Buil-in Exceptions: The below codes demonstrates use of Argument with Built-in Exceptions: Python Programming : Lecture Seven Dr. Ahmed Alnasheri 30 EXCEPTION WITH ARGUMENTS Example 1: try: b = float(100 + 50 / 0) except Exception as Argument: print( 'This is the Argument\n', Argument) Output: This is the Argument division by zero Python Programming : Lecture Seven Dr. Ahmed Alnasheri 31 EXCEPTION WITH ARGUMENTS Arguments in User-defined Exceptions: The below codes demonstrates use of Argument with User-defined Exceptions: Example 1: # create user-defined exception # derived from super class Exception class MyError(Exception): # Constructor or Initializer def __init__(self, value): self.value = value # __str__ is to print() the value def __str__(self): return(repr(self.value)) try: raise(MyError("Some Error Data")) # Value of Exception is stored in error except MyError as Argument: print('This is the Argument\n', Argument) Output: 'This is the Argument 'Some Error data' Python Programming : Lecture Seven Dr. Ahmed Alnasheri 32 USER-DEFINED EXCEPTIONS Creating User-defined Exception Programmers may name their own exceptions by creating a new exception class. Exceptions need to be derived from the Exception class, either directly or indirectly. Although not mandatory, most of the exceptions are named as names that end in “Error” similar to naming of the standard exceptions in python. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 33 USER-DEFINED EXCEPTIONS For example: # A python program to create user-defined exception # class MyError is derived from super class Exception class MyError(Exception): # Constructor or Initializer def __init__(self, value) self.value = value # __str__ is to print() the value def __str__(self): return(repr(self.value)) try: raise(MyError(3*2)) # Value of Exception is stored in error except MyError as error: print('A New Exception occured: ',error.value) Python Programming : Lecture Seven Dr. Ahmed Alnasheri 34 SUMMARY Files: Python supports file handling and allows users to handle files for example, to read and write files, along with many other file handling options, to operate on files. The concept of file handling has justified by various other languages, but the implementation is either difficult. Python delights file differently as text or binary and this is significant. Each line of code includes a sequence of characters and they form text file. Each line of a file is ended with a special character like comma {,}. It ends the current line and expresses the interpreter a new one has started. In Python a file is a contiguous set of bytes used to store data. This data is organized in a precise format and can be anything as simple as a text file. In the end, these byte files are then translated into binary 1 and 0 for simple for processing. In Python, a file operation takes place in the order like Open a file then Read or write and finally close the file. Exceptions: Python provides two important features to handle any unexpected error in Python programs and to add debugging capabilities in them.In Python, all exceptions must be occurrences of a class that arises from BaseException. In a try statement with an except clause that references a particular class, that clause further handles any exception classes derived from that class.Two exception classes that are not connected via sub classing are never equal, even if they have the same name. User code can advance built-in exceptions. This can be used to test an exception handler and also to report an error condition. Python Programming : Lecture Seven Dr. Ahmed Alnasheri 35 Exercises 1. Write a Python program to read an entire text file 2. Write a Python program to append text to a file and display the text 3. Write a Python program to read a file line by line store it into a variable 4. Write a Python program to count the number of lines in a text file 5. Write a Python program to write a list to a file 6. Write a Python program to extract characters from various text files and puts them into a list. 7. What are exceptions in Python? 8. When would you not use try-except? 9. When will the else part of try-except-else be executed? 10. How can one block of except statements handle multiple exception?... Python Programming : Lecture Seven Dr. Ahmed Alnasheri 36 REFERENCES 1. https://www.learnpython.org/ 2. https://www.packtpub.com/tech/python 3. https://www.softcover.io/read/e4cd0fd9/conversational- python/ch6_files_excepts 4. https://docs.python.org/3/library/exceptions.html 5. https://www.tutorialspoint.com/python/python_exceptions.htm 6. https://www.w3schools.com/python/python_try_except.asp 7. https://www.geeksforgeeks.org/python-exception-handling/ 8. https://www.analyticsvidhya.com/blog/2020/04/exception-handling- python/ 9. https://www.programiz.com/python-programming/file-operation 10. https://www.geeksforgeeks.org/file-handling-python/ 11. https://realpython.com/read-write-files-python/ 12. https://www.guru99.com/reading-and-writing-files-in-python.html Python Programming : Lecture Seven Dr. Ahmed Alnasheri 37 PYTHON PROGRAMMING PYTHON FOR DATA ANALYSIS Unit 9: Python for Data Analysis Python Programming : Lecture Nine Dr. Ahmed Alnasheri 1 Outline of This Lecture 9.1 Objective 9.2 Introduction to Data Analysis with Python 9.2.1 Understanding the role of Python in data analysis 9.2.2 Overview of popular Python libraries for data analysis (e.g., NumPy, Pandas, Matplotlib, Seaborn) 9.2.3 Data Manipulation with NumPy 9.3 Reading Data; Selecting and Filtering the Data; Data manipulation, sorting, grouping, rearranging 9.4 Plotting the data 9.5 Descriptive statistics 9.6 Inferential statistics 8.9 Summary 8.10 Exercise 8.11 Reference Python Programming : Lecture Nine Dr. Ahmed Alnasheri 2 Lecture Objectives After reading through this chapter, you will be able to : 1. Understand the fundamental concepts and techniques of data analysis using Python. 2. Gain proficiency in using key Python libraries for data analysis, such as NumPy, Pandas, Matplotlib, and Seaborn. 3. Learn how to manipulate, clean, and preprocess data using Pandas, including handling missing data and data cleaning techniques. 4. Develop skills in visualizing data effectively using Matplotlib and Seaborn, including creating various types of plots and customizing visualizations. Python Programming : Lecture Nine Dr. Ahmed Alnasheri 3 Role of Python in Data Analysis Python plays a crucial role in data analysis due to its wide range of powerful libraries and tools specifically designed for working with data. Here are some key aspects of Python's role in data analysis: Data Manipulation: Python provides libraries like NumPy and Pandas, which offer efficient data structures and functions for handling and manipulating large datasets. These libraries enable tasks such as data cleaning, filtering, sorting, merging, reshaping, and aggregation. Data Visualization: Python offers libraries such as Matplotlib and Seaborn that allow users to create a variety of high- quality visualizations, including line plots, scatter plots, bar plots, histograms, heatmaps, and more. These libraries provide customization options for creating visually appealing and informative plots. Statistical Analysis: Python provides libraries like SciPy and Statsmodels that offer a wide range of statistical functions, probability distributions, hypothesis tests, and regression models. These libraries enable users to perform statistical analysis and make data-driven decisions. Python Programming : Lecture Nine Dr. Ahmed Alnasheri 4 Role of Python in Data Analysis Here are some key aspects of Python's role in data analysis: Machine Learning: Python has become a popular language for machine learning due to libraries like Scikit-learn, TensorFlow, and PyTorch. These libraries provide implementations of various machine learning algorithms and tools for tasks such as classification, regression, clustering, and model evaluation. Integration and Ecosystem: Python has a vast ecosystem of libraries and tools that seamlessly integrate with each other. This allows data analysts to leverage specialized libraries for specific tasks, such as natural language processing (NLTK), network analysis (NetworkX), and geospatial analysis (GeoPandas). Additionally, Python integrates well with other data-related technologies and databases, making it a versatile choice for data analysis workflows. Accessibility and Community Support: Python is known for its simplicity and readability, making it accessible to beginners and experienced programmers alike. It has a large and active community of users who contribute to its development and provide support through forums, tutorials, and open-source projects. This community-driven nature ensures that there are abundant resources available for learning and problem-solving. Python Programming : Lecture Nine Dr. Ahmed Alnasheri 5 Python Libraries for Data Analysis Many popular Python toolboxes/libraries: NumPy SciPy Pandas All these libraries are installed on YOUR Computer SciKit-Learn Visualization libraries matplotlib Seaborn and many more … Python Programming : Lecture Nine Dr. Ahmed Alnasheri 6 Python Libraries for Data Analysis NumPy:  introduces objects for multidimensional arrays and matrices, as well as functions that allow to easily perform advanced mathematical and statistical operations on those objects  provides vectorization of mathematical operations on arrays and matrices which significantly improves the performance  NumPy is a fundamental library for numerical computing in Python.  NumPy is the foundation for many other data analysis libraries in Python. Link: http://www.numpy.org/ Python Programming : Lecture Nine Dr. Ahmed Alnasheri 7 Python Libraries for Data Analysis SciPy:  collection of algorithms for linear algebra, differential equations, numerical integration, optimization, statistics and more  part of SciPy Stack  built on NumPy  provides additional functionality for scientific computing and advanced mathematics. It includes modules for optimization, integration, interpolation, signal processing, linear algebra, and more.  SciPy complements NumPy and provides a rich set of tools for scientific analysis and modeling. Link: https://www.scipy.org/scipylib/ Python Programming : Lecture Nine Dr. Ahmed Alnasheri 8 Python Libraries for Data Analysis Pandas:  adds data structures and tools designed to work with table-like data (similar to Series and Data Frames in R Language)  It introduces two primary data structures: Series and DataFrame.  provides tools for data manipulation: reshaping, merging, sorting, slicing, aggregation etc.  Pandas prov

Use Quizgecko on...
Browser
Browser