KEMBAR78
Class X Practical Notes | PDF | String (Computer Science) | Computing
0% found this document useful (0 votes)
6 views17 pages

Class X Practical Notes

Uploaded by

aadianshu1000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views17 pages

Class X Practical Notes

Uploaded by

aadianshu1000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Class X Practical Notes

Modules and Packages


 Python Modules: A file containing python code (function, variables
and classes) that you can reuse in other programs.
 Module is a .py file.
 Helps to organize the code.
 Reusability of code
 Avoids repetitions (DRY Principle – Don’t Repeat Yourself)
 Easier to manage and maintain
 It is like a toolkit that contains tools for reuse
 eg – math, random, datetime – builtin python modules
 Whenever we need to use a module, we import it from its library
 For use we just need to use import like
 # importing math library
import math from math import sqrt
print(math.sqrt(16)) or print(sqrt(16))
 Python Package: It is a collection of various python modules
 Folder containing multiple .py files
 Helps managing larger projects by grouping them in similar
modules
 It also has a special file __init__.py that you create in order to
create your own packages ( i.e User-Defined Packages)
 Package -> contains-> Modules -> contains-> Functions, Classes
and Variables.
 Python Library: It is a collection of various modules and packages that
cater to specific types of needs and applications.
eg. – Numpy Library -> caters to scientific computing needs
 Library – Collection of precompiled codes, that can be later used in our
program.
 Types of Common Python Libraries used :-
 Matplotlib:
 Responsible for plotting numerical data.
 Used in data analysis
 Open-source library
 Plots pie charts, histograms, scatterplots, etc
 Pandas:
 Open-source machine learning library
 Eases data-analysis, data manipulation, and data cleaning
 Supports 2 data structures -> Series and DataFrame
 Numpy:
 (Numerical Python) Machine learning library -> supports large
matrices and multidimensional data
 Inbuilt mathematical functions
 Allows sorting and indexing of array
 Scipy:
 (Scientific Python) -> open-source library for high-level scientific
computations.
 Built over an extension of Numpy
 Numerical data code sorted in SciPy
 Readily available Packages of Python
 Numpy (Numerical Python): Used for mathematical operations
and working with arrays
 Very powerful for scientific computing
 Eg-> import numpy as np
arr=np.array([1,2,3,4,5])
print(arr) ->O/P is [1,2,3,4,5]
print(arr +5) ->O/P is [6,7,8,9,10]
 OpenCV (Open Source Computer Vision): used for image and
video processing
 Helps in tasks like face detection, filters and object tracking
 Matplotlib: used for data visualization
 Good for making line graphs, bar charts, etc.
 NLTK (Natural Language Toolkit): used in NLP (Natural Language
Processing)
 Helps in working with text data like tokenizing, analyzing
sentences.
 Pandas: Used for data analysis and manipulation
 Works with tables (DataFrame) and spreadsheets
 Eg->
import pandas as pd
data = {‘Name”:[“Alice”,”Bob”],”Age”:[25,30]}
df = pd.DataFrame(data)
print(df)
 O/P:->

 Works on packages like Numpy and Matplotlib and gives us a


single, convenient place to do most of our data analysis and
visualization work.
 Advantages:
 Data Manipulation
 Data Analysis
 Integration
 Flexibility
 Visualization
 Line Graph:
 Express a relationship between 2 variables
 Used to show trends or changes over time
 Created using plot()
 Bar Graph:
 To show relationship between two axes
 Represent categories on 1 axes and discrete values on another
 Used to compare values
 Created using bar()
 Pie Chart:
 Circular plot, divided into slices to show numerical proportions
 Widely used in business world
 Shows slice of time
 Specialized graph in statistics
 Each arc length represents the proportion of each category, while
full circle represents total sum of all data, equal to 100% ( basically
to show parts of whole (percentage))
 Created using pie(time,
labels=””,startangle=90,autopct=’%1.1f%%’)
 %->displays literal percent sign
 1.1f-> means 1 digit before and 1 digit after decimal point
 .0f-> means no decimals
 .2f-> means 2 decimal places
 Scatter Plot:
 Use dots to show relationships between variables
 It shows how change in one affects others.
 Created using scatter()
 Series: 1-dimensional array containing a sequence of values of any data
type(int, float, string, list, etc) which by default have numeric indexes
starting from 0.
 It is like a column in spreadsheet
 Creating a Series->
import pandas as pd
import numpy as np
s1=pd.Series([10,20,30])
print(s1)
o/p->

s2=pd.Series([10,20,30],index=[‘a’,’b’,’c’])
print(s2)
o/p->

a=np.array([1,2,3,4,5])
s3=pd.Series(a)
print(s3)
o/p->

 Accessing elements of a series -> 2 ways -> Indexing and Slicing


 Indexing-> 2 types-> a) Positional index (starting from 0)
b) Labelled index (user defined labels)
import pandas as pd
s4=pd.Series([10,20,30,40,50],index=[‘a’,’b’,’c’,’d’,’e’])
print(s4[2]) ->o/p->30 #positional index
print(s4[‘c’])->o/p->30 #labelled index
 Slicing-> used to extract a part of series
