PYTHON-2 -LAB MANUAL LAST UPDATED.docx
Document Details
Uploaded by SimplerOnyx3210
Tags
Full Transcript
![](media/image2.png) **Al-Zaytoonah Private University of Jordan** **Faculty of Science and Information Technology** **\ ** Table of Contents Number Subject Page -------- ----------------------------...
![](media/image2.png) **Al-Zaytoonah Private University of Jordan** **Faculty of Science and Information Technology** **\ ** Table of Contents Number Subject Page -------- ------------------------------------------------------------------------------------------------ -------- 1 **Lab Manual Overview** **3** 2 **Required Tools and Resources** **3** 3 **Rules and Policies** **3** 4 **Learning Outcomes** **5** 5 **Exercise 1: Python Classes and Objects** **6** 6 **Exercise 2: The \_\_init\_\_() Function, The self Parameter and The \_\_str\_\_() Function** **8** 7 **Exercise 3: Accessing Attributes and Methods:** **11** 8 **Exercise 4: Python Inheritance** **13** 9 **Exercise 5: Different types of Python Inheritance** **17** 10 **Exercise 6: Python Polymorphism:1** **24** 11 **Exercise 7: Python Polymorphism:2** **27** 12 **Exercise 8: File Handling** **31** 13 **Exercise 9: Python encapsulation** **35** 14 **Exercise 10: Data Abstraction in Python** **40** 15 **Exercise11: Python Modules/numpy** **43** 16 **Exercise12: Python Modules/ NumPy Array Slicing** **50** 17 **Exercise13: Python Modules/ Pandas Tutorial** **54** 18 **Exercise14: Python Matplotlib** **66** Lab Manual Overview As Example (This lab manual enables students to learn the design and implementing of programs using Object Oriented Paradigm (OOP). Students will learn the basics of OOP using python, which are encapsulation, inheritance, and polymorphism) Required Tools and Resources Number Name -------- --------- 1 Pycharm Rules and Policies - Before you come to the lab session - You can bring your notebook so that you can keep your work with you - No food or beverage is allowed in the lab - Be sure to come on time to make sure you follow lab exercises with other students. - Be sure to remember your student account username and password - While being in the lab session - Interact with the lab supervisor. Do not hesitate to ask him questions - Maintain silence and discipline while being in the lab - Show cooperation with your fellow students - Log in to your computer using your student account - Make sure you complete your lab exercises - After finishing the lab session - Make sure the place you are using is clean - Put your chair or any material you have used back to its proper place - Make sure to logout of your student account - Attendance - You are required to come on time, otherwise you will be considered absent - Absence from lab sessions is recorded and will be used for absence warning system - Grading - Lab supervisor will record your progress during each lab session. - You are required to solve and submit any assignments the lab supervisor assigns to you. - Your final lab grade is based on your overall performance during lab sessions. Learning Outcomes: ILO1-k Understand the advanced topics in object-oriented programming in Python, including defining classes, invoking methods, using class libraries, etc -------- --------------------------------------------------------------------------------------------------------------------------------------------------- ILO2-k Knowledge of the structure and model of the Python programming language. ILO3-s Have the ability to use the rich libraries in python that are related to artificial intelligence to write programs for machine learning ILO4-s Write python programs using NumPy, matplotlib and pandas. ILO5-c The ability to implement programs using OOP concepts ILO6-c The ability to write programs using common libraries used for AI **OOPs Concepts in Python** - - - - - - ![Is Python Object Oriented?, 58% OFF \| www.bharatagritech.com](media/image4.png) ***Exercise 1: Python Classes and Objects*** **Exercise Objectives**: A. **Background:** - **A class is a collection of objects. It is a logical entity that contains some attributes and methods.** - **Classes are created by keyword class.** - **Attributes are the variables that belong to a class.** - **Attributes are always public and can be accessed using the dot (.) operator** **Class Definition Syntax:** **class** class\_name: \'\'\'This is a docstring. I have created a new class\'\'\' \ \.. \ - **class\_name: It is the name of the class** - **Docstring: It is the first string inside the class and has a brief description of the class. Although not mandatory, this is highly recommended.** - **statements: Attributes and methods** **[Python Objects]** **[Creating an Object]:** **Syntax** \ = \(\) **[An object consists of]:** **To understand the state, behavior, and identity let us take the example of the class dog:** B. **Experiments:** **Experiment1:** **class Person:** **def \_\_init\_\_(self, name, age):** **self.name = name** **self.age = age** **p1 = Person(\"John\", 36)** **print(p1)** **OUTPUT: \** C. **Assignments** ***Exercise 2: The \_\_init\_\_() Function, The self Parameter and The \_\_str\_\_() Function*** **Exercise Objectives**: A. **Background:** **[Method:]** ------------------------- **The method is a function that is associated with an object.** **[Python Class self Constructor:]** ------------------------------------------------ **[The Python self :]** **[Is self in Python a Keyword?]** **[Self: Pointer to Current Object]** **[The \_\_init\_\_() Function]:** **Syntax** class Subject: def \_\_init\_\_(self, attr1, attr2): self.attr1 = attr1 sef.attr2 = attr2 **[The \_\_str\_\_() Function]:** B. **Experiments:** **Experiment\#1:** **Insert a function that prints a greeting, and execute it on the p1 object:** class Person:\ def \_\_init\_\_(self, name, age):\ self.name = name\ self.age = age\ def myfunc(self):\ print(\"Hello my name is \" + self.name)\ p1 = Person(\"John\", 36)\ p1.myfunc() **Experiment\#2:** **The string representation of an object WITH the \_\_str\_\_() function:** **Experiment\#3:** **Use the words mysillyobject and abc instead of self:** class Person:\ def \_\_init\_\_(mysillyobject, name, age):\ mysillyobject.name = name\ mysillyobject.age = age\ \ def myfunc(abc):\ print(\"Hello my name is \" + abc.name)\ \ p1 = Person(\"John\", 36)\ p1.myfunc() C. **Assignments** **Assignment\#1: Write a Python class named Rectangle constructed from length and width and a method that will compute the area of a rectangle.** **Assignment\#2: Write a Python class named Rectangle constructed from length and width and a method that will compute the area of a rectangle.** ***Exercise 3: Accessing Attributes and Methods:*** **Exercise Objectives**: A. **Background:** **Attributes and methods are accessed using the dot (.) operator.** B. **Experiments: You can modify properties on objects like this:** **Experiment\#1:** **Set the age of p1 to 40:** **p1.age = 40** **Experiment\#2:** **Delete Object Properties. You can delete properties on objects by using the del keyword:** **Delete the age property from the p1 object:** **del p1.age** **Experiment\#3:** **Delete Objects. You can delete objects by using the del keyword:** **Delete the p1 object:** **del p1** **Experiment\#4:** **The pass Statement: if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.** **class Person:\ pass** C. **Assignments** ***Exercise 4: Python Inheritance*** **Exercise Objectives**: A. **Background:** - **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.** - **Any class can be a parent class** **The syntax of simple inheritance in Python is as follows:** **Class BaseClass:** **{Body}** **Class DerivedClass(BaseClass):** **{Body}** B. **Experiments:** **Experiment\#1: Create a class named Person, with firstname and lastname properties, and a printname method:** **Experiment\#1: To create a class that inherits the functionality from another class, send the parent class as a parameter when creating the child class:** **Create a class named Student, which will inherit the properties and methods from the Person class:** class Student(Person):\ pass **Now the Student class has the same properties and methods as the Person class.** **Experiment\#2: Use the Student class to create an object, and then execute the printname method:** x = Student(\"Mike\", \"Olsen\")\ x.printname() **Experiment\#3: Add the \_\_init\_\_() Function** **So far we have created a child class that inherits the properties and methods from its parent.** **We want to add the \_\_init\_\_() function to the child class (instead of the pass keyword).** Note:** The \_\_init\_\_() function is called automatically every time the class is being used to create a new object.** **Add the \_\_init\_\_() function to the Student class:** class Student(Person):\ def \_\_init\_\_(self, fname, lname):\ \#add properties etc. **When you add the \_\_init\_\_() function, the child class will no longer inherit the parent\'s \_\_init\_\_() function.** **Note: The child\'s \_\_init\_\_() function overrides the inheritance of the parent\'s \_\_init\_\_() function.** **To keep the inheritance of the parent\'s \_\_init\_\_() function, add a call to the parent\'s \_\_init\_\_() function:** class Student(Person):\ def \_\_init\_\_(self, fname, lname):\ Person.\_\_init\_\_(self, fname, lname) **Experiment\#3: Use the super() Function:** **Python also has a super() function that will make the child class inherit all the methods and properties from its parent:** class Student(Person):\ def \_\_init\_\_(self, fname, lname):\ super().\_\_init\_\_(fname, lname) **By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent.** **Experiment\#4: Add Properties** **Add a property called graduationyear to the Student class:** class Student(Person):\ def \_\_init\_\_(self, fname, lname):\ super().\_\_init\_\_(fname, lname)\ self.graduationyear = 2019 **In the example below, the year 2019 should be a variable, and passed into the Student class when creating student objects. To do so, add another parameter in the \_\_init\_\_() function:** **Experiment\#5: Add a year parameter, and pass the correct year when creating objects:** class Student(Person):\ def \_\_init\_\_(self, fname, lname, year):\ super().\_\_init\_\_(fname, lname)\ self.graduationyear = year\ x = Student(\"Mike\", \"Olsen\", 2019) **Experiment\#5: Add Methods** **Add a method called welcome to the Student class:** class Student(Person):\ def \_\_init\_\_(self, fname, lname, year):\ super().\_\_init\_\_(fname, lname)\ self.graduationyear = year\ def welcome(self):\ print(\"Welcome\", self.firstname, self.lastname, \"to the class of\", self.graduationyear) **If you add a method in the child class with the same name as a function in the parent class, the inheritance of the parent method will be overridden.** C. **Assignments** **Assignment\#1: Given** **class** Vehicle: **def** \_\_init\_\_(self, name, max\_speed, mileage): self.name = name self.max\_speed = max\_speed self.mileage = mileage **Expected Output:** Vehicle Name: School Volvo Speed: 180 Mileage: 12 ***Exercise 5: Different types of Python Inheritance*** **Exercise Objectives**: A. **Background:** **There are 5 different types of inheritance in Python. They are as follows:** 1. **Single inheritance: When a child class inherits from only one parent class, it is called single inheritance. We saw an example above.** 2. **Multiple inheritances: When a child class inherits from multiple parent classes, it is called multiple inheritances. ** 3. **Multilevel inheritance: When we have a child and grandchild relationship. This means that a child class will inherit from its parent class, which in turn is inheriting from its parent class.** 4. **Hierarchical inheritance More than one derived class can be created from a single base.** 5. **Hybrid inheritance: This form combines more than one form of inheritance. Basically, it is a blend of more than one type of inheritance.** B. **Experiments:** **Experiment\#1:** **Single inheritance In this type, a derived class inherits from only one base class.**https://media.geeksforgeeks.org/wp-content/uploads/20200108135809/inheritance11.png \# Python program to demonstrate \# single inheritance \# Base class class Parent: def func1(self): print(\"This function is in parent class.\") \# Derived class class Child(Parent): def func2(self): print(\"This function is in child class.\") \# Driver\'s code object = Child() object.func1() object.func2() **Output:** This function is in parent class. This function is in child class. **Experiment\#2: Multiple Inheritance: In this inheritance, the derived class inherits from multiple base classes.** ![https://media.geeksforgeeks.org/wp-content/uploads/20200108144424/multiple-inheritance1.png](media/image6.png) \# Python program to demonstrate \# multiple inheritance \# Base class1 class Mother: mothername = \"\" def mother(self): print(self.mothername) \# Base class2 class Father: fathername = \"\" def father(self): print(self.fathername) \# Derived class class Son(Mother, Father): def parents(self): print(\"Father :\", self.fathername) print(\"Mother :\", self.mothername) \# Driver\'s code s1 = Son() s1.fathername = \"RAM\" s1.mothername = \"SITA\" s1.parents() **Output:** Father : RAM Mother : SITA **Experiment\#3: Multilevel Inheritance: In this, a derived class inherits another derived class. This is similar to a relationship representing a child and a grandfather. ** Lightbox \# Python program to demonstrate \# multilevel inheritance \# Base class class Grandfather: def \_\_init\_\_(self, grandfathername): self.grandfathername = grandfathername \# Intermediate class class Father(Grandfather): def \_\_init\_\_(self, fathername, grandfathername): self.fathername = fathername \# invoking constructor of Grandfather class Grandfather.\_\_init\_\_(self, grandfathername) \# Derived class class Son(Father): def \_\_init\_\_(self, sonname, fathername, grandfathername): self.sonname = sonname \# invoking constructor of Father class Father.\_\_init\_\_(self, fathername, grandfathername) def print\_name(self): print(\'Grandfather name :\', self.grandfathername) print(\"Father name :\", self.fathername) print(\"Son name :\", self.sonname) \# Driver code s1 = Son(\'Prince\', \'Rampal\', \'Lal mani\') print(s1.grandfathername) s1.print\_name() **Output:** Lal mani Grandfather name : Lal mani Father name : Rampal Son name : Prince **Experiment\#4: Hierarchical Inheritance: In this, we create more than one derived classes from one base class. In this program, we have a parent (base) class and two child (derived) classes.** ![Lightbox](media/image8.png) \# Python program to demonstrate \# Hierarchical inheritance \# Base class class Parent: def func1(self): print(\"This function is in parent class.\") \# Derived class1 class Child1(Parent): def func2(self): print(\"This function is in child 1.\") \# Derivied class2 class Child2(Parent): def func3(self): print(\"This function is in child 2.\") \# Driver\'s code object1 = Child1() object2 = Child2() object1.func1() object1.func2() object2.func1() object2.func3() **Output:** This function is in parent class. This function is in child 1. This function is in parent class. This function is in child 2. **Experiment\#5: Hybrid Inheritance: Inheritance consisting of multiple types of inheritance is called hybrid inheritance.** Lightbox \# Python program to demonstrate \# hybrid inheritance class School: def func1(self): print(\"This function is in school.\") class Student1(School): def func2(self): print(\"This function is in student 1. \") class Student2(School): def func3(self): print(\"This function is in student 2.\") class Student3(Student1, School): def func4(self): print(\"This function is in student 3.\") \# Driver\'s code object = Student3() object.func1() object.func2() **Output:** This function is in school. This function is in student 1. C. **Assignments** **Assignment\#1: Given the following ULM diagram:** ![Python Inheritance Model](media/image10.png) **Write a python program using inheritance for the previous UML diagram model.** ***Exercise 6: Python Polymorphism:1*** **Exercise Objectives**: A. **Background:** **The word \"polymorphism\" means \"many forms\", and in programming it refers to methods/functions/operators with the same name that can be executed on many objects or classes.** **[Class Polymorphism:] Polymorphism is often used in Class methods, where we can have multiple classes with the same method name. For example, say we have three classes: Car, Boat, and Plane, and they all have a method called move():** B. **Experiments:** **Experiment\#1: Different classes with the same method:** class Car:\ def \_\_init\_\_(self, brand, model):\ self.brand = brand\ self.model = model\ def move(self):\ print(\"Drive!\")\ class Boat:\ def \_\_init\_\_(self, brand, model):\ self.brand = brand\ self.model = model\ def move(self):\ print(\"Sail!\")\ class Plane:\ def \_\_init\_\_(self, brand, model):\ self.brand = brand\ self.model = model\ def move(self):\ print(\"Fly!\")\ car1 = Car(\"Ford\", \"Mustang\") \#Create a Car class\ boat1 = Boat(\"Ibiza\", \"Touring 20\") \#Create a Boat class\ plane1 = Plane(\"Boeing\", \"747\") \#Create a Plane class\ for x in (car1, boat1, plane1):\ x.move()\ **Look at the for loop at the end. Because of polymorphism we can execute the same method for all three classes.** **Experiment\#2: Inheritance Class Polymorphism:** **What about classes with child classes with the same name? Can we use polymorphism there?** **Yes. If we use the example above and make a parent class called Vehicle, and make Car, Boat, Plane child classes of Vehicle, the child classes inherit the Vehicle methods, but can override them:** **Create a class called Vehicle and make Car, Boat, Plane child classes of Vehicle:** class Vehicle:\ def \_\_init\_\_(self, brand, model):\ self.brand = brand\ self.model = model\ def move(self):\ print(\"Move!\")\ class Car(Vehicle):\ pass\ class Boat(Vehicle):\ def move(self):\ print(\"Sail!\")\ class Plane(Vehicle):\ def move(self):\ print(\"Fly!\")\ car1 = Car(\"Ford\", \"Mustang\") \#Create a Car object\ boat1 = Boat(\"Ibiza\", \"Touring 20\") \#Create a Boat object\ plane1 = Plane(\"Boeing\", \"747\") \#Create a Plane object\ for x in (car1, boat1, plane1):\ print(x.brand)\ print(x.model)\ x.move() **Child classes inherits the properties and methods from the parent class.** **In the example above you can see that the Car class is empty, but it inherits brand, model, and move() from Vehicle.** **The Boat and Plane classes also inherit brand, model, and move() from Vehicle, but they both override the move() method.** **Because of polymorphism we can execute the same method for all classes.** **Experiment\#3: Polymorphism with Functions** **allows you to work with objects based on their behavior rather than their specific types.** class Circle:\ def area(self, radius):\ return 3.14159265359 \* radius \*\* 2\ class Square:\ def area(self, side\_length):\ return side\_length \*\* 2\ def calculate\_area(shape, size):\ return shape.area(size)\ *\# Usage of polymorphism with functions*\ circle = Circle()\ square = Square()\ print(calculate\_area(circle, 5)) \# Output: 78.539816339745\ print(calculate\_area(square, 4)) **Output:** 78.5\ 16 B. **Assignments** **Assignment\#1:** Class Polymorphism **Write a python program for the previous model to show polymorphism.** ***Exercise 7: Python Polymorphism:2*** **Exercise Objectives**: A. **Background:** **Operator overloading is another type of polymorphism in which the same operator performs various operations depending on the operands.** **[Polymorphism in + operator:]** **We already know that the '+' operator is frequently used in Python programs. However, it does not have a single application. When you wish to add two integers, concatenate two strings, or extend two lists, you use the same + sign. The + operator behaves differently depending on the type of object on which it is used.** **[Polymorphism in \* operator:]** **The \* operator is used to multiply 2 numbers if the data elements are numeric values. If one of the data types is a string, and the other is numeric, the string is printed that many times as that of the 2nd variable in the multiplication process.** **[Function Polymorphism in Python:]** **There are certain Python functions that can be used with different data types. The len() function is one example of such a function. Python allows it to work with a wide range of data types. The built-in function len() estimates an object's length based on its type. If an object is a string, it returns the number of characters; or if an object is a list, it returns the number of elements in the list. If the object is a dictionary, it gives the total number of keys found in the dictionary.** B. **Experiments:** **Experiment\#1:** **Polymorphism in + operator:** **a = 10** **b = 20** **print(\'Addition of 2 numbers:\', a + b)** **str1 = \'Hello \'** **str2 = \'Python\'** **print(\'Concatenation of 2 strings:\', str1 + str2)** **list1 = \[1, 2, 3\]** **list2 = \[\'A\', \'B\'\]** **print(\'Concatenation of 2 lists:\', list1 + list2)** **Output:** **Addition of 2 numbers: 30** **Concatenation of 2 strings: Hello Python** **Concatenation of 2 lists: \[1, 2, 3, \'A\', \'B\'\]** **The + operator is used to execute arithmetic addition on integer data types. Similarly, the + operator is used to execute concatenation on string data types. In the case of lists, it returns a new list that contains elements from both original lists.** **Experiment\#2:** **Polymorphism in \* operator:** **a = 10** **b = 5** **print(\'Multiplication of 2 numbers:\', a \* b)** **num = 3** **mystr = \'Python\'** **print(\'Multiplication of string:\', num \* mystr)** **Output:** **Multiplication of 2 numbers: 50** **Multiplication of string: PythonPythonPython** **Experiment\#4: Polymorphism and Inheritance (Method Overriding)** **Polymorphism is most commonly associated with inheritance. In Python, child classes, like other programming languages, inherit methods and attributes from the parent class. Method Overriding is the process of redefining certain methods and attributes to fit the child class. This is especially handy when the method inherited from the parent class does not exactly fit the child class. In such circumstances, the method is re-implemented in the child class. Method Overriding refers to the technique of re-implementing a method in a child class.** ***Exercise8: File Handling*** **Exercise Objectives**: **A.** **Background:** **Create a New File** To create a new file in Python, use the open() method, with one of the following parameters: \"x\" - Create - will create a file, returns an error if the file exist \"a\" - Append - will create a file if the specified file does not exist \"w\" - Write - will create a file if the specified file does not exist **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 **File Handling** ----------------- The key function for working with files in Python is the open() function. The open() function takes two parameters; *filename*, and *mode*. There are four different methods (modes) for opening a file: \"r\" - Read - Default value. Opens a file for reading, error if the file does not exist \"a\" - Append - Opens a file for appending, creates the file if it does not exist \"w\" - Write - Opens a file for writing, creates the file if it does not exist \"x\" - Create - Creates the specified file, returns an error if the file exists In addition you can specify if the file should be handled as binary or text mode \"t\" - Text - Default value. Text mode \"b\" - Binary - Binary mode (e.g. images) **Syntax** ---------- To open a file for reading it is enough to specify the name of the file: f = open(\"demofile.txt\") The code above is the same as: f = open(\"demofile.txt\", \"rt\") Because \"r\" for read, and \"t\" for text are the default values, you do not need to specify them. **Delete a File** ----------------- To delete a file, you must import the OS module, and run its os.remove() function: - To avoid getting an error, you might want to check if the file exists before you try to delete it: **Delete Folder** ----------------- **Check if File exist** ----------------------- To avoid getting an error, you might want to check if the file exists before you try to delete it: B. **Experiments:** f = open(\"myfile.txt\", \"x\") output: a new empty file is created! **Experiment\#2:** **Python File Open** Open a File on the Server Assume we have the following file, located in the same folder as Python: **Experiment\#4:** **Read Lines** **Experiment\#5:** **Close Files** f = open(\"demofile.txt\", \"r\")\ print(f.readline())\ f.close() C. **Assignments** **Assignment\#1:** **Write a function in python to read the content from a text file \"poem.txt\" line by line and display the same on screen.** ***Exercise 9: Python encapsulation*** **Exercise Objectives**: - Understanding Encapsulation concept in Python - Understanding data Hiding using public, protected, and private members - Understanding Getter and Setter Methods A. **Background:** - - - - - ![Data hiding using access access modifiers](media/image12.jpeg) - B. **Experiments:** **Experiment\#1:** **Public members** **Experiment\#5:** **Getters and Setters in Python** class Student: def \_\_init\_\_(self, name, age): \# private member self.name = name self.\_\_age = age \# getter method def get\_age(self): return self.\_\_age \# setter method def set\_age(self, age): self.\_\_age = age stud = Student(\'Jessa\', 14) \# retrieving age using getter print(\'Name:\', stud.name, stud.get\_age()) \# changing age using setter stud.set\_age(16) \# retrieving age using getter print (\'Name:\', stud.name, stud.get\_age()) C. **Assignment** 1. Create a Book class with the following attributes: - title (private): The title of the book. - author (private): The author of the book. - isbn (private): The ISBN (International Standard Book Number) of the book. - availability (private): A boolean value indicating whether the book is currently available or not. 2. Implement appropriate getter and setter methods to access and modify the private attributes. 3. Create a method named check\_out that sets the availability of the book to False if the book is currently available. If the book is already checked out, display an appropriate message indicating that the book is not available. 4. Create a method named check\_in that sets the availability of the book to True if the book is currently checked out. If the book is already checked in, display an appropriate message indicating that the book is already available. 5. Create a method named display\_book\_details that displays the book\'s title, author, ISBN, and availability. 6. Create instances of the Book class for at least three different books in the library. 7. Demonstrate the functionality of the system by performing the following operations on the books: - Check out a book and display its details. - Check in a book and display its details. - Display the details of all the books in the library. Ensure that the private attributes are accessed and modified only through the getter and setter methods, demonstrating encapsulation principles. Write a Python script that implements the Library Catalog System based on the given problem statement. ***Exercise 10: Data Abstraction in Python*** **Exercise Objectives**: - Understanding Encapsulation concept in Python - Understanding data Hiding using public, protected, and private members - Understanding Getter and Setter Methods D. 1. Abstraction is one of the important principles of object-oriented programming. It refers to a programming approach by which only the relevant data about an object is exposed, hiding all the other details. This approach helps in reducing the complexity and increasing the efficiency in application development. 2. There are two types of abstraction. One is data abstraction, wherein the original data entity is hidden via a data structure that can internally work through the hidden data entities. Other type is called process abstraction. It refers to hiding the underlying implementation details of a process. 3. In object-oriented programming terminology, a class is said to be an abstract class if it cannot be instantiated, that is you can have an object of an abstract class. You can however use it as a base or parent class for constructing other classes. 4. To form an abstract class in Python, it must inherit ABC class that is defined in the abc module. This module is available in Python\'s standard library. Moreover, the class must have at least one abstract method. Again, an abstract method is the one which cannot be called, but can be overridden. You need to decorate it with \@abstractmethod decorator. B. **Experiments:** The **demo** class inherits ABC class. There is a method1() which is an abstract method. Note that the class may have other non-abstract (concrete) methods. If you try to declare an object of demo class, Python raises TypeError −. The **demo** class here may be used as parent for another class. However, the child class must override the abstract method in parent class. If not, Python throws this error −. Hence, the child class with the abstract method overridden is given in the following **example** -- **Experiment\#2:** class democlass(ABC): \@abstractmethod def method1(self): print (\"abstract method\") return def method2(self): print (\"concrete method\") class concreteclass(democlass): def method1(self): super().method1() return obj = concreteclass() obj.method1() obj.method2() C. **Assignment:** You are tasked with designing an Online Shopping System. The system should abstract the implementation details of various products and provide a simplified interface for customers to browse and purchase items. 1. Create an abstract class named Product with the following abstract methods: - get\_name(): Returns the name of the product. - get\_price(): Returns the price of the product. - display\_details(): Displays the details of the product. 2. Implement at least two concrete subclasses of Product representing different types of products (e.g., electronics, books, clothing). Each subclass should provide an implementation for the abstract methods. 3. Create a ShoppingCart class that allows customers to add products, remove products, and calculate the total cost of all the products in the cart. The ShoppingCart class should use abstraction to interact with the Product objects without knowing the specific details of each product. 4. Demonstrate the functionality of the system by performing the following operations: - Create instances of different product types and display their details. - Create a ShoppingCart object and add products to it. - Calculate and display the total cost of the products in the shopping cart. Ensure that the abstract class defines a common interface for all the products, allowing the ShoppingCart class to work with any type of product without knowing the specific implementation details. Write a Python script that implements the Online Shopping System based on the given problem statement. Remember to follow Python naming conventions and best practices for abstraction. ***Exercise11: Python Modules*** **Exercise Objectives**: **A.** **Background:** NumPy is a Python library. NumPy is used for working with arrays: In Python we have lists that serve the purpose of arrays, but they are slow to process. NumPy aims to provide an array object that is up to 50x faster than traditional Python lists. NumPy is short for \"Numerical Python\". The array object in NumPy is called ndarray. **Installation of NumPy** If you have [[Python]](https://www.w3schools.com/python/default.asp) and [[PIP]](https://www.w3schools.com/python/python_pip.asp) already installed on a system, then installation of NumPy is very easy. Install it using this command: C:\\Users\\*Your Name*\>pip install numpy If this command fails, then use a python distribution that already has NumPy installed like, Anaconda, Spyder etc. **Import NumPy** Once NumPy is installed, import it in your applications by adding the import keyword: import numpy Now NumPy is imported and ready to use. **B.** **Experiments:** **Experiment\#1:** import numpy\ arr = numpy.array(\[1, 2, 3, 4, 5\])\ print(arr) **NumPy as np** NumPy is usually imported under the np alias. import numpy as np **NumPy Creating Arrays** **Create a NumPy ndarray Object** NumPy is used to work with arrays. The array object in NumPy is called ndarray. We can create a NumPy ndarray object by using the array() function. To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will be converted into an ndarray: **Experiment\#2:** Use a tuple to create a NumPy array: import numpy as np\ arr = np.array((1, 2, 3, 4, 5))\ print(arr) **Dimensions in Arrays** A dimension in arrays is one level of array depth (nested arrays). **nested array:** are arrays that have arrays as their elements. **0-D Arrays** 0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array. **Experiment\#3:** Create a 0-D array with value 42 import numpy as np\ arr = np.array(42)\ print(arr) **1-D Arrays** An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array. These are the most common and basic arrays. **Experiment\#4:** Create a 1-D array containing the values 1,2,3,4,5: import numpy as np\ arr = np.array(\[1, 2, 3, 4, 5\])\ print(arr) **2-D Arrays** An array that has 1-D arrays as its elements is called a 2-D array. These are often used to represent matrix or 2nd order tensors. **Experiment\#5:** Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6: import numpy as np\ arr = np.array(\[\[1, 2, 3\], \[4, 5, 6\]\])\ print(arr) **3-D arrays** An array that has 2-D arrays (matrices) as its elements is called 3-D array. These are often used to represent a 3rd order tensor. **Experiment\#6:** Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and 4,5,6: import numpy as np\ arr = np.array(\[\[\[1, 2, 3\], \[4, 5, 6\]\], \[\[1, 2, 3\], \[4, 5, 6\]\]\])\ print(arr) **Check Number of Dimensions?** NumPy Arrays provides the ndim attribute that returns an integer that tells us how many dimensions the array have. **Experiment\#7:** Check how many dimensions the arrays have: import numpy as np\ a = np.array(42)\ b = np.array(\[1, 2, 3, 4, 5\])\ c = np.array(\[\[1, 2, 3\], \[4, 5, 6\]\])\ d = np.array(\[\[\[1, 2, 3\], \[4, 5, 6\]\], \[\[1, 2, 3\], \[4, 5, 6\]\]\])\ print(a.ndim)\ print(b.ndim)\ print(c.ndim)\ print(d.ndim) **Higher Dimensional Arrays:** An array can have any number of dimensions. When the array is created, you can define the number of dimensions by using the ndmin argument. **Experiment\#8:** Create an array with 5 dimensions and verify that it has 5 dimensions: import numpy as np\ arr = np.array(\[1, 2, 3, 4\], ndmin=5)\ print(arr)\ print(\'number of dimensions :\', arr.ndim) **Access Array Elements** Array indexing is the same as accessing an array element. You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc. **Experiment\#9:** Get the first element from the following array: import numpy as np\ arr = np.array(\[1, 2, 3, 4\])\ print(arr\[0\]) **Experiment\#10:** Get the second element from the following array. import numpy as np\ arr = np.array(\[1, 2, 3, 4\])\ print(arr\[1\]) **Experiment\#11:** Get third and fourth elements from the following array and add them. import numpy as np\ arr = np.array(\[1, 2, 3, 4\])\ print(arr\[2\] + arr\[3\]) **Access 2-D Arrays:** To access elements from 2-D arrays we can use comma separated integers representing the dimension and the index of the element. Think of 2-D arrays like a table with rows and columns, where the dimension represents the row and the index represents the column. **Experiment\#12:** Access the element on the first row, second column: import numpy as np\ arr = np.array(\[\[1,2,3,4,5\], \[6,7,8,9,10\]\])\ print(\'2nd element on 1st row: \', arr\[0, 1\]) **Experiment\#13:** Access the element on the 2nd row, 5th column: import numpy as np\ arr = np.array(\[\[1,2,3,4,5\], \[6,7,8,9,10\]\])\ print(\'5th element on 2nd row: \', arr\[1, 4\]) **Access 3-D Arrays:** To access elements from 3-D arrays we can use comma separated integers representing the dimensions and the index of the element. **Experiment\#14:** Access the third element of the second array of the first array: import numpy as np\ arr = np.array(\[\[\[1, 2, 3\], \[4, 5, 6\]\], \[\[7, 8, 9\], \[10, 11, 12\]\]\])\ print(arr\[0, 1, 2\]) arr\[0, 1, 2\] prints the value 6. And this is why: The first number represents the first dimension, which contains two arrays:\ \[\[1, 2, 3\], \[4, 5, 6\]\]\ and:\ \[\[7, 8, 9\], \[10, 11, 12\]\]\ Since we selected 0, we are left with the first array:\ \[\[1, 2, 3\], \[4, 5, 6\]\] The second number represents the second dimension, which also contains two arrays:\ \[1, 2, 3\]\ and:\ \[4, 5, 6\]\ Since we selected 1, we are left with the second array:\ \[4, 5, 6\] The third number represents the third dimension, which contains three values:\ 4\ 5\ 6\ Since we selected 2, we end up with the third value:\ 6 **Negative Indexing** Use negative indexing to access an array from the end. **Experiment\#15:** Print the last element from the 2nd dim: import numpy as np\ arr = np.array(\[\[1,2,3,4,5\], \[6,7,8,9,10\]\])\ print(\'Last element from 2nd dim: \', arr\[1, -1\]) ***Exercise12: Python Modules*** **Exercise Objectives**: NumPy Array Slicing A. Slicing in python means taking elements from one given index to another given index. We pass slice instead of index like this: \[*start*:*end*\]. We can also define the step, like this: \[*start*:*end*:*step*\]. If we don\'t pass start its considered 0 If we don\'t pass end its considered length of array in that dimension If we don\'t pass step its considered 1 B. **Experiments** **Experiment\#1:** Slice elements from index 1 to index 5 from the following array: import numpy as np\ \ arr = np.array(\[1, 2, 3, 4, 5, 6, 7\])\ \ print(arr\[1:5\]) **Note:** The result *includes* the start index, but *excludes* the end index. Example Slice elements from index 4 to the end of the array: import numpy as np\ \ arr = np.array(\[1, 2, 3, 4, 5, 6, 7\])\ \ print(arr\[4:\]) **Experiment\#2:** Slice elements from the beginning to index 4 (not included): import numpy as np\ \ arr = np.array(\[1, 2, 3, 4, 5, 6, 7\])\ \ print(arr\[:4\]) **Negative Slicing** Use the minus operator to refer to an index from the end: **Experiment\#3:** Slice from the index 3 from the end to index 1 from the end: import numpy as np\ \ arr = np.array(\[1, 2, 3, 4, 5, 6, 7\])\ \ print(arr\[-3:-1\]) **STEP** Use the step value to determine the step of the slicing: **Experiment\#4:** Return every other element from index 1 to index 5: import numpy as np\ \ arr = np.array(\[1, 2, 3, 4, 5, 6, 7\])\ \ print(arr\[1:5:2\]) **Experiment\#5:** Return every other element from the entire array: import numpy as np\ \ arr = np.array(\[1, 2, 3, 4, 5, 6, 7\])\ \ print(arr\[::2\]) **Slicing 2-D Arrays** **Experiment\#6:** From the second element, slice elements from index 1 to index 4 (not included): import numpy as np\ \ arr = np.array(\[\[1, 2, 3, 4, 5\], \[6, 7, 8, 9, 10\]\])\ \ print(arr\[1, 1:4\]) **Note:** Remember that *second element* has index 1. **Experiment\#7:** From both elements, return index 2: import numpy as np\ \ arr = np.array(\[\[1, 2, 3, 4, 5\], \[6, 7, 8, 9, 10\]\])\ \ print(arr\[0:2, 2\]) **Experiment\#8:** From both elements, slice index 1 to index 4 (not included), this will return a 2-D array: import numpy as np\ \ arr = np.array(\[\[1, 2, 3, 4, 5\], \[6, 7, 8, 9, 10\]\])\ \ print(arr\[0:2, 1:4\]) **Generate Random Number** NumPy offers the random module to work with random numbers. **Experiment\#9:** Generate a random integer from 0 to 100: from numpy import random\ \ x = random.randint(100)\ \ print(x) C. **Assignments** **Assignment1:** Insert the correct slicing syntax to print the following selection of the array: Everything from (including) the second item to (not including) the fifth item. arr = np.array(\[10, 15, 20, 25, 30, 35, 40\]) print(arr) ***Exercise13: Python Modules*** **Exercise Objectives**: **Pandas Tutorial** A. **Pandas is a Python library.** **Pandas is used to analyze data.** - - - - **What Can Pandas Do?** - - - - - **Min value?** **Pandas are also able to delete rows that are not relevant, or contains wrong values, like empty or NULL values. This is called cleaning the data.** **Where is the Pandas Codebase?** **The source code for Pandas is located at this github repository ** **github: enables many people to work on the same codebase.** B. **Experiments** **Experiment\#1:** import pandas\ mydataset = {\ \'cars\': \[\"BMW\", \"Volvo\", \"Ford\"\],\ \'passings\': \[3, 7, 2\]}\ myvar = pandas.DataFrame(mydataset)\ print(myvar) **Experiment\#2: Pandas as pd** **Pandas is usually imported under the pd alias.** import pandas as pd\ \ mydataset = {\'cars\': \[\"BMW\", \"Volvo\", \"Ford\"\],\ \'passings\': \[3, 7, 2\]}\ myvar = pd.DataFrame(mydataset)\ print(myvar) **Experiment\#3: Pandas Series** **What is a Series?** **A Pandas Series is like a column in a table.** **It is a one-dimensional array holding data of any type.** **Create a simple Pandas Series from a list:** import pandas as pd\ a = \[1, 7, 2\]\ myvar = pd.Series(a)\ print(myvar) **Experiment\#4: Labels** **If nothing else is specified, the values are labeled with their index number. First value has index 0, second value has index 1 etc.** **This label can be used to access a specified value**. Return the first value of the Series: print(myvar\[0\]) **Experiment\#5: Create Labels** **With the index argument, you can name your own labels.** **Create your own labels:** import pandas as pd\ a = \[1, 7, 2\]\ myvar = pd.Series(a, index = \[\"x\", \"y\", \"z\"\])\ print(myvar) **When you have created labels, you can access an item by referring to the label.** **Return the value of \"y\":** print(myvar\[\"y\"\]) **Experiment\#6: Key/Value Objects as Series** **You can also use a key/value object, like a dictionary, when creating a Series.** **Create a simple Pandas Series from a dictionary:** import pandas as pd\ calories = {\"day1\": 420, \"day2\": 380, \"day3\": 390}\ myvar = pd.Series(calories)\ print(myvar) **Note: The keys of the dictionary become the labels.** **Experiment\#7: To select only some of the items in the dictionary, use the index argument and specify only the items you want to include in the Series.** **Create a Series using only data from \"day1\" and \"day2\":** import pandas as pd\ calories = {\"day1\": 420, \"day2\": 380, \"day3\": 390}\ myvar = pd.Series(calories, index = \[\"day1\", \"day2\"\])\ print(myvar) **Experiment\#8: DataFrames** **Data sets in Pandas are usually multi-dimensional tables, called DataFrames.** **Series is like a column, a DataFrame is the whole table.** **Create a DataFrame from two Series:** import pandas as pd\ data = {\"calories\": \[420, 380, 390\],\ \"duration\": \[50, 40, 45\]}\ myvar = pd.DataFrame(data)\ print(myvar) **What is a DataFrame?** **A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional array, or a table with rows and columns.** **Experiment\#9: Create a simple Pandas DataFrame:** import pandas as pd\ data = {\ \"calories\": \[420, 380, 390\],\ \"duration\": \[50, 40, 45\]\ }\ \#load data into a DataFrame object:\ df = pd.DataFrame(data)\ print(df) **Result** calories duration 0 420 50 1 380 40 2 390 45 **Experiment\#10: Locate Row** **As you can see from the result above, the DataFrame is like a table with rows and columns.** **Pandas use the loc attribute to return one or more specified row(s)** **Return row 0:** \#refer to the row index:\ print(df.loc\[0\]) **Result** calories 420 duration 50 Name: 0, dtype: int64 **Note: This example returns a Pandas Series.** **Return row 0 and 1:** \#use a list of indexes:\ print(df.loc\[\[0, 1\]\]) **Result** calories duration 0 420 50 1 380 40 **Note:** When using \[\], the result is a Pandas **DataFrame**. **Experiment\#11: Named Indexes** **With the** index **argument, you can name your own indexes.** **Add a list of names to give each row a name:** import pandas as pd\ data = {\ \"calories\": \[420, 380, 390\],\ \"duration\": \[50, 40, 45\]}\ df = pd.DataFrame(data, index = \[\"day1\", \"day2\", \"day3\"\])\ print(df) **Result** calories duration day1 420 50 day2 380 40 day3 390 45 **Experiment\#12: Locate Named Indexes** **Use the named index in the loc attribute to return the specified row(s).** **Return \"day2\":** \#refer to the named index:\ print(df.loc\[\"day2\"\]) **Result** calories 380 duration 40 Name: day2, dtype: int64 **Experiment\#13: Load Files Into a DataFrame** **If your data sets are stored in a file, Pandas can load them into a DataFrame.** **Load a comma separated file (CSV file) into a DataFrame:** import pandas as pd\ df = pd.read\_csv(\'data.csv\')\ print(df) Load the CSV into a DataFrame: import pandas as pd\ \ df = pd.read\_csv(\'data.csv\')\ \ print(df.to\_string()) **Tip:** use to\_string() to print the entire DataFrame.Top of Form **Experiment\#14: If you have a large DataFrame with many rows, Pandas will only return the first 5 rows, and the last 5 rows:** Print the DataFrame without the to\_string() method: import pandas as pd\ \ df = pd.read\_csv(\'data.csv\')\ \ print(df) ***Exercise14: Python Matplotlib*** What is Matplotlib? Matplotlib is a low level graph plotting library in python that serves as a visualization utility. Pyplot Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under the plt alias: import matplotlib.pyplot as plt **Example1:** ***\#Three lines to make our compiler able to draw:*** **import sys** **import matplotlib** **matplotlib.use(\'Agg\')** **import matplotlib.pyplot as plt** **import numpy as np** **xpoints = np.array(\[0, 6\])** **ypoints = np.array(\[0, 250\])** **plt.plot(xpoints, ypoints)** **plt.show()** ***\#Two lines to make our compiler able to draw:*** **plt.savefig(sys.stdout.buffer)** **sys.stdout.flush()** **Output:** https://www.w3schools.com/python/img\_matplotlib\_pyplot.png **Matplotlib Plotting:** Plotting x and y points The plot() function is used to draw points (markers) in a diagram. By default, the plot() function draws a line from point to point. The function takes parameters for specifying points in the diagram. Parameter 1 is an array containing the points on the **x-axis**. Parameter 2 is an array containing the points on the **y-axis**. If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays \[1, 8\] and \[3, 10\] to the plot function. **Example2: Draw a line in a diagram from position (1, 3) to position (8, 10):** \#Three lines to make our compiler able to draw: import sys import matplotlib matplotlib.use(\'Agg\') import matplotlib.pyplot as plt import numpy as np xpoints = np.array(\[1, 8\]) ypoints = np.array(\[3, 10\]) plt.plot(xpoints, ypoints) plt.show() \#Two lines to make our compiler able to draw: plt.savefig(sys.stdout.buffer) sys.stdout.flush() Result: ![https://www.w3schools.com/python/img\_matplotlib\_plotting1.png](media/image15.png) Plotting Without Line To plot only the markers, you can use *shortcut string notation* parameter \'o\', which means \'rings\'. Example Draw two points in the diagram, one at position (1, 3) and one in position (8, 10): import matplotlib.pyplot as plt\ import numpy as np\ \ xpoints = np.array(\[1, 8\])\ ypoints = np.array(\[3, 10\])\ \ plt.plot(xpoints, ypoints, \'o\')\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_plot\_o.png Multiple Points You can plot as many points as you like, just make sure you have the same number of points in both axis. Example Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and finally to position (8, 10): import matplotlib.pyplot as plt\ import numpy as np\ \ xpoints = np.array(\[1, 2, 6, 8\])\ ypoints = np.array(\[3, 8, 1, 10\])\ \ plt.plot(xpoints, ypoints)\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_plotting2.png](media/image17.png) Default X-Points If we do not specify the points on the x-axis, they will get the default values 0, 1, 2, 3 etc., depending on the length of the y-points. So, if we take the same example as above, and leave out the x-points, the diagram will look like this: Example Plotting without x-points: import matplotlib.pyplot as plt\ import numpy as np\ \ ypoints = np.array(\[3, 8, 1, 10, 5, 7\])\ \ plt.plot(ypoints)\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_plotting4.png The **x-points** in the example above are \[0, 1, 2, 3, 4, 5\]. Matplotlib Markers Markers You can use the keyword argument marker to emphasize each point with a specified marker: Example[[Get your own Python Server]](https://www.w3schools.com/python/python_server.asp) Mark each point with a circle: import matplotlib.pyplot as plt\ import numpy as np\ \ ypoints = np.array(\[3, 8, 1, 10\])\ \ plt.plot(ypoints, marker = \'o\')\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_marker\_o.png](media/image19.png) Example Mark each point with a star: \...\ plt.plot(ypoints, marker = \'\*\')\ \... Result: https://www.w3schools.com/python/img\_matplotlib\_marker\_star.png Marker Reference You can choose any of these markers: **Marker** **Description** ------------ ----------------- \'o\' Circle \'\*\' Star \'.\' Point \',\' Pixel \'x\' X \'X\' X (filled) \'+\' Plus \'P\' Plus (filled) \'s\' Square \'D\' Diamond \'d\' Diamond (thin) \'p\' Pentagon \'H\' Hexagon \'h\' Hexagon \'v\' Triangle Down \'\^\' Triangle Up \'\\' Triangle Right \'1\' Tri Down \'2\' Tri Up \'3\' Tri Left \'4\' Tri Right \'\|\' Vline \'\_\' Hline Format Strings fmt You can also use the *shortcut string notation* parameter to specify the marker. This parameter is also called fmt, and is written with this syntax: *marker*\|*line*\|*color* Example Mark each point with a circle: import matplotlib.pyplot as plt\ import numpy as np\ \ ypoints = np.array(\[3, 8, 1, 10\])\ \ plt.plot(ypoints, \'o:r\')\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_marker\_fmt1.png](media/image21.png) The marker value can be anything from the Marker Reference above. The line value can be one of the following: Line Reference **Line Syntax** **Description** ----------------- -------------------- \'-\' Solid line \':\' Dotted line \'\--\' Dashed line \'-.\' Dashed/dotted line **Note:** If you leave out the *line* value in the fmt parameter, no line will be plotted. The short color value can be one of the following: Color Reference **Color Syntax** **Description** ------------------ ----------------- \'r\' Red \'g\' Green \'b\' Blue \'c\' Cyan \'m\' Magenta \'y\' Yellow \'k\' Black \'w\' White Marker Size You can use the keyword argument markersize or the shorter version, ms to set the size of the markers: Example Set the size of the markers to 20: import matplotlib.pyplot as plt\ import numpy as np\ \ ypoints = np.array(\[3, 8, 1, 10\])\ \ plt.plot(ypoints, marker = \'o\', ms = 20)\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_marker\_o\_20.png Marker Color You can use the keyword argument markeredgecolor or the shorter mec to set the color of the *edge* of the markers: Example Set the EDGE color to red: import matplotlib.pyplot as plt\ import numpy as np\ \ ypoints = np.array(\[3, 8, 1, 10\])\ \ plt.plot(ypoints, marker = \'o\', ms = 20, mec = \'r\')\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_marker\_o\_mec.png](media/image23.png) You can use the keyword argument markerfacecolor or the shorter mfc to set the color inside the edge of the markers: Example Set the FACE color to red: import matplotlib.pyplot as plt\ import numpy as np\ \ ypoints = np.array(\[3, 8, 1, 10\])\ \ plt.plot(ypoints, marker = \'o\', ms = 20, mfc = \'r\')\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_marker\_o\_mfc.png Use *both *the mec and mfc arguments to color the entire marker: Example Set the color of both the *edge* and the *face* to red: import matplotlib.pyplot as plt\ import numpy as np\ \ ypoints = np.array(\[3, 8, 1, 10\])\ \ plt.plot(ypoints, marker = \'o\', ms = 20, mec = \'r\', mfc = \'r\')\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_marker\_o\_mec\_mfc.png](media/image25.png) You can also use [[Hexadecimal color values]](https://www.w3schools.com/colors/colors_hexadecimal.asp): Example Mark each point with a beautiful green color: \...\ plt.plot(ypoints, marker = \'o\', ms = 20, mec = \'\#4CAF50\', mfc = \'\#4CAF50\')\ \... Result: https://www.w3schools.com/python/img\_matplotlib\_marker\_o\_hex.png Or any of the [[140 supported color names]](https://www.w3schools.com/colors/colors_names.asp). Example Mark each point with the color named \"hotpink\": \...\ plt.plot(ypoints, marker = \'o\', ms = 20, mec = \'hotpink\', mfc = \'hotpink\')\ \... Result: ![https://www.w3schools.com/python/img\_matplotlib\_marker\_hotpink.png](media/image27.png) Matplotlib Line Linestyle You can use the keyword argument linestyle, or shorter ls, to change the style of the plotted line: Example Use a dotted line: import matplotlib.pyplot as plt\ import numpy as np\ \ ypoints = np.array(\[3, 8, 1, 10\])\ \ plt.plot(ypoints, linestyle = \'dotted\')\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_line\_dotted.png Example Use a dashed line: plt.plot(ypoints, linestyle = \'dashed\')\ \ Result: ![https://www.w3schools.com/python/img\_matplotlib\_line\_dashed.png](media/image29.png) Shorter Syntax The line style can be written in a shorter syntax: linestyle can be written as ls. dotted can be written as :. dashed can be written as \--. Example Shorter syntax: plt.plot(ypoints, ls = \':\') Result: https://www.w3schools.com/python/img\_matplotlib\_line\_dotted.png Line Styles You can choose any of these styles: **Style** **Or** --------------------- --------------- \'solid\' (default) \'-\' \'dotted\' \':\' \'dashed\' \'\--\' \'dashdot\' \'-.\' \'None\' \'\' or \' \' Line Color You can use the keyword argument color or the shorter c to set the color of the line: Example Set the line color to red: import matplotlib.pyplot as plt\ import numpy as np\ \ ypoints = np.array(\[3, 8, 1, 10\])\ \ plt.plot(ypoints, color = \'r\')\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_line\_red.png](media/image30.png) You can also use [[Hexadecimal color values]](https://www.w3schools.com/colors/colors_hexadecimal.asp): Example Plot with a beautiful green line: \...\ plt.plot(ypoints, c = \'\#4CAF50\')\ \... Result: https://www.w3schools.com/python/img\_matplotlib\_line\_hex.png Or any of the [[140 supported color names]](https://www.w3schools.com/colors/colors_names.asp). Example Plot with the color named \"hotpink\": \...\ plt.plot(ypoints, c = \'hotpink\')\ \... Result: ![https://www.w3schools.com/python/img\_matplotlib\_line\_hotpink.png](media/image32.png) Line Width You can use the keyword argument linewidth or the shorter lw to change the width of the line. The value is a floating number, in points: Example Plot with a 20.5pt wide line: import matplotlib.pyplot as plt\ import numpy as np\ \ ypoints = np.array(\[3, 8, 1, 10\])\ \ plt.plot(ypoints, linewidth = \'20.5\')\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_line\_lw.png Multiple Lines You can plot as many lines as you like by simply adding more plt.plot() functions: Example Draw two lines by specifying a plt.plot() function for each line: import matplotlib.pyplot as plt\ import numpy as np\ \ y1 = np.array(\[3, 8, 1, 10\])\ y2 = np.array(\[6, 2, 7, 11\])\ \ plt.plot(y1)\ plt.plot(y2)\ \ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_line\_two.png](media/image34.png) You can also plot many lines by adding the points for the x- and y-axis for each line in the same plt.plot() function. (In the examples above we only specified the points on the y-axis, meaning that the points on the x-axis got the the default values (0, 1, 2, 3).) The x- and y- values come in pairs: Example Draw two lines by specifiyng the x- and y-point values for both lines: import matplotlib.pyplot as plt\ import numpy as np\ \ x1 = np.array(\[0, 1, 2, 3\])\ y1 = np.array(\[3, 8, 1, 10\])\ x2 = np.array(\[0, 1, 2, 3\])\ y2 = np.array(\[6, 2, 7, 11\])\ \ plt.plot(x1, y1, x2, y2)\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_line\_two.png Matplotlib Labels and Title Create Labels for a Plot With Pyplot, you can use the xlabel() and ylabel() functions to set a label for the x- and y-axis. Example[[Get your own Python Server]](https://www.w3schools.com/python/python_server.asp) Add labels to the x- and y-axis: import numpy as np\ import matplotlib.pyplot as plt\ \ x = np.array(\[80, 85, 90, 95, 100, 105, 110, 115, 120, 125\])\ y = np.array(\[240, 250, 260, 270, 280, 290, 300, 310, 320, 330\])\ \ plt.plot(x, y)\ \ plt.xlabel(\"Average Pulse\")\ plt.ylabel(\"Calorie Burnage\")\ \ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_labels.png](media/image35.png) Create a Title for a Plot With Pyplot, you can use the title() function to set a title for the plot. Example Add a plot title and labels for the x- and y-axis: import numpy as np\ import matplotlib.pyplot as plt\ \ x = np.array(\[80, 85, 90, 95, 100, 105, 110, 115, 120, 125\])\ y = np.array(\[240, 250, 260, 270, 280, 290, 300, 310, 320, 330\])\ \ plt.plot(x, y)\ \ plt.title(\"Sports Watch Data\")\ plt.xlabel(\"Average Pulse\")\ plt.ylabel(\"Calorie Burnage\")\ \ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_title.png Set Font Properties for Title and Labels You can use the fontdict parameter in xlabel(), ylabel(), and title() to set font properties for the title and labels. Example Set font properties for the title and labels: import numpy as np\ import matplotlib.pyplot as plt\ \ x = np.array(\[80, 85, 90, 95, 100, 105, 110, 115, 120, 125\])\ y = np.array(\[240, 250, 260, 270, 280, 290, 300, 310, 320, 330\])\ \ font1 = {\'family\':\'serif\',\'color\':\'blue\',\'size\':20}\ font2 = {\'family\':\'serif\',\'color\':\'darkred\',\'size\':15}\ \ plt.title(\"Sports Watch Data\", fontdict = font1)\ plt.xlabel(\"Average Pulse\", fontdict = font2)\ plt.ylabel(\"Calorie Burnage\", fontdict = font2)\ \ plt.plot(x, y)\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_title\_fontdict.png](media/image37.png) Position the Title You can use the loc parameter in title() to position the title. Legal values are: \'left\', \'right\', and \'center\'. Default value is \'center\'. Example Position the title to the left: import numpy as np\ import matplotlib.pyplot as plt\ \ x = np.array(\[80, 85, 90, 95, 100, 105, 110, 115, 120, 125\])\ y = np.array(\[240, 250, 260, 270, 280, 290, 300, 310, 320, 330\])\ \ plt.title(\"Sports Watch Data\", loc = \'left\')\ plt.xlabel(\"Average Pulse\")\ plt.ylabel(\"Calorie Burnage\")\ \ plt.plot(x, y)\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_title\_loc.png Matplotlib Bars Creating Bars With Pyplot, you can use the bar() function to draw bar graphs: Example[[Get your own Python Server]](https://www.w3schools.com/python/python_server.asp) Draw 4 bars: import matplotlib.pyplot as plt\ import numpy as np\ \ x = np.array(\[\"A\", \"B\", \"C\", \"D\"\])\ y = np.array(\[3, 8, 1, 10\])\ \ plt.bar(x,y)\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_bars1.png](media/image39.png) The bar() function takes arguments that describes the layout of the bars. The categories and their values represented by the *first *and *second *argument as arrays. Example x = \[\"APPLES\", \"BANANAS\"\]\ y = \[400, 350\]\ plt.bar(x, y) Horizontal Bars If you want the bars to be displayed horizontally instead of vertically, use the barh() function: Example Draw 4 horizontal bars: import matplotlib.pyplot as plt\ import numpy as np\ \ x = np.array(\[\"A\", \"B\", \"C\", \"D\"\])\ y = np.array(\[3, 8, 1, 10\])\ \ plt.barh(x, y)\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_bars2.png Bar Color The bar() and barh() take the keyword argument color to set the color of the bars: Example Draw 4 red bars: import matplotlib.pyplot as plt\ import numpy as np\ \ x = np.array(\[\"A\", \"B\", \"C\", \"D\"\])\ y = np.array(\[3, 8, 1, 10\])\ \ plt.bar(x, y, color = \"red\")\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_bars\_red.png](media/image41.png) Color Names You can use any of the [[140 supported color names]](https://www.w3schools.com/colors/colors_names.asp). Example Draw 4 \"hot pink\" bars: import matplotlib.pyplot as plt\ import numpy as np\ \ x = np.array(\[\"A\", \"B\", \"C\", \"D\"\])\ y = np.array(\[3, 8, 1, 10\])\ \ plt.bar(x, y, color = \"hotpink\")\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_bars\_hotpink.png Color Hex Or you can use [[Hexadecimal color values]](https://www.w3schools.com/colors/colors_hexadecimal.asp): Example Draw 4 bars with a beautiful green color: import matplotlib.pyplot as plt\ import numpy as np\ \ x = np.array(\[\"A\", \"B\", \"C\", \"D\"\])\ y = np.array(\[3, 8, 1, 10\])\ \ plt.bar(x, y, color = \"\#4CAF50\")\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_bars\_green.png](media/image43.png) Bar Width The bar() takes the keyword argument width to set the width of the bars: Example Draw 4 very thin bars: import matplotlib.pyplot as plt\ import numpy as np\ \ x = np.array(\[\"A\", \"B\", \"C\", \"D\"\])\ y = np.array(\[3, 8, 1, 10\])\ \ plt.bar(x, y, width = 0.1)\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_bars\_thin.png The default width value is 0.8 **Note:** For horizontal bars, use height instead of width. Bar Height The barh() takes the keyword argument height to set the height of the bars: Example Draw 4 very thin bars: import matplotlib.pyplot as plt\ import numpy as np\ \ x = np.array(\[\"A\", \"B\", \"C\", \"D\"\])\ y = np.array(\[3, 8, 1, 10\])\ \ plt.barh(x, y, height = 0.1)\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_barh\_height.png](media/image45.png) Matplotlib Histograms Histogram A histogram is a graph showing *frequency* distributions. It is a graph showing the number of observations within each given interval. Example: Say you ask for the height of 250 people, you might end up with a histogram like this: https://www.w3schools.com/python/img\_matplotlib\_histogram1.png You can read from the histogram that there are approximately: 2 people from 140 to 145cm\ 5 people from 145 to 150cm\ 15 people from 151 to 156cm\ 31 people from 157 to 162cm\ 46 people from 163 to 168cm\ 53 people from 168 to 173cm\ 45 people from 173 to 178cm\ 28 people from 179 to 184cm\ 21 people from 185 to 190cm\ 4 people from 190 to 195cm Create Histogram In Matplotlib, we use the hist() function to create histograms. The hist() function will use an array of numbers to create a histogram, the array is sent into the function as an argument. For simplicity we use NumPy to randomly generate an array with 250 values, where the values will concentrate around 170, and the standard deviation is 10. Learn more about [[Normal Data Distribution]](https://www.w3schools.com/python/python_ml_normal_data_distribution.asp) in our [[Machine Learning Tutorial]](https://www.w3schools.com/python/python_ml_getting_started.asp). Example A Normal Data Distribution by NumPy: import numpy as np\ \ x = np.random.normal(170, 10, 250)\ \ print(x) Result: This will generate a *random* result The hist() function will read the array and produce a histogram: Example A simple histogram: import matplotlib.pyplot as plt\ import numpy as np\ \ x = np.random.normal(170, 10, 250)\ \ plt.hist(x)\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_histogram1.png](media/image46.png) Matplotlib Pie Charts Creating Pie Charts With Pyplot, you can use the pie() function to draw pie charts: Example[[Get your own Python Server]](https://www.w3schools.com/python/python_server.asp) A simple pie chart: import matplotlib.pyplot as plt\ import numpy as np\ \ y = np.array(\[35, 25, 25, 15\])\ \ plt.pie(y)\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_pie1.png As you can see the pie chart draws one piece (called a wedge) for each value in the array (in this case \[35, 25, 25, 15\]). By default the plotting of the first wedge starts from the x-axis and moves *counterclockwise*: ![https://www.w3schools.com/python/img\_matplotlib\_pie\_start.png](media/image48.png) **Note:** The size of each wedge is determined by comparing the value with all the other values, by using this formula: The value divided by the sum of all values: x/sum(x) Labels Add labels to the pie chart with the labels parameter. The labels parameter must be an array with one label for each wedge: Example A simple pie chart: import matplotlib.pyplot as plt\ import numpy as np\ \ y = np.array(\[35, 25, 25, 15\])\ mylabels = \[\"Apples\", \"Bananas\", \"Cherries\", \"Dates\"\]\ \ plt.pie(y, labels = mylabels)\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_pie\_labels.png Start Angle As mentioned the default start angle is at the x-axis, but you can change the start angle by specifying a startangle parameter. The startangle parameter is defined with an angle in degrees, default angle is 0: ![https://www.w3schools.com/python/img\_matplotlib\_pie\_angles.png](media/image50.png) Example Start the first wedge at 90 degrees: import matplotlib.pyplot as plt\ import numpy as np\ \ y = np.array(\[35, 25, 25, 15\])\ mylabels = \[\"Apples\", \"Bananas\", \"Cherries\", \"Dates\"\]\ \ plt.pie(y, labels = mylabels, startangle = 90)\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_pie\_angle\_90.png Explode Maybe you want one of the wedges to stand out? The explode parameter allows you to do that. The explode parameter, if specified, and not None, must be an array with one value for each wedge. Each value represents how far from the center each wedge is displayed: Example Pull the \"Apples\" wedge 0.2 from the center of the pie: import matplotlib.pyplot as plt\ import numpy as np\ \ y = np.array(\[35, 25, 25, 15\])\ mylabels = \[\"Apples\", \"Bananas\", \"Cherries\", \"Dates\"\]\ myexplode = \[0.2, 0, 0, 0\]\ \ plt.pie(y, labels = mylabels, explode = myexplode)\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_pie\_explode.png](media/image52.png) Shadow Add a shadow to the pie chart by setting the shadows parameter to True: Example Add a shadow: import matplotlib.pyplot as plt\ import numpy as np\ \ y = np.array(\[35, 25, 25, 15\])\ mylabels = \[\"Apples\", \"Bananas\", \"Cherries\", \"Dates\"\]\ myexplode = \[0.2, 0, 0, 0\]\ \ plt.pie(y, labels = mylabels, explode = myexplode, shadow = True)\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_pie\_shadow.png Colors You can set the color of each wedge with the colors parameter. The colors parameter, if specified, must be an array with one value for each wedge: Example Specify a new color for each wedge: import matplotlib.pyplot as plt\ import numpy as np\ \ y = np.array(\[35, 25, 25, 15\])\ mylabels = \[\"Apples\", \"Bananas\", \"Cherries\", \"Dates\"\]\ mycolors = \[\"black\", \"hotpink\", \"b\", \"\#4CAF50\"\]\ \ plt.pie(y, labels = mylabels, colors = mycolors)\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_pie\_color.png](media/image54.png) You can use [[Hexadecimal color values]](https://www.w3schools.com/colors/colors_hexadecimal.asp), any of the [[140 supported color names]](https://www.w3schools.com/colors/colors_names.asp), or one of these shortcuts: \'r\' - Red\ \'g\' - Green\ \'b\' - Blue\ \'c\' - Cyan\ \'m\' - Magenta\ \'y\' - Yellow\ \'k\' - Black\ \'w\' - White Legend To add a list of explanation for each wedge, use the legend() function: Example Add a legend: import matplotlib.pyplot as plt\ import numpy as np\ \ y = np.array(\[35, 25, 25, 15\])\ mylabels = \[\"Apples\", \"Bananas\", \"Cherries\", \"Dates\"\]\ \ plt.pie(y, labels = mylabels)\ plt.legend()\ plt.show() Result: https://www.w3schools.com/python/img\_matplotlib\_pie\_legend.png Legend With Header To add a header to the legend, add the title parameter to the legend function. Example Add a legend with a header: import matplotlib.pyplot as plt\ import numpy as np\ \ y = np.array(\[35, 25, 25, 15\])\ mylabels = \[\"Apples\", \"Bananas\", \"Cherries\", \"Dates\"\]\ \ plt.pie(y, labels = mylabels)\ plt.legend(title = \"Four Fruits:\")\ plt.show() Result: ![https://www.w3schools.com/python/img\_matplotlib\_pie\_legend\_title.png](media/image56.png) **Revised By: Dr. Bilal Hani Al-hawasheen** **Head of Department: Signature:**