0% found this document useful (0 votes)
11 views

Python Packages Class 10

Packages in Python

Uploaded by

suchi.marts
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
11 views

Python Packages Class 10

Packages in Python

Uploaded by

suchi.marts
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 35
Chapter 4 UO OWL PROGRAMMING WITH PYTHON ESS ‘+ Modules and Packages ‘= Tuples in Python + Some More Programs + Difference between List and Tuple ‘ Usts in Python. « Strings e Modules and Packages ‘A module is a python file containing a collection of Python statements, functions and global variables. Its created with an extension .py. A collection of relevant modules saved under the same directory and a name is called a Package. There are various packages related to various purposes available for free to be used in Python. Scope and Uses of Packages Since a package organizes related modules, sub-packages, and resources into a hierarchical structure it provides a large set of predefined functions, classes, and methods for various tasks. The scope of the packages lies in: Organizing code: It organises the related modules into a hierarchical structure, making it more manageable and easier to navigate. Code reusabiltiy: Since the code is created once and can be used by anybody. Thus it provides the feature of reuseability of the code and eliminating the changes of duplicating code. Distribution and installation: Packages allow you to distribute and install code as a unit. You can package your code and resources into a distributable package format like tar.gz file. This makes it easier to share your code with others or deploy it on different systems. os corre Creer (-} Coding & Computational Thinking DP) Video Session Scan the QR code or visit the following link to watch the video: Modules in Python Explained | Python Built in Modules | Python Tutorial for Beginners ttps://iamw.youtube.com/watch?v=1oFneicTall Introduction to Data and Programming with Python | 183 4 LT Modules and Libraries Modules in Python are individual files that contain code, functions, or classes for code organisation and reusability, ‘They can be imported into other files using the import statement. whereas, Libraries in Python are collections of precompiled code, functions, of resources that provide additional functionality to Python developers. They solve specific problems or offer specific capabilities and can be installed and imported into Python projects. Modules help organize and reuse code within a program, while libraries extend Python's capabilities by providing ready-made solutions for various tasks or domains. Let us now study in detail the use of some of these packages: NumPy (‘Numerical Python’) NumPy is a powerful open-source scientific package that stands for ‘Numerical Python’. It uses mathematical and logical operations for handling large datasets through powerful data structure-n-dimensional arrays that also speeds up data processing. NumPy is the first step in learning to become a Python data scientist in the future Various other libraries like Pandas, Matplotlib, and Scikit-learn are built on using some concepts of this magical library. It can also be easily interfaced with other Python packages and provides tools for integrating with other programming languages like C, C++ etc. If you are using basic Python installed through https://www.python.org website then the NumPy package is not included by default. You need to install it separately. NumPy can be installed by typing following command: pip install Numpy Once it is installed, it can be readily used in any Python code by using import keyword as shown below: Numpy can also be imported into the Jupyter Notebook by using the given statement : >>> import numpy # this will import the complete numpy # package oR >>> import numpy as npy # this will import numpy and referred # as npy oR >>> from numpy import array fthis will import ONLY arrays #from whole numpy package oR >>> from numpy import array as ary #this will import ONLY farrays and referred as ary Arrays are an ordered collection of values of the same data types that can be arranged in one or more dimensions. They can be numbers, characters, Booleans, etc. The elements are referred to using index numbers(position) that start with 0 . Almost all Programming languages support arrays in one form or another. y of one dimension is called a(Vector)an array having two dimensions is called avi) (Matrix 3nd an array with le dimensions is calledh-dimension array ) native to Python lists because they _ ing Items effective tly, The NumPy library has a large set of ~ built-in functions available in the form of modules and packages for creating, manipulating, and transforming ~7 NumPy arrays. 2@™ 184 | Touchpad Robotics & Artificial ntelligence-x ae tage eR Ene g eae EEE \ cL / /toms Q Ditbenema bebweer NuroPy roy and Py aalvast / Z _Soifwe compare NumPy-Arrays and Pythons then ( « Array is a collectic of ae Hon of homogeneous values whereas Listas studied in lass 9 isa collection of heterogeneous + In Arrays data of Fone toe ee Hoes Not sipport data of another type wherees In List ¢ works perfectly by using data of one typeby converting into another datatype © Arrays can be a = SEO caren vatl.throuah package -NumPy and accuples less memory space whereas List occupies 'y space and can be accessed Girectly in Python without any package support. + Inarrays the mathematical operators ¢ an be directly used whereas in list the mathematical operators cannot be used directly on it instead need to be Used separately on individual elements. Arrays are mainly used for, “Mathematical operations where Lists are mainly used for data management. + Syntax of creating array is: import numpy marks=; Syntax of creating a list is: marks= wumpy.array([34,23,41,42]) 34,23,41, 42) Creating an Array using NumPy: + Creating one dimensional array: import numpy rollno = numpy.array({1, 2, 3]) print (rol1no) Output: {1 253]| * Create a sequential 1 D array with values as multiples of 10 from 10 to 100: import numpy as np a = np.arange(10,101,10) print (a) Output: [10 20 30 40 50 60 70 80 90 100) ‘Another example : >>>import numpy as np >>> student = np.array((11,'Amita’,92.5]) >>> student * Creating 1 D array with 4 random values: import numpy as np a = np.random. random (4) print (a) Output: [0.9290503 0.89991053 0.7563874 0.89570953) * Creating a 3x4 array with random integer values less than 10: import numpy as np @ = np.random.randint (10, size=(3,4)) Introduction to Data and Programming with Python | 185 LT print (a) import numpy as np a = np.ones((3,4)) print (a) Output: LS) Tees) Goeeee te) Creating two dimensional array of 3 rows and 3 columns with all zeroes as value: import numpy as np @ = np.zeros((3,3)) print (a) Output: [[0. 0. 0.) [0. 0. 0.) {0. 0. 0.}] Creating two dimensional array of 3 rows and 4 columns with all six as value: import numpy as np a = np. full ((3,4),6) print (a) Output: [16 6 6 6] [6 6 6 6) (6 6 6 6}} We can create two dimensional (2-D) arrays by passing nested lists to the array() function, import numpy as np a = np.array((11,'Arshia',93],[15,'Riddhi',95]) print (a) Output: {{11, 'Arshia', 93] (15, 'Riddhi', 95]) 186 | Touchpad Robotics & Artificial Intelligence-X \_AN #Experiential Learning Type “import this" in your Python IDLE and you will find a poem written by Tim Peters, a major contributer to the Python community, Using Mathematical operators on integer array: period Syntax Output eo import numpy as np 1294) (exponential) marks1 = np.array((1,2,3,4)) marks1 to the marks2=np,array ({2/1,2,1]) is: [1 827 Print (marksi**marks2) Print ("marks1 to the power of 3 is 2",marks1**3) + import nunpy as np 1214 911) (Addition) marks1 = np.array({7,8,5,4]) 2 marks extra : [ marks2=np.array((5,6,4,71) 7 61 print (marksitmarks2) print ("2 marks extra: ",marks1+2) 5 import numpy as np (ees (subtraction) marks1 = np.array({7,8,5,41) 2 marks deducted : (5 6 marks2=np.array((5,6/4/7]) eee print (marksi-marks2) print ("2 marks deducted :",marks1-2) . import numpy as np [35 48 20 28 (Multiplication) marks = np.array({7,8,5,4)) 2 marks multiplied : [14 marks2=np.array((5, 6/4/71) 16 10 8) print (marks1*marks2) print ("2 marks multiplied :",marks1*2) / import numpy as np omen (divide) marks1 = np.array([10,20,30,40]) 2 marks divided : [ 5. 10. 15. 20.) marks2=np.array ((2,4,3,5]) print (marks1/marks2) marks divided :",marks1/2) print (" Introduction to Data and Programming with Python | 187»; LUT a W import numpy as np CS eno oP (floor division) marks1 = np.array(({10,20,30,40]) 2 ee divided using floor division: ( § 10 15 marks2=np.array ((2,473/51) A print (marks1//marks2) print ("2 marks divided using floor division:",marks1//2) % import numpy as np {0 0 0 0) (Remainder of marks1 = np.array({10,20, 30,401) remainder of division; division) marks2=np.array({1,2,3,41) 201) print (marks1¢marks2) print ("remainder of division:",marks183) Some of the basic mathematical operations can also be done by using built-in functions like: 1. Addition: np.add0) 2. Subtraction: np subtract() 3. Multiplication: np. multiply() 4. Division: np.divide) 5. Remainder: np.remainder) Type of an object type(ARR) ie array gives the ARR.ndim. dimensions of an array as an integer value. Arrays can be 1-D, 2-D orn-D. Shape of an array ARRshape ie. length of the array of each dimension Size of an array ARRsize ie. counts the total _number of elements WH Some important attributes and functions of NumPy Array: import numpy as np ARR = np.array({1,2,3,4]) print (type (ARR) ) import numpy as np 2 ARR = np.array([[1,2,3,4], 13,4,5,61)) print (ARR.ndim) import numpy as np ARR = np.array(({1,2,3,4], [3,4,5,611) print (ARR. shape) (2, 4) import numpy as np 8 ARR = np-array({(1,2,3,4], (3,4,5,61]) print (ARR. size) 188 | Touchpad Robotics & Artifical Inteligence-x Datatype of elements stored in the array Maximum value in the element of the array Row wise & column wise maximum value Row wise & column wise minimum value ‘Sum of all values inthe given array ARRadtype ARRmax() ARR.max(axis=1) for row ARR.max(axis=0) for column ARR.min(axis=1) for row for column ARRsum() import numpy as np. ARR = np.array({{1,2,3,4), (3,4,5,6)1) Print (ARR.dtype) import numpy as np ARR = np.array({(10,34,45, 23,1211) Print (ARR.max ()) import numpy as np ARR = np.array({{11,2,13,4], [3,4,5,6})) Print ("Rowwise max :", ARR.max (axis=1) ) Print ("Column wise max ARR.max (axis=0)) import numpy as np ARR = np.array({{11,2,13,4], (3,4,5,611) print ("Rowwise min :", ARR.min (axis=1)) print ("Column wise min :* ARR.min (axis=0)) import numpy as np ARR np.array({{11,2,13, 4], [3,4,5,61)) print ("Row Wise sum :", ARR. sum(axis=1)) print ("Column wise sum ARR. sum (axis=0)) print ("sum is :", ARR. sum()) tion to Data and Programming with Python | 189 & inked 45 Rowwise max : (13 6] Column wise max : [11 413 6) Rowwise min + [2 3] Column wise min : [3 254) Rowwise sum : [30 18] Column wise sum : (14 6 18 10) sum is: 48 LT Sorting the array ARRsort() a= np.array({12, 4, -10, 23, 29, 15, -1, 45, 33, 37, -14]) # Creating a 1-D (-14 -10 -1 4 12 WCE A) ei” eh) 45) Numpy array tt 5 Plz print (np,sort(a)) # 18) Printing the sorted [+10 3 10 nunpy array 1) # We can also sort array ce y 3 row wise and column wise! 10) ble "np.areay({t=9) 5, 18, (10° 11 i899 9, 12}, (10,' 11, 3, -5, 12) -10}]) # Creating a 2-D Numpy array print (np.sort(b, axis = 1)) # Axis = 1 performs the sorting function row-wise print (np.sort (b, axis = 0)) + Axis = 0 performs the sorting function columns- wise Pandas(PANel Data) Panda is an open-source Python library used for data manipulation and data analysis. It provides a very strong feature of using three important data structures - Series (1-dimensional) DataFrame (2-dimensional) and Panel(3- -dimensional) for smooth processing and analysis of data, regardless of its origin, The data actually need not be labelled at all to be placed into a Pandas data structure. Pandas was created by Wes McKinney in 2008 and has derived its name from both "Panel Data”, and "Python Data Analysis" which means using a statistical method of analysing the data taken from the observations about different cross sections over the period of time. Pandas libraries are built on NumPy so to work in Pandas the prerequisite is to get familiar with NumPy and install it It gives us a single, convenient place to do most of our data analysis and visualisation work. Data required for Pandas can be taken as : Tabular data with heterogeneously-typed columns, as in an SQL table or Excel spreadsheet Ordered and unordered (not necessarily fixed-frequency) time series data. Arbitrary matrix data (homogeneously typed or heterogeneous) with row and column labels. Any other form of observational / statistical data sets. Installing Pandas To install Pandas from command line, we need to type in: pip install pandas A\llibraries including NumPy and Pandas can be installed only when Python is already installed on that system. $. 190 | Touchpad Robotics & Artificial Intelligence-x ~AN Cee eee ee ee ec a eee ey ee cee eet et Data Structures in Pandas ‘Two commonly used data structures in Pandas are: © Series # Dataframes Series Series is a one-dimensional array that can store data of any type like integer, string, float, python objects, ete. We can also say that the Pandas series is just like a column of a spreadsheet. The values can be referred to by using data axis labels also called index. Indexes are of two types: positional index and labelled index, Positional indexes are integers starting with default 0 whereas labelled indexes are user defined labels that can be of any datatype and can be used as an index. Pandas Series can be created by loading the datasets from existing storage like SQL Database, CSV file, and Excel file Pandas Series can also be created from the lists, dictionary, and from any other scalar value. Different ways of creating Series are: + Creating an empty series xt pandas as pd Emp=pd. Series () + Creating a Series from a NumPy array import pandas as pd port numpy as np data = np.array((10, 30, 50]) sl - pd.Series (data) print (s1) Output: o 10 1 30 2 50 dtype: inte4 ‘+ Creating series using labelled index import pandas as pd friends = pd.Series({"Rohan", "Susan", "James"], index=[11,22,33]) print (friends) Output: 11 Rohan 22 susan A dtype: object * Creating a Series from a Python list import pandas as pd cities = ‘Delhi’, ‘Mumbai’, ‘Chennai', ‘Kolkata'] 82 = pd, Series (cities) print (s2) Introduction to Data and Programming with Python | 191 $ LM Output: 0 delhi 1 Mumbai 2 Chennai Kolkata dtype: object Creating series using labelled index mport pandas as pd ath= "June", "August", "October", "December" s4 = pd.Series(month, index = [6,8,10,12]) print (s4) Output: 6 June 8 August October 12 December Stype: object Creating a Series from a Python dictionary import pandas as pd month={6:"June", 8:"August", 10: "October", 12:"December") 85 = pd.Series(dict) print (s5) Output: 6 June August 10 October 12 December dtype: object File access using Panda Pandas can be accessed by using import: import pandas as pd To save the csv file into a variable : s= pd.read_csv("Student data.csv") To print the first five rows of the file: print (s.head(5)) To print the first ten rows of the file: print (s,head(10)) ys 192 | Touchpad Robotics & Artifical intelligence-x. I —_coCo OC EE, , To sort the records in the file: 1 = s.sort_values(by="Name", ascending = False) print (s1.head (5) ) + Accessing the element of the Series The elements can be accessed using either positional index or labelled index. | For example: import pandas as pd ies ([96, 191,93], inde: print ("Using Labelled index | eae "Shashi", "Sonali", "Neha, "Rajeev"}) + Marks ["Sonali"]) Jsing Positional index “, Marks{1]) pril Output: Using Labelled index 92 | Using Positional index 92 To print 2 elements print (Marks [[2,311) Output: Nena 91 Rajeev 93 dtype: inted print (Marks [["Sonali", "Rajeev"]]) Output Sonali 92 Rajeev 93 Gtype: int64 + Elements can be accessed using Slicing as follows: print(Marks[1:3]) #excludes the value at index position 3 Output: | sonatt $2 Neha 91 dtype: int64 print (Marks ["Sonali' Output: Sonali 92 Rajeev")) fincludes the value at labelled index Neha 91 Rajeev 93 dtype: int64 print (Marks Output: Rajeev 93 | Introduction to Data and Programming with Python | 193 a ll LT 91 Sonali 92 Neha Shashi 96 dtype: intés Attributes of the Series Attributes Description name Aname to a series is given indexname value size empty A name to an index is given Returns the list of values in the series Returns the number of value in the series Returns True if the series is empty. Built in Functions in Series Function headin) Description Returns the first n members of the series. If n not specified then by default first five members are displayed. m= 194 | Touchpad Robotics & Artificial Intelligence-x trLright ° diamond 2. 202 | Touchpad Robotics & Artificial Intelligence-X ae RCRA ANIONS Colours ‘We can either use character codes or the color names as values to the parameter color in the plot( Linewidth and Line Style The linewidth is given in pixels. The default is 1 pixel. You can increase the number to increase the width Linestyle can be “solid”, “dotted”, "dashed" or "dashdot*. Let us now make some graphs : Plotting a Line Chart ‘+ Single line chart import matplotlibipyplot as plt city=["Delhi', 'Mumbai', ‘Chennai’, 'Kolkata'} temp=[35, 21, 40, 22] plt.xlabel ("Metro Cities") plt.ylabel(*Temp in Celsius’) plt.title('Temperature Study of the Day’) plt.plot (city, temp, marker='*',markersiz linewidth=2, linestyle='dashdot') 0, color="red", plt.show() The above code will create a line graph as shown below: Temperature Study of the Day 400 3754 350) * 2 a2. 300: Es 250: 25. Delhi Mumbai Chennai Kol Metro Cities Introduction to Data and Programming with Python | 203 $ 5,21, 40,22] day2=[30,25,3 1201 day3=[24,29, 42,24] plt-xlabel (‘Metro Cities") pit.ylabel (‘Temp in Celsius*) plt.title("Temperature Study of the Day’) plt.plot (city, dayl) plt.plot (city, day2) 1t.plot (city, day3) plot.show () The above code will create a multiple line graph as shown below: ‘Temperature Study of the Day 40 335 8 £30. 5 2 20. Delhi Mumbai Chennai Kolkata Metro Cities Plotting a bar chart It is used to plot data using rectangular bars or columns. It is generally used to compare values of two different categories. Example: marks of 5 subjects to compare, rise in population in five years.changing fuel price every month. Various versions of bar charts exist lke single bar chart, double bar chart, etc. can be used. Matplotlib uses a built-in function - bar ( and plot() to create bar charts. Using bard) # Data for the x-axis and y-axis "Dell +, Mumbai", 'Chennai', 'Kolkata'] day1=[35,21, 40,22] # Creating the bar chart plt.bar(city, dayl) # Adding labels and title 24. 204 | Touchpad Robotics & Artificial Inteligence-x ae plt.xlabel('Metro Cities") plt.ylabel ("Temp in plt.title(’ Celsius') Temperature Study of the Day’) # Displaying the chart plt.show () ‘Another example is: Example: Temperature Study of the Day 3B as. ‘Temp in Celsius Mumbai Chennai Metro Cities: Kolkata import matplotlib.pyplot as pit marks = (23, 45, 34, plt-bar (["Eng 41, 13,49) Maths", "Science", "Sst","2nd Lang", "Computers"], marks) plt.title('Bar Chart") plt.xlabel ("Subjects") plt.ylabel (‘Marks") plt.show() Output: Bar Chart. 50. Maths. Science Sst 2nd Lang Computers Subjects Eng Introduction to Data and Programming with Python | 205 & amy © Using plot0for creating Single bar import matplotlib.pyplot as pit import pandas as pd # Create a DataFrame 30, 25,36, 201) di={ "Cities": ('Delhi, "Mumbai", ‘Chennai’, 'Kolkata'), ‘Day’: dé = pd.DataFrame (di) # Creating the bar chart dt.plot (x='Cities', y="Dayl', kind="bar') # Adding labels and title Plt.xlabel ("Metro Cities!) plt.ylabel ("Temp in Celsius") plt.title (‘Temperature Study of the Day!) # Displaying the chart plt.show() ‘Temperature Study of the Day ‘Temp in Celsius eth Mumbai Kolkata 2 é Metro Cities * Using plot0for creating Multiple bars import matplotlib.pyplot as plt import pandas as pd # Create a DataFrame din{"Cities':['Delni, ‘Mumbai', ‘Chennai', 'Kolkata’), 'Dayl': (30,25, 36,20], "Day2" : (30,25,36, 20], 'Day3':[24, 29, 42,24]) df = pd.DataFrame(d1) dt.set_index(‘Cities', inplace=True) 4 Creating the bar chart dt .plot (kind="bar') 4 Adding labels and title plt.xlabel (‘Metro Cities") a+ 206 | Touchpad Robotics & Artificial Intelligence-x Ww 1t.ylabel ("Temp in Celsius’) 1t.title(*Temperature study of the Day’) # Displaying the chart plt-show() Temperature Study of the Day Temp in Celsius 0 5 ps = 3 3 2 g a - & 3 é s Metro Ces Plotting a Histogram chart It represents the frequency of the variable at different points of time. It is used for continuous data and the bars created show no gap in between X-axis represents the bin ranges while Y-axis gives information about frequency. Ahistogram displays the numerical data grouped into bars also known as “bins" of equal size. The height of the bar represents the data point. Histogram helps you find the number of bars, the range of numbers that go into each bar, and the labels for the bar edges. Before you go for designing a Histogram you need to finalise the width of each bin. If we go from 10 to 250 using bins with a width of 50 then the data can easily adjust in 5 bins. It is always a good practice of using a decent number of bins in the designing of a histogram. import matplotlib.pyplot as plt # Number of schools in each city schools = [10,25,29] # Creating the histogram with bins plt-his (schools, bins=[10, 15,20, 25,301) # Adding labels and title plt.xlabel (‘Number of Schools") plt.ylabel ("Frequency') plt.title (‘Distribution of Schools in Cities") # Customizing x-axis tick labels plt-xticks(=(15, 20, 25, 30)) | # Displaying the histogram plt.show() Introduction to Data and Programming with Python | 207 LIT ne ciate i i. Distribution of Schools in Cities a5 20 25 Number of Schools, Let's draw a histogram to represent marks out of 100 of 40 students in class. Matplotlib uses a built-in function - hist () to create a histogram. Example: from matplotlib import pyplot as plt import numpy as np fig, ax = plt.subplots(1,1) marks = np.array([19,16,28,45,37, 34, 13,49, 42,441) ax-hist (marks, bins = [10,20,30,40,50]) ax.set_title("histogram of result") ax.set_xlabel ('marks') ax.set_ylabel('no. of students") plt.show() Output: histogram of result ‘number of students, 208 | Touchpad Robotics & Artificial Intelligence-x. \ Brainy Fact You may create a figure with man axis or same y axis. Following ist fig, ¥ Plots known as subplots side by side sharing either the same x the code to create 3 subplots with shared y axis ~ Plt.subplots(1, 3, sharey=true) Plotting a Pie chart It's a circular representation of data where each slice shows the relative size of the data.The dat circle equal to 360°with each segment and sector Matplotlib uses a built-in function - a is a complete S forming a certain portion of the total(percentage) ie( to create pie charts, Pie chart represents a circle divided into plot is used to represent numerical data import matplotlib.pyplot as different sectors where each sector represents a part of the whole. A pie proportionally, pit # Data for the pie chart Temp = [20, 30, 15, 10, 25) Cities = ['Pune", ‘Banglore’, 'gammu', ‘Srinagar’, 'Mumbai') cre: ng the pie chart Plts Pie (tsi rebel Sol DAC emeMCOEEE) Te iicty*) # Adding title plt.title("Pie chart") # Display ng the pie chart plt.show() Pie Chart Bengaluru Pune Jammu Mumbai Srinagar Let us do the following question: Suppose you conducted a survey to determine the favourite genres of music among a group of students in your school. The results of the survey are as follows: 30% prefer Pop, 25% prefer Rock, 15% prefer Hip Hop, 20% prefer Country, and 10% prefer Jazz. Design a pie chart to visually represent these survey results.” import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame({’Music':[30, 25, 15, 20, 101,) index{"Pop', 'Rock', ‘Hip Hop', ‘Country’, 'Jazz"}) Introduction to Data and Programming with Python | 209 &. Wa y if.plot (kinds 'pie', y="Music') plot. show () ME Pop Poe HMMM Fock Rock HR Hip Hop IE Country mm az 3 liz 2 Hip Hop Country Another example is: Example: from matplotlib import pyplot as plt import nur fig = plest ax = fig.add_axes([0,0,1,11) ax.axis ("equal") nd Lang", "Computers”] subjects = ["Eng", "Maths", "Science", "Sst", marks = (23, 45, 34, 41,13, 49] ax-pie(marks, labels = subjects, autopct="$1.2£8%') plt.show() Output Maths Science, Eng Sst Computers 2nd Lang Plotting a Scatter Chart Scatter plots use dots to display values from two variables in a graph It is used to plot data which has no continuity(non continuous data). This allows us to see if there is any relationship or correlation between the two variables. Matplotlib uses a built-in function - scatter() to create scatterplots, Example: import matplotlib.pyplot as plt 2. 210 | Touchpad Robotics & Artificial Intelligence-x [USANA ON marks1=(31,34,36, 42, 40,23, 39} marks2 (34, 45,23, 44,12,16,35) plt.scatter(marks1, marks2, c='red") plt,title('Scatter plot") plt.xlabel (‘marks 1") plt,ylabel (‘makes 2") plt,show() Output: Scatter plot 4s ; 7 40. 35 >> import math JBq x12 | Touchpad Robotics & Artificial Intelligence-x —~\ ww >>> print (math. sqrt (16) ) 4.0 >>> print (math. pow (25,2) ) 625.0 >>> print (math. fabs (-10)) 10.0 >>> print (math.cos (0) ) 1.0 >>> print (math. sin (90)) 0.8939966636005579 Example 2 Few examples of using Python library - random for random number generation: >>> import random >>> rollno=[1, 2, 3, 4, 5} >>> random. shuffle (rol1no) >>>print (rol1no) (2, 3, 2 4, 5) >>> random. shuffle (rolino) >>> print (rolino) (Serdy Mr 22 >>> random_number = random.randint(1, 10) # Generate a random integer between 1 and 10 (inclusive) >>> print (random_number) 6 >>> random float = random.random() # Generate a random floating-point number between 0 and 1 >>> print (round (random float, 2)) 0.81 2% Reboot 1. What are python libraries? 2. Who created Matplotlib? 3. What are the points on the graph that represent a data value on a line or scatter chart called? Introduction to Data and Programming with Python | 213 - (AL 5) Lists in Python ; of any data type |il List is a collection of heterogeneous data arranged in a sequence. The values a ata ine (in poeta integer, float, objects or even a list. Each value in a list is called an element os i ig aan eS ie ca YY an index number. The number of ‘elements in a list will make the length of a list. Al | the *Parated by comma and enclosed in square brackets [ ]. q List is a mutable data type in Python as the content of the list can be added, ee, naa hee ae User anytime throughout the code. A number of operations can be performed on the list by using uilt-n lise functions which we will study in detail in this chapter. Important Features of Lists Based on the above definition, the list has the following important features: * Itis mutable data type + Its an ordered sequence of values. * Each element is separated by comma and enclosed in squaté brackets []. * Each value/element is accessed by an index number. * The values can be added, modified or deleted by the user throughout the program. + Itstores the values of different data types, Creation of List A listis created by enclosing the values within square brackets, Each value/element is separated by a comma and stored under a common name, These values can be of different data types. The name follows the rules of naming Conventions for identifiers as shown below: Examples ‘Commands Creating an empty list list1 = (] Creating a list with single value list2 = [56] Creating a list of friends friends = ["Saisha", "Advika", "Arshia"} Creating a list of marks marks=[92, 81, 89, 95, 93] Creating a list of students with roll no students = (21, *Gunjan", 94.5, 34, "Rohit", 91.3] and percentage (list of mixed values) Creating a list within another list section = ["A", 25, *Englisn*, [*B¥,34}) [»c¥,37), 5617) Creating a list with repeated values 1 = (10) + 5 $ 11 will have (10, 10, 10, 10, 10) Creating 2 list from another sequence alpha = list (*hello") #etring converted to a list or string using list() function Foutpuel vila! (hie al aiiealioay Values input ftom the userina list 1 = List (input (“enter numbers 2) Access Elements of a List 2. 214 | Touchpad Robotics & Artificial Intelligence-x \_ IS, String in-built Functions/Methods f lend) It retums the total number 0! dior ara characters in the string > 22 PROGRAMMING IS AMAZING” upper() It displays the string in uppercase >>> TX’ >>> TXT upper () ‘PROGRAMMING IS AMAZING’ >>> ‘hello! .upper () ‘HELLO! RAMMING IS AMAZING” lower) It displays the string in lowercase. >>>‘ TXT="PROG! >>> TXT. lower () ‘programming is amazing! >>> TXT "PROGRAMMING IS AMAZING" title Itdisplays the firstletter of every word >>> TXT="PROGRAMMING IS AMAZING" in uppercase and remaining in small >>> TxT.title() ‘Programming Is Amazing' capitalize() It displays the first letter of first word >>> TX’ in uppercase and remaining in small PROGRAMMING IS AMAZING" >>> TXT.capitalize() "Programming is amazing’ startswith) It returns True if a string starts with >>> "Hello, how the specified substring are you?", startswith('Hello') True >>> "Hello, how startswith(*hello') False are you?" >>? "Hello, how are you?". start swith ('He') True endewith) It retuns true if a string ends with >>> "e110, how are you?" endswith (‘you') False >>>"Hello, how are you?" endswith (*you?") True >>> "Hello, how are you True endswith (‘u?") 2 230 | Touchpad Robotics & Artificial Intelligence-x \__ SAA, find(str,start, It returns the index of the first >>> s Hello, how are you?" figs Occurrence of a substring inside a >>> §. find("e1") string if itis found. If not found, it, returns - >>> 8.find (EA | Syntax is: aa | String.find (Substring, Start, 555 ¢ ; | eee 8. find (how!) 7 , Where Start and End ate optional. fs i csyuoys | not given then the searching starts °°? S-find('How') from index 0 to index last, tt | >>> S.find('0',5,10) | 8 ae It returns True if the string contains >>> Si="Class10B" at least one lowercase letter and NO >>> S1.islower() | uppercase at all. ee | >>> thello! -islower () | True aeo It returns True if the string contains >>> 2="#WoRLD" at least one uppercase letter and no 355 52. icupper() lowercase at all. nga >>> sis"classi0s" >>> 'S1-isupper () False isalpha) It returns True if the string contains >>> si="Clase102" only alphabets >>> $1 .dsalpha() False >>> $2="WORLD" >>> $2.isalpha() rue isalnumd) It returns True if the string contains >>> S1s"Class10B" only alphanumericlalphabets or >>> 51.isalnum() digits) True b5> S2e"Classi0-B* >>> §2.isalnum() False 5 ="class108" isdigit) It returns True if the string contains >>> Sl="Class only digits >>> Sl.isdigit () False >>> S3,isdigit () True Introduction to Data and Programming with Python | 231 fe. LTT 'sspace), It returns True if the string contains >>> § only space >>> 84.isspace () False >>> s5=" " >>> §5.isspace () True replace() it replaces an old string with a new) 222 TxToMhello Nora sing o>> TXT. replace('o'y'_') Syntax is: ‘hell_ world! String. replace (old, new) ee HeMnC NON EARN dea ace ace 8t/ 147) ‘H#llo, how ar# you?! count(str, It searches the substring in a given >>> T="Hello, how aze you?" start, end) string and returns how many times >>> T.count ('0') the substring is present in it. 3 Syntax is String. count (Substring, Start, End+1) Where Start and End are optional. If Not given then the searching starts from index 0 to index last. joind It returns a string in which the >>> city="DELHI' characters in the string have been joined by a separator @ At a Glance A module is a python file containing a collection of Python statements, functions and global variables. + A Package is a collection of relevant modules saved under the same directory and a name. + NumPy is a powerful open-source scientific package that stands for ‘Numerical Python’. = Panda is an open-source Python library used for data manipulation and data analysis. + A DataFrame ig a two-dimensional labelled heterogeneous data structure that contains rows and columns. » SciPy is a free, open source Python library used for scientific and technical Compute ello class" >>> S >>> S.join(city) "DeE@LGHGL' n. <_ ‘= Python libraries are pre-written set of code which gives additional functionality and tools to enhance the capabilities of Python. + List is @ collection of heterogeneous data arranged in a sequence. The values can be of any data type like sting. integer, float, objects or even a lst. ‘= Matplotlb is 2 free and open source, data visualisation library used for plotting graphs and visualisation in Python built on NumPy arrays. '* sort() function sorts the list in ascending or descending order, ‘+ Markers are the points on the graph that represent a data value on a line or scatter chart. 232 | Touchpad Robotics & Artificial Intelligence-x

You might also like