[start:end:step]
start->starting index (included) (by default 0)
end->ending index (excluded)
step->how many steps to skip
s5=pd.Series([1,2,3,4,5,6,7,8,9,10])
print(s5[0:3])->o/p->

Print(s5[-1:-3:-1])->o/p->

 DataFrames: 2-dimensional tabular spreadsheet with rows and


columns.
 Rows :- individual records (like robot reading)
 Columns :- different categories (like battery, names,…)
 Can hold different types of data
 You can add ,remove, modify, sort and filter data
 Eg->
import pandas as pd
data={ “Robot Name”:[“alpha”,”beta”,”gamma”],
“battery(%)”:[85,60,95],
“Status”:[“Active”,”Idle”,”Active”]}
df=pd.DataFrame(data)
print(df)
o/p->

 Lists:
 It is a standard datatype that stores a list of values(elements) of
any datatype
 Collection of items
 Ordered->elements are accessed using the index number
 Mutable->it can be changed once created
 It allows duplicate values
 Accessing is slower -> as it allows changing data
 List structure:-[1,2,3,4,5]
 Similar to strings but are mutable

 Empty Lists-> a=[]-> truth value is False
a=list() both means empty
0 in a lists
o/p-> False
 Nested lists: A list inside list as an element

#as an element of list


 Different ways of initializing a list:-
1) list()

2) list by user input:-

 Accessing elements of a list:-elements are accessed with the help


of index numbers

 Traversing a list:- same as strings


 Comparing two lists - <, >, ==, != (Boolean results)
True-> if all corresponding elements are equal and the length is
same.
False-> if length differ or any element differ

 List Operations:
 Concatenation:- (+) for this both elements must be of list
type ; you cannot add any other value to a list.


 Replicating: (*)

 Lists are mutable

 Reversing a list

 Functions of a list:
 append(): adds an element at the end of the list
 extend(): adds more than 1 element. It also is used to add
elements of another list to the existing one.
 count(): returns the count of number of times a value exists
in a list
 Deleting elements: - 3 ways
 pop(): index is passed as argument ; used if index is known ;
if nothing is passed it removes the last element from the
list.

 remove(): if element is known and not index

 del(): it removes a sublist of elements or the complete list


->[start:end:step]

 insert(): When we want to insert an element at a specified index


Function takes two arguments-> (index value , element)
 reverse(): reverse the order of elements

 sort(): arrange the elements in a list in ascending order

#in sort reverse is by default False


Descending order:

 clear(): clears all elements from the list->empty list


does not take any parameters
does not return any value

 index(): to find the index at which an element is at the list

 max(): returns the maximum value from a list


this is used when list has same type of values(datatypes)

 min(): returns minimum value

 Search: means finding an element in list


1) In operator: to check if an element is present or not
2) Index()
3) Count()
4) Loop: To find all positions where the element is present

 Tuples: Collection of items just like lists, but:


 It is immutable
 Used to multiple values (different datatypes as well)
 Used to keep data safe from accidental changes
 Faster than lists
 A = (1,2,3,4)
 Cannot be partially deleted but can be completely deleted

 Accessing elements
 Tuple Methods:
 Count():

 Index():

 Len():

 Del():

 Iterating through a tuple

 Conversion of tuple to list and vice-versa


 Converting list to tuples: tuple()

 Converting tuples to list: list()


 Strings: Sequence of characters enclosed in single or double quotes
S=”hello”

 Creating a string

 Escape Sequences: used to include special characters inside a


string using \.
Escape Sequences Meaning
\n New line
\t Tab(4-8 spaces)
\\ Backlash
\’ Single quote
\” Double quote

 Traversing a String (using indexing)


 String operators
 Concatenating Strings

 Replicating Strings

 Membership operators

 Comparison Operators

 String Built in functions


 Len(): returns the length of the string
 Lower(): converts to lowercase

 Upper(): converts to uppercase

 Find(str,start,end): finds occurrences of a substring

 Startswith(substring):- check if string starts with given


substring

 Endswith(substring): checks if string ends with given


substring

 Isalnum(): returns true if all characters are letters or


numbers

 Islower()/isupper(): checks if all letters are lowercase or


uppercase
 Replace(old str,new str): replaces parts of the string

 Join(): returns a string in which characters are joined with


the help of a separator

 Count(): returns the count of an element appearing in a


string

 Isalpha(): checks if all characters are alphabets

 Isdigit(): checks if all elements are digits

 Capitalize(): Capitalizes first letter of the string


 Splits(): it splits the string into a list

 Differences between strings and lists


Lists Strings
1) Lists are mutable Strings are immutable
2) Lists can have any datatypes Strings can have only characters
3) Lists are enclosed in [] Strings are enclosed in quotes

 Similarities between lists and strings


 Both are sequences
 Both support->indexing, slicing, looping, len()
 Both can use operators like +,*.

*********************************

You might also like