Looking for a Tutor Near You?

Post Learning Requirement » x
Ask a Question
x
x

Direction

x

Ask a Question

x

Hire a Tutor

Note On Python

In detail material

Nasvi K / Al Ain

5 years of teaching experience

Qualification: Post Graduate in Engineering

Teaches: Biology, Chemistry, Computer Science, Physics, Maths, ICT Training, MS Office, Python Programming, Programming Technology, Mathematics

Contact this Tutor
  1. Python Tutorial What is Python? Python is a popular programming language. It was created by Guido van Rossum, and released in 1991. It is used for: web development (server-side), software development, mathematics, system scripting. What can Python do? Python can be used on a server to create web applications. Python can be used alongside software to create workflows. Python can connect to database systems. It can also read and modify files. Python can be used to handle big data and perform complex mathematics. Python can be used for rapid prototyping, or for production-ready software development. Why Python? Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). Python has a simple syntax similar to the English language. Python has syntax that allows developers to write programs with fewer lines than some other programming languages. Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. Python can be treated in a procedural way, an object-oriented way or a functional way. Good to know • The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular.
  2. In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files. Python Syntax compared to other programming languages Python was designed for readability, and has some similarities to the English language with influence from mathematics. Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses. Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose. Python Comments Comments can be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code. Creating a Comment Comments starts with a #, and Python will ignore them: #This is a comment print("Hello, World! ") Comments can be placed at the end of a line, and Python will ignore the rest of the line: print("He110, World!") #This is a comment Multiline Python Comment We must use the hash(#) at the beginning of every line of code to apply the multiline Python comment. Consider the following example. 1. 2. 3. # First line Of the comment # Second line Of the comment # Third line of the comment
  3. Example: # Variable a holds value 5 # Variable b holds value 10 # Variable c holds sum Of a and b # Print the result b = 10 c = a+b print("The sum is:", c) Output: The sum is: 15 The above code is very readable even the absolute beginners can under that what is happening in each line of the code. This is the advantage of using comments in code. We can also use the triple quotes (""") for multiline comment. The triple quotes are also used to string formatting. Consider the following example. Docstrings Python Comment The docstring comment is mostly used in the module, function, class or method. It is a documentation Python string. We will explain the class/method in further tutorials. Example: def intro(): This function prints Hello Joseph print("Hi Joseph intro() Output: Hello Joseph We can check a function's docstring by using the doc attribute.
  4. Generally, four whitespaces are used as the indentation. The amount of indentation depends on user, but it must be consistent throughout that block. 1. 2. 3. 4. 5. 6. def intro(): This function prints Hello Joseph print("Hello Joseph") intro. doc Output: Output: This function prints Hello Joseph\n Note: The docstring must be the first thing in the function; otherwise, Python interpreter cannot get the docstring. Python indentation Python indentation uses to define the block of the code. The other programming languages such as C, C++, and Java use curly braces {}, whereas Python uses an indentation. Whitespaces are used as indentation in Python. Indentation uses at the beginning of the code and ends with the unintended line. That same line indentation defines the block of the code (body of a function, loop, etc.) Generally, four whitespaces are used as the indentation. The amount of indentation depends on user, but it must be consistent throughout that block. for i in range(5): print(i) if(i 3): break To indicate a block of code we indented each line of the block by the same whitespaces. Consider the following example. dn = int(input("Enter the number:"))
  5. print("Even Number") else: print("Odd Number") 1. 2. print("Task Complete") Output: Enter the number: 10 Even Number Task Complete The above code, if and else are two separate code blocks. Both code blocks are indented four spaces. The print("Task Complete") statement is not indented four whitespaces and it is out of the if-else block. If the indentation is not used properly, then that will result in IndentationError. Variables Variables are containers for storing data values Creating Variables Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Y = "John" print(x) print(y) Variables do not need to be declared with any particular type, and can even change type after they have been set. x = 4 # x is of type int x = "Sally" # x is now of type str print(x)
  6. Variable Names A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables: A variable name must start with a letter or the underscore character A variable name cannot start with a number A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case-sensitive (age, Age and AGE are three different variables) Example Legal variable names: myvar = "John" my var = "John" my_var = "John" myVar = "John" MYVAR = "John" Many Values to Multiple Variables Python allows you to assign values to multiple variables in one line: Example x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) Output Variables The Python print statement is often used to output variables. To combine both text and a variable, Python uses the + character: x = "awesome" print("Python is " + x) You can also use the + character to add a variable to another variable:
  7. x = "Python is " y "awesome" print(z) Python Data Types Built-in Data Types In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories: Text Type: Numeric Types: Sequence Types: Mapping Type: Set Types: Boolean Type: Binary Types: Getting the Data Type int, float, complex list, tuple, range dict set, frozenset bool bytes, bytearray, memoryview You can get the data type of any object by using the type() function: print(type(x)) Python Numbers There are three numeric types in Python: int
  8. float complex Variables Of numeric types are created when you assign a value to them: x = 1 # int Y = 2.8 # float z = Ij # complex To verify the type of any object in Python, use the type() function: print(type(x)) print(type(y)) print(type(z)) Specify a Variable Type There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types. Casting in python is therefore done using constructor functions: int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number) float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer) str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals Strings Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello". You can display a string literal with the print() function: print("Hello") print('Hello') Assign String to a Variable
  9. Assigning a string to a variable is done with the variable name followed by an equal sign and the string: a = "Hello" print(a) Slicing You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part Of the string. b = "Hello, World!" print(b[2:5]) Python has a set of built-in methods that you can use on strings. Upper Case Example The upper() method returns the string in upper case: a = "Hello, World!" print(a.upper()) Lower Case Example The lower() method returns the string in lower case: a = "Hello, World!" print(a.lower()) Remove Whitespace
  10. Whitespace is the space before and/or after the actual text, and very often you want to remove this space. Example The strip() method removes any whitespace from the beginning or the end: Hello, World! " print(a.strip()) # returns "Hello, World!" Replace String The replace() method replaces a string with another string: a = "Hello, World!" print(a.replace("H", "J")) Split String The split() method returns a list where the text between the specified separator becomes the list items. a = "Hello, World!" print(a.split(",")) # returns ['Hello', ' World!'] String Concatenation To concatenate, or combine, two strings you can use the + operator. Merge variable a with variable b into variable c: a = "Hello" b = "World" print(c) TO add a space between them, add a ' a = "Hello" b = "World" print(c) String Format
  11. As we learned in the Python Variables chapter, we cannot combine strings and numbers like this: age = 36 txt = "My name is John, I am " + age print(txt) But we can combine strings and numbers by using the format() method! The format() method takes the passed arguments, formats them, and places them in the string where the placeholders O are: Use the format() method to insert numbers into strings: age = 36 txt = "My name is John, and I am O" print(txt.format(age)) Python List A list in Python is used to store the sequence of various types of data. Python lists are mutable type its mean we can modify its element after it created. However, Python consists of six data- types that are capable to store the sequences, but the most common and reliable type is the list. A list can be defined as a collection of values or items of different types. The items in the list are separated with the comma (,) and enclosed with the square brackets [l. A list can be define as below 1. Ll = ["John", 102, "USA"] llf we try to print the type of LI, L2, and L3 using type() function then it will come out to be a list. Skip Ad 1. print(type(L1)) 2. print(type(L2)) Output: <class 'list'> <class 'list'>
  12. Characteristics of Lists The list has the following characteristics: The lists are ordered. The element of the list can access by index. The lists are the mutable type. The lists are mutable types. A list can store the number of various elements. Let's check the first statement that lists are the ordered. Output: False Both lists have consisted of the same elements, but the second list changed the index position Of the 5th element that violates the order Of lists. When compare both lists it returns the false. Lists maintain the order Of the element for the lifetime. That's why it is the ordered collection of objects. 1. a = [1, 2,"Peter", 2. b = [1, 2,"Peter", Output: True 4.50, 6] Let's have a look at the list example in detail. 1. 2. 3. 4. 5. 6. emp = ["John", 102, "USA"] Depl = Dep2 = HOD_CS = Holding"] HOD_IT = [11, "Mr. Bewon"] print("printing employee data...")
  13. 7. 8. 9. print("Name : %s, ID: %d, Country: %s"%(emp[O],emp[1],emp[2])) print("printing departments... ") print("Department 1:\nName: ID: %d\nDepartment 2:\nName: %s, ID: %s"%(Dep1[O 10. print("HOD Details 11. HOD Name: Id: 12. HOD Name: Id: IT[O])) 13. print(type(emp),type(Dep1),type(Dep2),type(HOD CS),type(HOD IT)) Output: printing employee data... Name : John, ID: 102, Country: USA printing departments. Department 1: Name: CS, ID: 11 Department 2: Name: IT, ID: 11 HOD Details CS HOD Name: Mr. Holding, 'd: 10 IT HOD Name: Mr. Bewon, Id: 11 <class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'> In the above example, we have created the lists which consist of the employee and department details and printed the corresponding details. Observe the above code to understand the concept of the list better. List indexing and splitting The indexing is processed in the same way as it happens with the strings. The elements of the list can be accessed by using the slice operator [l. The index starts from O and goes to length - 1. The first element of the list is stored at the 0th index, the second element of the list is stored at the 1st index, and so on.
  14. List = 1 o List[0] = O List[l] = 1 List[2] = 2 List[3] = 3 List[4] = 4 List[5] = 5 2 3 List[0:] = List[ ] = LISt[ 4] = 4 5 We can get the sub-list of the list using the following syntax. 1. list_varible(start:stop:step) The start denotes the starting index position of the list. The stop denotes the last index position of the list. The step is used to skip the nth element within a start:stop Consider the following example: 1. 2. 3. 4. 5. 6. 7. 8. list = print(list[O]) print(list[l]) print(list[2]) print(list[3]) # Slicing the elements print(Iist[O:6]) # By default the index value is O so its starts from the 0th element and go for index -1.
  15. 9. print(list[:]) 10. print(list[2:5]) 11. print(list[1:6:2]) Output: 1 2 3 4 Unlike other languages, Python provides the flexibility to use the negative indexing also. The negative indices are counted from the right. The last element (rightmost) of the list has the index -1; its adjacent left element is present at the index -2 and so on until the left-most elements are encountered. Forward Direction O o -6 List = [0, 1, 2, 3, 4, 5] 1 1 -5 2 2 -4 3 3 -3 4 4 -2 5 5 Backward Direction Let's have a look at the following example where we will use negative indexing to access the elements of the list. 1. 2. 3. 4. 5. list = print(list[-l]) print(Iist[-3:]) print(list[:-l]) print(list[-3:-1]) Output: 5
  16. As we discussed above, we can get an element by using negative indexing. In the above code, the first print statement returned the rightmost element of the list. The second print statement returned the sub-list, and so on. Updating List values Lists are the most versatile data structures in Python since they are mutable, and their values can be updated by using the slice and assignment operator. Python also provides append() and insert() methods, which can be used to add values to the list. Consider the following example to update the values inside the list. 1. list = [1, 2, 3, 4, 5, 6] print(list) 2. 3. # It will assign value to the value to the second index 4. list[2] = 10 print(list) 5. 6. # Adding multiple-element 7. = [89, 78] print(list) 8. 9. # It will add value at the end of the list 10. list[-l] = 25 11. print(list) Output: [1, 2, 10, 4, 5, 6] [1, 89, 78, 4, 5, 6] [1, 89, 78, 4, 5, 25] The list elements can also be deleted by using the del keyword. Python also provides us the remove() method if we do not know which element is to be deleted from the list.
  17. Consider the following example to delete the list elements. 1. list = [1, 2, 3, 4, 5, 6] print(list) 2. 3. # It will assign value to the value to second index 4. list[2] = 10 print(list) 5. 6. # Adding multiple element 7. = [89, 78] print(list) 8. 9. # It will add value at the end of the list 10. list[-l] = 25 11. print(list) Output: [1, 2, 10, 4, 5, 6] [1, 89, 78, 4, 5, 6] [1, 89, 78, 4, 5, 25] Python List Operations The concatenation (+) and repetition ( * ) operators work in the same way as they were working with the strings. Let's see how the list responds to various operators. 1. Consider a Lists Il = [1, 2, 3, 4], and 12 = [5, 6, 7, 8] to perform operation. Operator Description Repetition The repetition operator enables the list elements to be repeated multiple times. Concatenation It concatenates the list mentioned on either side of the operator. Example 11+12 = [1, 2, 3, 4, 5, 6, 7, 8]
  18. Membership Iteration Length Iterating a List It returns true if a particular item exists in a particular list otherwise false. The for loop is used to iterate over the list elements. It is used to get the length of the list print(2 in Il) prints True. for i in Il: print(i) Output 1 2 3 4 len(ll) = 4 A list can be iterated by using a for - in loop. A simple list containing four strings, which can be iterated as follows. 1. 2. 3. 4. list = ["John", "David", "James", "Jonathan"] for i in list: # The i variable will iterate over the elements of the List and contains each element in each iteration. print(i) Output: John David James Jonathan Adding elements to the list Python provides append() function which is used to add an element to the list. However, the append() function can only add value to the end of the list. Consider the following example in which, we are taking the elements of the list from the user and printing the list on the console. 1. #Declaring the empty list
  19. 3. #Number of elements will be entered by the user n = int(input("Enter the number of elements in the list:")) 4. 5. # for loop to take the input for i in range(O,n): 6. 7. # The input is taken from the user and added to the list as the item Lappend(input("Enter the item:")) 8. print("printing the list items..") 9. 10. # traversal loop to print the list items 11. for i in l: print(i, end = " 12. Output: Enter the number Of elements in the list:5 Enter the item:25 Enter the item:46 Enter the item:12 Enter the item:75 Enter the item:42 printing the list items 25 46 12 75 42 Removing elements from the list Python provides the remove() function which is used to remove the element from the list. Consider the following example to understand this concept. Example - 1. 2. 3. 4. 5. list = print("printing original list: "), for i in list: print(i,end=" ") list.remove(2)
  20. 6. 7. 8. print("\nprinting the list after the removal Of first element...") for i in list: print(i,end=" Output: printing original list: 01234 printing the list after the removal of first element... 0134 Python List Built-in functions Python provides the following built-in functions, which can be used with the lists. SN Function 1 2 3 4 5 cmp(listl, list2) len(list) max(list) min(list) list(seq) Description It compares the elements of both the lists. It is used to calculate the length of the list. It returns the maximum element of the list. It returns the minimum element of the list. It converts any sequence to the list. Example This method is not used in the Python 3 and the above versions. print(len(L1)) 8 Ll = print(max(L1)) 72 print(min(L1)) 12 str = "Johnson" S = list(str) print(type(s))
  21. <class list> Let's have a look at the few list examples. Example: 1- Write the program to remove the duplicate element of the list. 1. 2. 3. 4. 5. 6. 7. listl = # Declare an empty list that will store unique values list2 = [l for i in listl: if i not in list2: list2.append(i) print(Iist2) Output: [1, 2, 3, 55, 98, 65, 13, 29] Example:2- Write a program to find the sum of the element in the list. 1. 2. 3. 4. 5. listl = sum = O for i in listl: sum = sum+i print("The sum is:",sum) Output: The sum is: 67 Example: 3- Write the program to find the lists consist of at least one common element. 1. 2. 3. 4. 5. 6. listl = list2 = for x in listl: for y in list2: if x Y: print("The common element is:",x) Output:
  22. The common element is: 2 Python Tuple Python Tuple is used to store the sequence of immutable Python objects. The tuple is similar to lists since the value of the items stored in the list can be changed, whereas the tuple is immutable, and the value of the items stored in the tuple cannot be changed. Creating a tuple A tuple can be written as the collection of comma-separated (,) values enclosed with the small ( ) brackets. The parentheses are optional but it is good practice to use. A tuple can be defined as follows. 1. 2. 3. 4. 5. 6. 7. Tl = (101, "Peter", 22) T2 = ("Apple", "Banana", "Orange") T3 = print(type(T1)) print(type(T2)) print(type(T3)) Output: <class 'tuple'> <class 'tuple'> <class 'tuple'> Note: The tuple which is created without using parentheses is also known as tuple packing. An empty tuple can be created as follows. Creating a tuple with single element is slightly different. We will need to put comma after the element to declare the tuple. 1. 2. 3. 4. tupl = ("JavaTpoint") print(type(tupl)) #Creating a tuple with single element tup2 = ("JavaTpoint",)
  23. 5. print(type(tup2)) Output: <class 'str'> <class 'tuple'> A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by using their specific index value. Consider the following example of tuple: Example - 1 tuplel = (10, 20, 30, 40, 50, 60) 1. print(tuplel) 2. 3. count = O 4. for i in tuplel: print("tuplel[%d] = %d"%(count, i)) 5. 6. count = count+l Output: (10, 20, 30, 40, 50, 60) tuple1[O] = 10 tuplel[l] = 20 tuple1[2] = 30 tuple1[3] = 40 tuple1[4] = 50 tuple1[5] = 60 Example - 2 print("tuplel[%d] = %s"%(count, i)) 1. 2. 3. 4. 5. 6. tuplel = tuple(input("Enter the tuple elements ...")) print(tuplel) count = O for i in tuplel: count = count+l
  24. Output: Enter the tuple elements tuple1[O] = 1 tuplel[l] = 2 tuple1[2] = 3 tuple1[3] = 4 tuple1[4] = 5 tuple1[5] 6 .123456 A tuple is indexed in the same way as the lists. The items in the tuple can be accessed by using their specific index value. We will see all these aspects of tuple in this section of the tutorial. Tuple indexing and slicing The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts from O and goes to length(tuple) - 1. The items in the tuple can be accessed by using the index [] operator. Python also allows us to use the colon operator to access multiple items in the tuple. Consider the following image to understand the indexing and slicing in detail.
  25. ???'? = (0, 1, 2, ?, 4, 5) ? 1 ???'?[0] = ? ???'?[1] = 1 ???'?[2] = 2 ???'?[?] = ? ???1?[4] = 4 ???'?[5] = 5 2 ? 4 5 ???'?[0:] = (0, 1, 2, ?, 4, 5) ???'?[ ] = ???'?[2 4] = ???'?[ 4] = Consider the following ?????'?: 1. 2. 3. 4. 5. ?. tup = print(tup[O]) print(tup[1]) print(tup[2]) # lt will give the IndexError print(tup[8]) 0utput: 1 2 ? tup'e index out 0f range '? the above code, the tuple has 7 elements which denote ? to ?. We tried to access ?? element outside 0f tuple that raised ?? IndexError.
  26. 1. 2. 3. 4. 5. 6. 7. 8. 9. tuple = (1,2,3,4,5,6,7) #element 1 to end print(tuple[l:]) #element O to 3 element #element 1 to 4 element print(tuple[1:5]) # element O to 6 and take step Of 2 print(tuple[O:6:2]) Output: Negative Indexing The tuple element can also access by using negative indexing. The index Of -1 denotes the rightmost element and -2 to the second last item and so on. The elements from left to right are traversed using the negative indexing. Consider the following example: 1. 2. 3. 4. 5. 6. tuplel = (1, 2, 3, 4, 5) print(tuplel[-l]) print(tuple1[-3:-1]) print(tuplel[:-l]) print(tuple1[-2:]) Output: 5 2
  27. Deleting Tuple Unlike lists, the tuple items cannot be deleted by using the del keyword as tuples are immutable. TO delete an entire tuple, we can use the del keyword with the tuple name. Consider the following example. 1. 2. 3. 4. 5. 6. tuplel = (1, 2, 3, 4, 5, 6) print(tuplel) del tuple1[O] print(tuplel) del tuplel print(tuplel) Output: Traceback (most recent call last): File "tuple.py", line 4, in print(tuplel) NameError: name 'tuplel' is not defined Basic Tuple operations The operators like concatenation repetition (*), Membership (in) works in the same way as they work with the list. Consider the following table for more detail. Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple tl = (6, 7, 8, 9) are declared. Operator Repetition Concatenation Description The repetition operator enables the tuple elements to be repeated multiple times. It concatenates the tuple mentioned on either side of the operator. Example Tl*2 = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5) Tl+T2 (1, 2, 3, 4, 5, 6, 7, 8, 9)
  28. Membership Iteration Length It returns true if a particular item exists in the tuple otherwise false The for loop is used to iterate over the tuple elements. It is used to get the length of the tuple. print (2 in T 1) prints True. for i in T 1: print(i) Output 1 2 3 4 5 len(T1) 5 Python Tuple inbuilt functions SN 1 2 3 4 5 Function cmp(tuplel, tuple2) len(tuple) max(tuple) min(tuple) tuple(seq) Description It compares two tuples and returns true if tuplel is greater than tuple2 otherwise false. It calculates the length of the tuple. It returns the maximum element of the tuple It returns the minimum element of the tuple. It converts the specified sequence to the tuple. Where use tuple? Using tuple instead of list is used in the following scenario. 1. Using tuple instead of list gives us a clear idea that tuple data is constant and must not be changed.
  29. 2. Tuple can simulate a dictionary without keys. Consider the following nested structure, which can be used as a dictionary. 1. [(101, "John", 22), (102, "Mike", 28), (103, "Dustin", 30)] List vs. Tuple SN 1 2 3 4 5 6 List The literal syntax Of list is shown by the The List is mutable. The List has the a variable length. The list provides more functionality than a tuple. The list is used in the scenario in which we need to store the simple collections with no constraints where the value of the items can be changed. The lists are less memory efficient than a tuple. Tuple The literal syntax of the tuple is shown by the (). The tuple is immutable. The tuple has the fixed length. The tuple provides less functionality than the list. The tuple is used in the cases where we need to store the read-only collections i.e., the value of the items cannot be changed. It can be used as the key inside the dictionary. The tuples are more memory efficient because of its immutability. Python Dictionary Python Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in Python, which can simulate the real-life data arrangement where some specific value exists for some particular key. It is the mutable data-structure. The dictionary is defined into element Keys and values. Keys must be a single element Value can be any type such as list, tuple, integer, etc. In other words, we can say that a dictionary is the collection of key-value pairs where the value can be any Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string, or tuple.
  30. Creating the dictionary The dictionary can be created by using multiple key-value pairs enclosed with the curly brackets f}, and each key is separated from its value by the colon (:).The syntax to define the dictionary is given below. Syntax: Dict = {"Name": "Tom", "Age": 22} In the above dictionary Dict, The keys Name and Age are the string that is an immutable object. Let's see an example to create a dictionary and print its content. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"} print(type(Employee)) print("printing Employee data ") print(Employee) Output <class 'dict'> Printing Employee data {'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'} Python provides the built-in function dict() method which is also used to create dictionary. The empty curly braces {} is used to create empty dictionary. # Creating an empty Dictionary Dict = {Y print("Empty Dictionary: ") print(Dict) # Creating a Dictionary # with dict() method Dict = dict({l: 'Java', 2: 'T', 3:'Point'}) print("\nCreate Dictionary by using dict(): ") print(Dict) # Creating a Dictionary
  31. # with each item as a Pair Dict = dict([(l, 'Devansh'), (2, 'Sharma')]) print("\nDictionary with each item as a pair: " print(Dict) Output: Empty Dictionary: Create Dictionary by using dict(): {1: 'Java', 2: 'T', 3: 'Point'} Dictionary with each item as a pair: {1: 'Devansh', 2: 'Sharma'} Accessing the dictionary values We have discussed how the data can be accessed in the list and tuple by using the indexing. However, the values can be accessed in the dictionary by using the keys as keys are unique in the dictionary. The dictionary values can be accessed in the following way. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company . "•"GOOGLE"} print(type(Employee)) print("printing Employee data ") print("Name : %s" print("Age : %d" %Employee["Age"]) print("Company : %s" %Employee["Company"]) Output: <class 'dict'> printing Employee data Name : John
  32. Age : 29 salary : 25000 Company : GOOGLE Python provides us with an alternative to use the get() method to access the dictionary values. It would give the same result as given by the indexing. Adding dictionary values The dictionary is a mutable data type, and its values can be updated by using the specific keys. The value can be updated along with key Dict[key] = value. The update() method is also used to update an existing value. Note: If the key-value already present in the dictionary, the value gets updated. Otherwise, the new keys added in the dictionary. Let's see an example to update the dictionary values. Example - 1: # Creating an empty Dictionary Dict = {Y print("Empty Dictionary: ") print(Dict) # Adding elements to dictionary one at a time Dict[O] = 'Peter' Dict[2] = 'Joseph' Dict[3] = 'Ricky' print("\nDictionary after adding 3 elements: ") print(Dict) # Adding set Of values # with a single Key # The Emp ages doesn't exist to dictionary Dict['Emp_ages'] = 20, 33, 24 print("\nDictionary after adding 3 elements: ")
  33. print(Dict) # Updating existing Key's Value Dict[3] - — 'JavaTpoint' print("\nUpdated key value: print(Dict) Output: Empty Dictionary: Dictionary after adding 3 elements: {O: 'Peter', 2: 'Joseph', 3: 'Ricky'} Dictionary after adding 3 elements: {O: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)} Updated key value: {O: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', Example - 2: 'Emp_ages': (20, 33, 24)} Employee = {"Name": "John", "Age": 29, "salary":25000,"Company . 1. 2. 3. 4. 5. 6. 7. 8. 9. " • "GOOGLE"} print(type(Employee)) print("printing Employee data print(Employee) print("Enter the details of the new employee...." Employee["Name"] = input("Name: Employee["Age"] = int(input("Age: ")); Employee["salary"] = int(input("Salary: ")); Employee["Company"] = input("Company:");
  34. 10. print("printing the new data"); 11. print(Employee) Output: Empty Dictionary: Dictionary after adding 3 elements: {O: 'Peter', 2: 'Joseph', 3: 'Ricky'} Dictionary after adding 3 elements: {O: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33, 24)} Updated key value: {O: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages': (20, 33, 24)} Deleting elements using del keyword The items of the dictionary can be deleted by using the del keyword as given below. 1. 2. 3. 4. 5. 6. 7. 8. 9. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"} print(type(Employee)) print("printing Employee data ") print(Employee) print("Deleting some of the employee data") del Employee["Name"] del Employee["Company"] print("printing the modified inforrnation print(Employee) 10. print("Deleting the dictionary: Employee"); 11. del Employee 12. print("Lets try to print it again ");
  35. 13. print(Employee) Output: <class 'dict'> printing Employee data {'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': Deleting some of the employee data printing the modified information {'Age': 29, 'salary': 25000} Deleting the dictionary: Employee Lets try to print it again NameError: name 'Employee' is not defined 'GOOGLE'} The last print statement in the above code, it raised an error because we tried to print the Employee dictionary that already deleted. Using pop() method The pop() method accepts the key as an argument and remove the associated value. Consider the following example. 1. 2. 3. 4. 5. 6. # Creating a Dictionary Dict = {1: 'JavaTpoint', 2: 'Peter', 3: 'Thomas') # Deleting a key # using pop() method pop ele = Dict.pop(3) print(Dict) Output: {1: 'JavaTpoint', 2: 'Peter'} Python also provides a built-in methods popitem() and clear() method for remove elements from the dictionary. The popitem() removes the arbitrary element from a dictionary, whereas the clear() method removes all elements to the whole dictionary. Iterating Dictionary A dictionary can be iterated using for loop as given below. Example 1
  36. # for loop to print all the keys of a dictionary 1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company 2. for x in Employee: print(x) 3. Output: Name Age salary Company Example 2 #for loop to print all the values of the dictionary 1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company . 2. for x in Employee: print(Employee[x]) 3. Output: John 29 25000 GOOGLE Example - 3 #for loop to print the values of the dictionary by using values() method. 1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company": 2. for x in Employee.values(): print(x) 3. Output: John 29 25000 " : "GOOGLE"} " • "GOOGLE"} "GOOGLE"}
  37. GOOGLE Example 4 #for loop to print the items Of the dictionary by using items() method. 1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company . " • "GOOGLE"} 2. for x in Employee.items(): print(x) 3. Output: ('Name', 'John') ('Age', 29) ('salary', 25000) ('Company', 'GOOGLE') Properties of Dictionary keys 1. In the dictionary, we cannot store multiple values for the same keys. If we pass more than one value for a single key, then the value which is last assigned is considered as the value of the key. Consider the following example. hn"} 2. for x,y in Employee.items(): print(x,y) 3. Output: Name John Age 29 salary 25000 Company GOOGLE "GOOG LE"," Name":"Jo 2. In python, the key cannot be any mutable object. We can use numbers, strings, or tuples as the key, but we cannot use any mutable object like the list as the key in the dictionary. Consider the following example. 1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",[100,201 , 301]:"Department ID"}
  38. 2. for x,y in Employee.items(): print(x,y) 3. Output: Traceback (most recent call last): File "dictionary.py", line 1, in Employee = {"Name": "John", "Age": 29, TypeError: unhashable type: 'list' Built-in Dictionary functions Department ID"} The built-in python dictionary methods along with the description are given below. SN 1 2 3 4 Function cmp(dictl, dict2) len(dict) str(dict) type(variable) Description It compares the items of both the dictionary and returns true if the first dictionary values are greater than the second dictionary, otherwise it returns false. It is used to calculate the length of the dictionary. It converts the dictionary into the printable string representation. It is used to print the type of the passed variable. Built-in Dictionary methods The built-in python dictionary methods along with the description are given below. SN 1 2 3 Method dic.clear() dict.copy() dict.fromkevs(iterable, value = None. l) Description It is used to delete all the items of the dictionary. It returns a shallow copy of the dictionary. Create a new dictionary from the iterable with the values equal to value.
  39. 4 5 6 7 8 9 10 11 12 13 14 15 dict.get(kev. default = ' None") dict.has_key(key) dict.items() dict.kevs() dict.setdefault(kev,default= "None") dict.update(dict2) dict.values() len() popltem() pepo count() index() It is used to get the value specified for the passed key. It returns true if the dictionary contains the specified key. It returns all the key-value pairs as a tuple. It returns all the keys of the dictionary. It is used to set the key to the default value if the key is not specified in the dictionary It updates the dictionary by adding the key-value pair of dict2 to this dictionary. It returns all the values of the dictionary. Booleans represent one of two values: True or False Boolean Values In programming you often need to know if an expression is True or False. You can evaluate any expression in Python, and get one of two answers, True or False. When you compare two values, the expression is evaluated and Python returns the Boolean answer:
  40. Example print(10 > 9) print(10 9) print(10 < 9) When you run a condition in an if statement, Python returns True or False: Example Print a message based on whether the condition is True or False: a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a") Evaluate Values and Variables The bool() function allows you to evaluate any value, and give you True or False in return, Example Evaluate a string and a number: print(bool("Hello")) print(bool(15)) Evaluate two variables: x = "Hello" Y = 15 print(bool(x)) print(bool(y)) Most Values are True Almost any value is evaluated to True if it has some sort Of content.
  41. Any string is True, except empty strings. Any number is True, except O. Any list, tuple, set, and dictionary are True, except empty ones. The following will return True: bool(123) bool(["apple", "cherry", "banana")) Python Operators Operators are used to perform operations on variables and values. In the example below, we use the + operator to add together two values: Example print(10 + 5) Python divides the operators in the following groups: Arithmetic operators Assignment operators Comparison operators Logical operators Identity operators Membership operators Bitwise operators Python Arithmetic Operators Arithmetic operators are used with numeric values to perform common mathematical operations: Operator Name Example
  42. Addition Subtraction Multiplication Division Modulus Exponentiation Floor division Python Assignment Operators Assignment operators are used to assign values to variables: Operator Example Same As
  43. N/A
  44. 3 Python Classes/Objects Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects. Create a Class To create a class, use the keyword class: Example Create a class named MyClass, with a property named x: class MyClass: Create Object Now we can use the class named MyClass to create objects: Example Create an object named PI, and print the value of x: pl = MyClass() print(pl.x) The init Function
  45. The examples above are classes and objects in their simplest form, and are not really useful in real life applications. () function. To understand the meaning of classes we have to understand the built-in init All classes have a function called init (), which is always executed when the class is being initiated. Use the _ init () function to assign values to object properties, or other operations that are necessary to do when the object is being created: Example Create a class named Person, use the class Person: init (self, name, age): def self.name = name self.age = age pl = Person("John", 36) print(pl.name) print(pl.age) Object Methods init () function to assign values for name and age: Objects can also contain methods. Methods in objects are functions that belong to the object. Let us create a method in the Person class: Example Insert a function that prints a greeting, and execute it on the pl object: class Person: init (self, name, age): def self.name = name self.age = age def myfunc(self): print("He110 my name is " + self.name) pl = Person("John", 36) pl.myfunc()
  46. Python Inheritance Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class Create a Parent Class Any class can be a parent class, so the syntax is the same as creating any other class: Example Create a class named Person, with firstname and lastname properties, and a printname method: class Person: init (self, fname, 'name): def self.firstname = fname self.lastname = Iname def printname(self): print(self.firstname, self.lastname) #Use the Person class to create an object, and then execute the printname method: x = Person("John", "Doe") x.printname() What is a Module? Consider a module to be the same as a code library. A file containing a set of functions you want to include in your application. Create a Module To create a module just save the code you want in a file with the file extension .py: Example Save this code in a file named mymodule.py
  47. def greeting(name): " + name) Use a Module Now we can use the module we just created, by using the import statement: Example Import the module named mymodule, and call the greeting function: import mymodule mymodule.greeting("Jonathan") Variables in Module The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc): Example Save this code in the file mymodule.py personl = { "name": "John", "age": 36, "country": "Norway" Example Import the module named mymodule, and access the personl dictionary: import mymodule a = mymodule.personl["age"] print(a) Naming a Module You can name the module file whatever you like, but it must have the file extension .py Re-naming a Module You can create an alias when you import a module, by using the as keyæaord:
  48. Example Create an alias for mymodule called mx: import mymodule as mx a = mx.personl["age"] print(a) Built-in Modules There are several built-in modules in Python, which you can import whenever you like. Example Import and use the platform module: import platform x = platform.system() print(x) Using the dir() Function There is a built-in function to list all the function names (or variable names) in a module. The dir() function: Example List all the defined names belonging to the platform module: import platform x = dir(platform) print(x) Import From Module You can choose to import only parts from a module, by using the from keyword. Example The module named mymodule has one function and one dictionary: def greeting(name): print("Hello, " + name)
  49. personl = { "name": "John", "age": 36, "country": "Norway" Example Import only the personl dictionary from the module: from mymodule import personl print (personl["age"]) Python File Open Open a File on the Server Assume we have the following file, located in the same folder as Python: demofile.txt Hello! Welcome to demofile.txt This file is for testing purposes. Good Luck! To open the file, use the built-in open() function. The open() function returns a file object, which has a read() method for reading the content of the file: Example f = open("demofile.txt", "r") print(f.read()) Write to an Existing File To write to an existing file, you must add a parameter to the open() function: "a" - Append - will append to the end of the file "w" - Write - will overwrite any existing content Example
  50. Open the file "demofile2.txt" and append content to the file: f = open("demofile2.txt", "a") f.write("Now the file has more content! ") f.close() #open and read the file after the appending: f = open("demofile2.txt", "r") print(f.read()) Delete a File To delete a file, you must import the OS module, and run its os.remove() function: Example Remove the file "demofile.txt": import os os.remove("demofile.txt") Check if File exist: TO avoid getting an error, you might want to check if the file exists before you try to delete it: Example Check if file exists, then delete it: import os if os.path.exists("demofile.txt"): os.remove("demofile.txt") else: print("The file does not exist") Python Function Functions are the most important aspect of an application. A function can be defined as the organized block Of reusable code, which can be called whenever required. Python allows us to divide a large program into the basic building blocks known as a function. The function contains the set of programming statements enclosed by {l. A function can be called multiple times to provide reusability and modularity to the Python program.
  51. The Function helps to programmer to break the program into the smaller part. It organizes the code very effectively and avoids the repetition of the code. As the program grows, function makes the program more organized. Python provide us various inbuilt functions like range() or print(). Although, the user can create its functions, which can be called user-defined functions. Hello Java Program for Beginners There are mainly two types of functions. User-define functions - The user-defined functions are those define by the user to perform the specific task. Built-in functions - The built-in functions are those functions that are pre-defined in Python. In this tutorial, we will discuss the user define functions. Advantage of Functions in Python There are the following advantages of Python functions. Using functions, we can avoid rewriting the same logic/code again and again in a program. We can call Python functions multiple times in a program and anywhere in a program. We can track a large Python program easily when it is divided into multiple functions. Reusability is the main achievement of Python functions. However, Function calling is always overhead in a Python program. Creating a Function Python provides the def keyword to define the function. The syntax of the define function is given below. Syntax: def my_function(parameters): function block return expression Let's understand the syntax of functions definition. The def keyword, along with the function name is used to define the function. The identifier rule must follow the function name. A function accepts the parameter (argument), and they can be optional.
  52. The function block is started with the colon (:), and block statements must be at the same indentation. The return statement is used to return the value. A function can have only one return Function Calling In Python, after the function is created, we can call it from another function. A function must be defined before the function call; otherwise, the Python interpreter gives an error. To call the function, use the function name followed by the parentheses. Consider the following example of a simple example that prints the message "Hello World". #function definition def hello_world(): print("hello world") # function calling hello world() Output: hello world The return statement The return statement is used at the end of the function and returns the result of the function. It terminates the function execution and transfers the result where the function is called. The return statement cannot be used outside of the function. Syntax return [expression_list] It can contain the expression which gets evaluated and value is returned to the caller function. If the return statement has no expression or does not exist itself in the function then it returns the None object. Consider the following example: Example 1 # Defining function def sum(): a = 10 b = 20 c = a+b
  53. return c # calling sum() function in print statement sum is:",sum()) Output: The sum is: 30 In the above code, we have defined the function named sum, and it has a statement c = a+b, which computes the given values, and the result is returned by the return statement to the caller function. Example 2 Creating function without return statement # Defining function def sum(): a = 10 b = 20 # calling sum() function in print statement print(sum()) Python with Data science Human minds are more adaptive for the visual representation of data rather than textual data. We can easily understand things when they are visualized. It is better to represent the data through the graph where we can analyze the data more efficiently and make the specific decision according to data analysis. Before learning the matplotlib, we need to understand data visualization and why data visualization is important. Data Visualization
  54. Graphics provides an excellent approach for exploring the data, which is essential for presenting results. Data visualization is a new term. It expresses the idea that involves more than just representing data in the graphical form (instead of using textual form). This can be very helpful when discovering and getting to know a dataset and can help with classifying patterns, corrupt data, outliers, and much more. With a little domain knowledge, data visualizations can be used to express and demonstrate key relationships in plots and charts. The static does indeed focus on quantitative description and estimations Of data. It provides an important set Of tools for gaining a qualitative understanding. There are five key plots that are used for data visualization. 3.3M 53 Java Try Catch Bar Graph Histogram Scatter Plot Area Plot Pie Plot
  55. There are five phases which are essential to make the decision for the organization: Transform Data Set Visualize Finding Insights In Data Document Insight Ana lysis Visualize: We analyze the raw data, which means it makes complex data more accessible, understandable, and more usable. Tabular data representation is used where the user will look up a specific measurement, while the chart Of several types is used to show patterns or relationships in the data for one or more variables. Analysis: Data analysis is defined as cleaning, inspecting, transforming, and modeling data to derive useful information. Whenever we make a decision for the business or in daily life, is by past experience. What will happen to choose a particular decision, it is nothing but analyzing our past. That may be affected in the future, so the proper analysis is necessary for better decisions for any business or organization. Document Insight: Document insight is the process where the useful data or information is organized in the document in the standard format. Transform Data Set: Standard data is used to make the decision more effectively. Why need data visualization?
  56. 11.1 Data visualization can perform below tasks: It identifies areas that need improvement and attention. It clarifies the factors. It helps to understand which product to place where. Predict sales volumes. Benefit of Data Visualization Here are some benefits of the data visualization, which helps to make an effective decision for the organizations or business: 1. Building ways Of absorbing information Data visualization allows users to receive vast amounts of information regarding operational and business conditions. It helps decision-makers to see the relationship between multi-dimensional data sets. It offers new ways to analyses data through the use of maps, fever charts, and other rich graphical representations. Visual data discovery is more likely to find the information that the organization needs and then end up with being more productive than other competitive companies. 2. Visualize relationship and patterns in Businesses
  57. The crucial advantage of data visualization is that it is essential to find the correlation between operating conditions and business performance in today's highly competitive business environment. A B c D E The ability to make these types Of correlations enables the executives to identify the root cause Of the problem and act quickly to resolve it. Suppose a food company is looking their monthly customer data, and the data is presented with bar charts, which shows that the company's score has dropped by five points in the previous months in that particular region; the data suggest that there's a problem with customer satisfaction in this area. 3. Take action on the emerging trends faster Data visualization allows the decision-maker to grasp shifts in customer behavior and market conditions across multiple data sets more efficiently. Having an idea about the customer's sentiments and other data discloses an emerging opportunity for the company to act on new business opportunities ahead of their competitor. 4. Geological based Visualization Geo-spatial visualization is occurred due to many websites providing web-services, attracting visitor's interest. These types of websites are required to take benefit of location-specific information, which is already present in the customer details. Matplotlib is a Python library which is defined as a multi-platform data visualization library built on Numpy array. It can be used in python scripts, shell, web application, and other graphical user interface toolkit.
  58. The John D. Hunter originally conceived the matplotlib in 2002. It has an active development community and is distributed under a BSD-style license. Its first version was released in 2003, and the latest version 3.1.1 is released on 1 July 2019. Matplotlib 2.0.x supports Python versions 2.7 to 3.6 till 23 June 2007. Python3 support started with Matplotlib 1.2. Matplotlib 1.4 is the last version that supports Python 2.6. There are various toolkits available that are used to enhance the functionality of the matplotlib. Some of these tools are downloaded separately, others can be shifted with the matplotlib source code but have external dependencies. Bashmap: It is a map plotting toolkit with several map projections, coastlines, and political boundaries. Cartopy: It is a mapping library consisting of object-oriented map projection definitions, and arbitrary point, line, polygon, and image transformation abilities. Excel tools: Matplotlib provides the facility to utilities for exchanging data with Microsoft Excel. Mplot3d: It is used for 3D plots. Natgrid: It is an interface to the Natgrid library for irregular gridding of the spaced data. Matplotlib Architecture There are three different layers in the architecture Of the matplotlib which are the following: Backend Layer Artist layer Scripting layer Backend layer The backend layer is the bottom layer of the figure, which consists of the implementation of the various functions that are necessary for plotting. There are three essential classes from the backend layer FigureCanvas(The surface on which the figure will be drawn), Renderer(The class that takes care of the drawing on the surface), and Event(lt handle the mouse and keyboard events). Artist Layer The artist layer is the second layer in the architecture. It is responsible for the various plotting functions, like axis, which coordinates on how to use the renderer on the figure canvas.
  59. Scripting layer The scripting layer is the topmost layer on which most of our code will run. The methods in the scripting layer, almost automatically take care of the other layers, and all we need to care about is the current state (figure & subplot). The General Concept of Matplotlib A Matplotlib figure can be categorized into various parts as below: Figure title .0 0.5 0.0 Axis 4 X label 5 Figure: It is a whole figure which may hold one or more axes (plots). We can think of a Figure as a canvas that holds plots. Axes: A Figure can contain several Axes. It consists of two or three (in the case of 3D) Axis objects. Each Axes is comprised of a title, an x-label, and a y-label. Axis: Axises are the number of line like objects and responsible for generating the graph limits. Artist: An artist is the all which we see on the graph like Text objects, Line2D objects, and collection objects. Most Artists are tied to Axes. Installing Matplotlib
  60. Before start working with the Matplotlib or its plotting functions first, it needs to be installed. The installation of matplotlib is dependent on the distribution that is installed on your computer. These installation methods are following: Use the Anaconda distribution Of Python The easiest way to install Matplotlib is to download the Anaconda distribution of Python. Matplotlib is pre-installed in the anaconda distribution No further installation steps are necessary. Visit the official site of Anaconda and click on the Download Button C anaconda.com/di5tnbut•on/ Products Why Anaconda? O ANACONDA Solutions Anaconda Distribution The WorldX Most Popular PythonfR Data Science Platform The open•source Anaconda Distribution is the easiest way to perform Pythor„'R data science and machine learning on Linux, Windows. and Mac OS k With over IS million users worldwide. it is the industry' standard for developing. testing. Resources Download NMnPy H 20 Com pany Contact us Search CONN website uses cookies to ensure you get the best on our website. enyucy-P00cy Choose download according to your Python interpreter configuration.
  61. C' istr&ticr X + Windows macOS Linux Anaconda 2019.07 for Windows Installer Python 3.7 version Down d Graphical Installer (486 MS) 32-Bit Graphical Installer (418 MB) Python 2.7 version D cMnload 64.B.t Graphical Installer (427 MB) 32-8it Graphical Installer (361 MB) Get Started with Anaconda Distribution Install Matplotlib using with Anaconda Prompt Matplotlib can be installed using with the Anaconda Prompt by typing command. TO install matplotlib, open Anaconda Prompt and type the following command: 1. conda install matplotlib Prompt - matplctlib (base) C: Wsers\OÉVANSH SHARMA)conda install matplotlib Solving environment: done Install Matplotlib with pip The python package manager pip is also used to install matplotlib. Open the command prompt window, and type the following command:
  62. 1. pip install matplotlib Verify the Installation To verify that matplotlib is installed properly or not, type the following command includes calling version in the terminal. 1. 2. 3. import matplotlib matplotlib. version '3.1.1' Basic Example of plotting Graph Here is the basic example of generating a simple graph; the program is following: 1. 2. 3. 4. 5. from matplotlib import pyplot as plt #ploting our canvas pit. #display the graph plt.show() Output: 40 20 15 roo 125 150 175 zoo 225 250 275 It takes only three lines to plot a simple graph using the Python matplotlib. We can add titles, labels to our chart which are created by Python matplotlib library to make it more meaningful. The example is the following:
  63. from matplotlib import pyplot as plt Y = [1, 10, 4] plt.plot(x, y) plt.title('Line graph') plt.ylabel('Y axis') plt.xlabel('X axis') plt.show() Output: 10 8 4 2 Line grap 3 X axis The graph is more understandable from the previous graph. Working with Pyplot The matplotlib.pyplot is the collection command style functions that make matplotlib feel like working with MATLAB. The pyplot functions are used to make some changes to figure such as create a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot including labels, etc. It is good to use when we want to plot something quickly without instantiating any figure or Axes. While working with matplotlib.pyplot, some states are stored across function calls so that it keeps track of the things like current figure and plotting area, and these plotting functions are directed to the current axes.
  64. The pyplot module provide the plot() function which is frequently use to plot a graph. Let's have a look on the simple example: from matplotlib import pyplot as plt plt.plot([1,2,3,4,5]) axis") plt.xlabel('x axis') plt.show() Output: 45 30 20 15 oo 0.5 10 15 20 x axis 25 30 In the above program, it plots the graph x-axis ranges from 0-4 and the y-axis from 1-5. If we provide a single list to the plot(), matplotlib assumes it is a sequence of y values, and automatically generates the x values. Since we know that python index starts at O, the default x vector has the same length as y but starts at O. Hence the x data are [O, 1, 2, 3, 4]. We can pass the arbitrary number of arguments to the plot(). For example, to plot x versus y, we can do this following way: from matplotlib import pyplot as plt axis") plt.xlabel('x axis') plt.show() Output:
  65. 25 20 15 10 15 20 25 35 45 x axis Formatting the style of the plot There is an optional third argument, which is a format string that indicates the color and line type of the plot. The default format string is 'b-'which is the solid blue as you can observe in the above plotted graph. Let's consider the following example where we plot the graph with the red circle. from matplotlib import pyplot as plt 2, 3, 4,5], [1, 4, 9, 16,25], 'ro') 6, O, 20]) plt.show() Output: 20.0 17.5 15.0 12.5 10.0 7.5 50 25 2 Example format String 3 4 5 6
  66. 'b' 'ro' '-g' Using for the blue marker with default shape. Red circle Green solid line A dashed line with the default color Black triangle up markers connected by a dotted line The matplotlib supports the following color abbreviation: Character 'b' Blue 'c' 'k' Plotting with categorical variables Color Green Red Cyan Magenta Yellow Black White Matplotlib allows us to pass categorical variables directly to many plotting functions: consider the following example
  67. from matplotlib import pyplot names = ['Abhishek', 'Himanshu', 'Devansh'] marks: plt.figure(figsize=(9,3)) plt.subplot(131) plt.bar(names, marks) plt.subplot(132) plt.scatter(names, marks) plt.subplot(133) plt.plot(names, marks) plt.suptitle('Categorical Plotting') plt.show() Output: Categorical Plotting 80 EO 20 •Crn Dev ansh Himanshu Devansh On Himanshu Devan sh In the above program, we have plotted the categorical graph using the subplot() function. Let's a have a look on the subplot() function. What is subplot() The Matplotlib subplot() function is defined as to plot two or more plots in one figure. We can use this method to separate two graphs which plotted in the same axis Matplotlib supports all kinds of subplots, including 2x1 vertical, 2x1 horizontal, or a 2x2 grid. It accepts the three arguments: they are nrows, ncols, and index. It denote the number of rows, number of columns and the index.
  68. The subplot() function can be called in the following way: subplot(nrows,ncols,index,**kwargs) subplot(pos,**kwargs) subplot(ax) Parameters: *args: Three separate integers or three-digit integer describes the position of the subplot. If the three integers are nrows, ncols, and index in order, the subplot will take the index position on a grid with nrows row and ncol column. The argument pos are a three-digit integer, where the first digit is denoted the number of rows, the second digit denoted the number of columns, and the third represents the index of the subplot. For example, subplot (1, 3, 2) is the same as the subplot (132). Note: Passed integer must be less than 10. * *kwargs The subplot() function also accepts the keyword arguments for the returned axes base class. Consider the following example: Creating different types Of graph 1. Line graph The line graph is one of charts which shows information as a series of the line. The graph is plotted by the plot() function. The line graph is simple to plot; let's consider the following example: from matplotlib import pyplot as plt plt.plot(x,y) plt.title("Line graph")
  69. plt.ylabel('Y axis') plt.xlabel('X axis') plt.show() Output: Line graph 14 13 12 11 X axis We can customize the graph by importing the style module. The style module will be built into a matplotlib installation. It contains the various functions to make the plot more attractive. In the below program, we are using the style module: from matplotlib import pyplot as plt from matplotlib import style style.use('ggplot') [16, 8, 10] Y = [8, 16, 6] x2 = [8, 15, 11] Y2 = [6, 15, 7] plt.plot(x, y, 'r', label='line one', linewidth=5) plt.plot(x2, y2, 'm', label='line two', linewidth=5) plt.title('Epic Info') fig = plt.figure() plt.ylabel('Y axis')
  70. plt.xlabel('X axis') plt.legend() plt.grid(True, color='k') plt.show() Output: Epic Info 14 12 10 8 9 10 11 12 X axis 13 14 IS 16 In Matplotlib, the figure (an instance of class plt.Figure) can be supposed of as a single container that consists of all the objects denoting axes, graphics, text, and labels. Example-3 import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = plt.axes() x = np.linspace(O, 10, 1000) ax.plot(x, np.sin(x)) Output:
  71. roo - 075 050 025 - _0.25 - _0.50 —0.75 • The matplotlib provides the fill_between() function which is used to fill area around the lines based on the user defined logic. Example-4 import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = plt.axes() x = np.linspace(O, 10, 1000) ax.plot(x, np.sin(x)) import matplotlib.pyplot as plt import numpy as np x = np.arange(O.O, 2, 0.01) yl = np.sin(2 * np.pi * x) Y2 = 1.2 * np.sin(4 * np.pi * x) fig, ax = plt.subplots(l, sharex=True) ax.plot(x, yl, x, y2, color='black') ax.fill between(x, VI, y2, where=y2 yl, facecolor='blue', interpolate=True)
  72. ax.fill between(x, VI, y2, where=y2 yl, facecolor='red', interpolate=True) between where') Output: 05 00 -1.0 coo 025 2. Bar graphs fill between where 050 075 1.00 1.25 1.50 1.75 200 Bar graphs are one of the most common types of graphs and are used to show data associated with the categorical variables. Matplotlib provides a bar() to make bar graphs which accepts arguments such as: categorical variables, their value and color. from matplotlib import pyplot as plt players = ['Virat','Rohit', 'Shikhar','Hardik'] runs = plt.bar(players,runs,color = 'green') plt.title('Score Card') plt.xlabel('players') plt.ylabel('Runs') plt.show() Output:
  73. Score Card 60 911khar Players Hardik Another function barh() is used to make horizontal bar graphs. It accepts xerr or yerr as arguments (in case of vertical graphs) to depict the variance in our data as follows: from matplotlib import pyplot as plt players = ['Virat','Rohit', 'Shikhar','Hardik'] runs = plt.barh(players,runs, color = 'green') plt.title('Score Card') plt.xlabel('players') plt.ylabel('Runs') plt.show() Output:
  74. Score Card Hardik Rohit Wat Let's have a look on the other example using the style() function: from matplotlib import pyplot as plt from matplotlib import style style.use('ggplot') x2 = plt.bar(x, y, color = 'y', align='center') plt.bar(x2, y2, color='c', align='center') plt.title('lnformation') plt.ylabel('Y axis') plt.xlabel('X axis') Output:
  75. 16 - 14 - 12 Information X axis Similarly to vertical stack, the bar graph together by using the bottom argument and define the bar graph, which we want to stack below and its value. from matplotlib import pyplot as plt import numpy as np countries = ['USA', 'India', 'China', 'Russia', 'Germany'] bronzes = np.array([38, 17, 26, 19, 15]) silvers = np.array([37, 23, 18, 18, 10]) golds = np.array([46, 27, 26, 19, 17]) ind = [x for x, _ in enumerate(countries)] plt.bar(ind, golds, width=O.5, label='golds', color='gold', bottom=silvers+bronzes) plt.bar(ind, silvers, width=O.5, label='silvers', color='silver', bottom=bronzes) plt.bar(ind, bronzes, width=O.5, label='bronzes', color='#CD853F') plt.xticks(ind, countries) plt.ylabel("Medals") plt.xlabel("Countries") plt.legend(loc="upper right") Olympics Top Scorers") Output:
  76. 100 - 80 - 60 - 20 - o- 2019 Olympics Top Scorers plds India China Russia Countries 3. Pie Chart A pie chart is a circular graph that is broken down in the segment or slices of pie. It is generally used to represent the percentage or proportional data where each slice Of pie represents a particular category. Let's have a look at the below example: from matplotlib import pyplot as plt # Pie chart, where the slices will be ordered and plotted counter-clockwise: Players = 'Rohit', 'Virat', 'Shikhar', 'Yuvraj' Runs = [45, 30, 15, 10] explode = (0.1, O, O, O) # it "explode" the 1st slice figl, axl = plt.subplots() axl.pie(Runs, explode=explode, labels=Players, autopct='%l.lf%%', shadow=True, startangle=90) axl.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.show() Output:
  77. Yuvraj 91ikhar 15. Virat 4. Histogram First, we need to understand the difference between the bar graph and histogram. A histogram is used for the distribution, whereas a bar chart is used to compare different entities. A histogram is a type of bar plot that shows the frequency of a number of values compared to a set of values ranges. For example we take the data of the different age group of the people and plot a histogram with respect to the bin. Now, bin represents the range of values that are divided into series of intervals. Bins are generally created of the same size. from matplotlib import pyplot as plt from matplotlib import pyplot as plt population_age = bins = [0, 1001 plt.hist(population_age, bins, histtype='bar', rwidth=O.8) plt.xlabel('age groups') plt.ylabel('Number of people') plt.title('Histogram') plt.show() Output:
  78. Histogram age groups Let's consider the another example of plotting histogram: from matplotlib import pyplot as plt # Importing Numpy Library import numpy as np plt.style.use('fivethirtyeight') mu = 50 sigma = 7 x = np.random .normal(mu, sigma, size=200) fig, ax = plt.subplots() ax.hist(x, 20) ax.set_title('Historgram') ax.set xlabel('bin range') ax.set_ylabel('frequency') fig.tight layout() plt.show() Output:
  79. 20 u 15 10 5 30 5. Scatter plot 35 40 Historgram 45 50 55 bin range 60 65 The scatter plots are mostly used for comparing variables when we need to define how much one variable is affected by another variable. The data is displayed as a collection of points. Each point has the value of one variable, which defines the position on the horizontal axes, and the value of other variable represents the position on the vertical axis. Let's consider the following simple example: Example-I: from matplotlib import pyplot as plt from matplotlib import style style.use('ggplot') x2 = plt.scatter(x, y) plt.scatter(x2, y2, color='g')
  80. plt.title('Epic Info') plt.ylabel('Y axis') plt.xlabel('X axis') plt.show() Output: 18 14 X 12 6 6 Example-2 Epic Info X axis 9 10 11 import matplotlib.pyplot as plt [2, 2.5, 3, 3.5, 4.5, 4.7, 5.0] y = [7.5, 8, 8.5, 9, 9.5, 10, 10.5] Xl = [9, 8.5, 9, 9.5, 10, 10.5, 12] yl = [3, 3.5, 4.7, 4, 4.5, 5, 5.2] plt.scatter(x, y, label='high income low saving', color='g') plt.scatter(xl, VI, label='low income high savings', color='r') 100') plt.ylabel('income*1000') plt.title('Scatter Plot') plt.legend() plt.show()
  81. Output: Scatter Plot • high income low saving • low income high savings o E 10 8 6 4 2 6. 3D graph plot 4 6 8 10 12 saving*100 Matplotlib was initially developed with only two-dimension plot. Its 1.0 release was built with some of three-dimensional plotting utilities on top of two-dimension display, and the result is a convenient set of tools for 3D data visualization. Three-dimension plots can be created by importing the mp10t3d toolkit, include with the main Matplotlib installation: 1. from mpl_toolkits import mplot3d When this module is imported in the program, three-dimension axes can be created by passing the keyword projection='3d' to any of the normal axes creation routines: Let's see the simple 3D plot Example-I: 1. 2. 3. 4. 5. from mpltoolkits import mplot3d import numpy as np import matplotlib.pyplot as plt fig = plt.figure() ax = plt.axes(projection='3d')
  82. Output: 04 06 Example-2: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 21. 08 06 04 02 00 08 06 from mpl toolkits import mplot3d import numpy as np import matplotlib.pyplot as plt height = 71, 86]) weight = scatter(height,weight) 11. fig = plt.figure() 12. ax = plt.axes(projection='3d') 13. # This is used to plot 3D scatter 14. ax.scatter3D(height,weight) 15. plt.title("3D Scatter Plot") 16. plt.xlabel("Height") 17. plt.ylabel("Weight") 18. plt.title("3D Scatter Plot") 19. plt.xlabel("Height") 20. plt.ylabel("Weight")
  83. 22. plt.show() Output: 3D sc 40 50 70 80 Plot 004 002 coo _0.02 _0.04 Height 100 110 40 Note: We can use the plot3D to plot simple 3D line graph. Example-3 import matplotlib as mpl from mpl toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt mpl.rcParams['legend.fontsize'] fig = plt.figure() ax = fig.gca(projection='3d') = 10 thetal = np.linspace(-4 np.pi, 4 * np.pi, 100) z = np.linspace(-2, 2, 100) x = r* np.sin(thetal) y = r np.cos(thetal) ax.plot3D(x, y, z, label='parametric curve', color = 'red') ax.legend() plt.show()
  84. Output: parametric curve 2.0 _2 Important functions of Matplotlib Functions plot(x-axis value, y-axis-values) title("string") xlabel("string") ylabel("string") figure() subplots(nrows,ncol,index) subtitle("string") -1.0 -2.0 4 Description It is used to plot a simple line graph with x-axis value against the y-axis values. show() It is used to display the graph. It is used to set the title of the plotted graph as specified by the string. It is used to set the label for the x-axis as specified by the string. It is used to set the label for y-axis as specified by the string. It is used to control a figure level attributes. It is used to add a subplot to recent figure. It adds a common title to the plotted graph specified by the string.
  85. subplots(nrows,ncols,figsize) set_title("string") bar(categorical variables, color) barh(categorical variables, color) legend(loc) values, values, xtricks(index, categorical variables) pie(value, categorical variables) hist(value, number of bins) xlim(start value, end value) ylim(start value, end value) scatter(x-axis values, y-axis values) axes() set_xlabel("string") set_ylabel("string") It provides the simple way to create subplot, in a single call and returns a tuple of a figure and number of axes. It is an axes level method which is used to set the title of the subplots. It is used to create a vertical bar graph. It is used to create horizontal bar graphs. It is used to make a legend of the graph. It is used to set or get the current tick locations labels Of the x-axis. It is used to create a pie chart. It is used to create a histogram. It is used to set the limit of values Of the x-axis. It is used to set the limit of values of the y-axis. It is used to plots a scatter plot with x-axis value against the y-axis values. It is used to add axes to the recent figure. It is an axes level method which is used to set the x-label of the plot specified as a string. It is used to set the y-label of the plot specified as a string.
  86. scatter3D(x-axis values) values, y-axis It is used to plot a three-dimension scatter plot with x- axis value against the y-axis. It is used to plots a three-dimension line graph with x- axis values against y-axis values. plot3D(x-axis values, y-axis values) Python NumPy Tutorial NumPy Our Python NumPy Tutorial provides the basic and advanced concepts of the NumPy. Our NumPy tutorial is designed for beginners and professionals. NumPy stands for numeric python which is a python package for the computation and processing of the multidimensional and single dimensional array elements. What is NumPy NumPy stands for numeric python which is a python package for the computation and processing of the multidimensional and single dimensional array elements. Travis Oliphant created NumPy package in 2005 by injecting the features of the ancestor module Numeric into another module Numarray. It is an extension module of Python which is mostly written in C. It provides various functions which are capable of performing the numeric computations with a high speed. NumPy provides various powerful data structures, implementing multi-dimensional arrays and matrices. These data structures are used for the optimal computations regarding arrays and matrices. In this tutorial, we will go through the numeric python library NumPy.
  87. The need of NumPy With the revolution of data science, data analysis libraries like NumPy, SciPy, Pandas, etc. have seen a lot of growth. With a much easier syntax than other programming languages, python is the first choice language for the data scientist. NumPy provides a convenient and efficient way to handle the vast amount of data. NumPy is also very convenient with Matrix multiplication and data reshaping. NumPy is fast which makes it reasonable to work with a large set of data. There are the following advantages of using NumPy for data analysis. 1. 2. 3. 4. 5. NumPy performs array-oriented computing. It efficiently implements the multidimensional arrays. It performs scientific computations. It is capable Of performing Fourier Transform and reshaping the data stored in multidimensional arrays. NumPy provides the in-built functions for linear algebra and random number generation. Nowadays, NumPy in combination with SciPy and Mat-plotlib is used as the replacement to MATLAB as Python is more complete and easier programming language than MATLAB. Python Pandas Tutorial Pandas Python Pandas is defined as an open-source library that provides high-performance data manipulation in Python. This tutorial is designed for both beginners and professionals. It is used for data analysis in Python and developed by Wes McKinney in 2008. Our Tutorial provides all the basic and advanced concepts of Python Pandas, such as Numpy, Data operation and Time Series
  88. Python Pandas Introduction Pandas is defined as an open-source library that provides high-performance data manipulation in Python. The name of Pandas is derived from the word Panel Data, which means an Econometrics from Multidimensional data. It is used for data analysis in Python and developed by Wes McKinney in 2008. Data analysis requires lots of processing, such as restructuring, cleaning or merging, etc. There are different tools are available for fast data processing, such as Numpy, Scipy, Cython, and Panda. But we prefer Pandas because working with Pandas is fast, simple and more expressive than other tools. Pandas is built on top Of the Numpy package, means Numpy is required for operating the Pandas. Before Pandas, Python was capable for data preparation, but it only provided limited support for data analysis. So, Pandas came into the picture and enhanced the capabilities of data analysis. It can perform five significant steps required for processing and analysis of data irrespective of the origin Of the data, i.e., load, manipulate, prepare, model, and analyze. Key Features of Pandas It has a fast and efficient DataFrame object with the default and customized indexing. Used for reshaping and pivoting of the data sets. Group by data for aggregations and transformations. It is used for data alignment and integration of the missing data. Provide the functionality of Time Series. Process a variety of data sets in different formats like matrix data, tabular heterogeneous, time series. Handle multiple operations of the data sets such as subsetting, slicing, filtering, groupBy, re-ordering, and re-shaping. It integrates with the other libraries such as SciPy, and scikit-learn. Provides fast performance, and If you want to speed it, even more, the Cython. Benefits of Pandas The benefits of pandas over using other language are as follows: you can use
  89. Data Representation: It represents the data in a form that is suited for data analysis through its DataFrame and Series. Clear code: The clear API of the Pandas allows you to focus on the core part of the code. So, it provides clear and concise code for the user. Python Pandas Data Structure The Pandas provides two data structures for processing the data, i.e., Series and DataFrame, which are discussed below: 1) Series It is defined as a one-dimensional array that is capable of storing various data types. The row labels of series are called the index. We can easily convert the list, tuple, and dictionary into series using "series' method. A Series cannot contain multiple columns. It has one parameter: Data: It can be any list, dictionary, or scalar value. Creating Series from Array: Before creating a Series, Firstly, we have to import the numpy module and then use array() function in the program. 1. 2. 3. 4. 5. import pandas as pd import numpy as np info = a = pd.Series(info) print(a) Output dtype: object Explanation: In this code, firstly, we have imported the pandas and numpy library with the pd and np alias. Then, we have taken a variable named "info" that consist of an array Of some
  90. values. We have called the info variable through a Series method and defined it in an variable. The Series has printed by calling the print(a) method. Python Pandas DataFrame "a" It is a widely used data structure of pandas and works with a two-dimensional array with labeled axes (rows and columns). DataFrame is defined as a standard way to store data and has two different indexes, i.e., row index and column index. It consists of the following properties: The columns can be heterogeneous types like int, boo', and so on. It can be seen as a dictionary Of Series structure where both the rows and columns are indexed. It is denoted as "columns" in case of columns and "index" in case of rows. Create a DataFrame using List: We can easily create a DataFrame in Pandas using list. import pandas as pd # a list of strings x = ['Python', 'Pandas'] # Calling DataFrame constructor on list df = pd.DataFrame(x) print(df)