Professional Documents
Culture Documents
Pandas Records
Pandas Records
⦁Write a Pandas program to create and display a one-dimensional array-like object containing an
array of data
Code:
import pandas as pd
ds = pd.Series([2, 4, 6, 8, 10])
print(ds)
Sample Output:
0 2
1 4
2 6
3 8
4 10
dtype: int64
Date: / /2022
⦁Write a Pandas program to convert a Panda module Series to Python list and it’s type
Code:
import pandas as pd
ds = pd.Series([2, 4, 6, 8, 10])
print(ds)
print(type(ds))
print(ds.tolist())
print(type(ds.tolist()))
Sample Output:
0 2
1 4
2 6
3 8
4 10
dtype: int64
<class 'pandas.core.series.Series'>
[2, 4, 6, 8, 10]
<class 'list'>
Date: / /2022
⦁Write a Pandas program to add, subtract, multiple and divide two Pandas Series
Code:
import pandas as pd
ds = ds1 + ds2
print(ds)
ds = ds1 - ds2
print(ds)
ds = ds1 * ds2
print(ds)
ds = ds1 / ds2
print(ds)
Sample Output:
0 3
1 7
2 11
3 15
4 19
Date: / /2022
dtype: int64
0 1
1 1
2 1
3 1
4 1
dtype: int64
0 2
1 12
2 30
3 56
4 90
dtype: int64
0 2.000000
1 1.333333
2 1.200000
3 1.142857
4 1.111111
dtype: float64
Date: / /2022
Code:
import numpy as np
import pandas as pd
print("NumPy array:")
print(np_array)
new_series = pd.Series(np_array)
print(new_series)
Sample Output:
NumPy array:
[10 20 30 40 50]
0 10
1 20
2 30
3 40
4 50
dtype: int64
Date: / /2022
Pandas Data Frames:Consider Sample python dictionary Data and its labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura',
'Kevin', 'Jonas'],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
1. Write a Pandas program to create and display a DataFrame from a specified dictionary data which
has the index labels.
Code:
import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura',
'Kevin', 'Jonas'],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print(df)
Sample Output:
b 3 Dima no 9.0
d 3 James no NaN
e 2 Emily no 9.0
h 1 Laura no NaN
i 2 Kevin no 8.0
2. Write a Pandas program to change the name 'James' to 'Suresh' in name column of the data frame.
Code:
import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura',
'Kevin', 'Jonas'],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print("Original rows:")
print(df)
print(df)
Date: / /2022
Sample Output:
Original rows:
b 3 Dima no 9.0
d 3 James no NaN
e 2 Emily no 9.0
h 1 Laura no NaN
i 2 Kevin no 8.0
b 3 Dima no 9.0
d 3 Suresh no NaN
e 2 Emily no 9.0
h 1 Laura no NaN
Date: / /2022
i 2 Kevin no 8.0
Code:
import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura',
'Kevin', 'Jonas'],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print("Original rows:")
print(df)
color = ['Red','Blue','Orange','Red','White','White','Blue','Green','Green','Red']
df['color'] = color
print(df)
Sample Output:
Original rows:
b 3 Dima no 9.0
d 3 James no NaN
e 2 Emily no 9.0
h 1 Laura no NaN
i 2 Kevin no 8.0
Code:
import pandas as pd
import numpy as np
df = pd.DataFrame(exam_data , index=labels)
print(list(df.columns.values))
Sample Output:
Original rows
B Dima 9 3 no
D James nan 3 no
Pandas index:
1. Write a Pandas program to display the default index and set a column as an Index in a given
dataframe.
Test Data:
Code:
import pandas as pd
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
print("Default Index:")
print(df.head(10))
df1 = df.set_index('school_code')
Date: / /2022
print(df1)
df2 = df.set_index('t_id')
print(df2)
Sample Output:
Default Index:
t_id
2. Write a Pandas program to create an index labels by using 64-bit integers, using floating-point
numbers in a given dataframe.
Test Data:
Code:
import pandas as pd
print("Create an Int64Index:")
df_i64 = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
'date_Of_Birth': ['15/05/2002','17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
index=[1, 2, 3, 4, 5, 6])
print(df_i64)
print(df_i64.index)
df_f64 = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
Date: / /2022
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
print(df_f64)
print(df_f64.index)
Sample Output:
Create an Int64Index:
1. Write a Pandas program to convert all the string values to upper, lower cases in a given pandas
series. Also find the length of the string values.
Code:
import pandas as pd
import numpy as np
s = pd.Series(['X', 'Y', 'Z', 'Aaba', 'Baca', np.nan, 'CABA', None, 'bird', 'horse', 'dog'])
print("Original series:")
print(s)
print(s.str.upper())
print(s.str.lower())
print(s.str.len())
Sample Output:
Original series:
0 X
1 Y
2 Z
3 Aaba
4 Baca
5 NaN
6 CABA
Date: / /2022
7 None
8 bird
9 horse
10 dog
dtype: object
0 X
1 Y
2 Z
3 AABA
4 BACA
5 NaN
6 CABA
7 None
8 BIRD
9 HORSE
10 DOG
dtype: object
0 x
1 y
2 z
3 aaba
Date: / /2022
4 baca
5 NaN
6 caba
7 None
8 bird
9 horse
10 dog
dtype: object
0 1.0
1 1.0
2 1.0
3 4.0
4 4.0
5 NaN
6 4.0
7 NaN
8 4.0
9 5.0
10 3.0
dtype: float64
Date: / /2022
2. Write a Pandas program to remove whitespaces, left sided whitespaces and right sided white
spaces of the string values of a given panda series.
Code:
import pandas as pd
color1 = pd.Index([' Green', 'Black ', ' Red ', 'White', ' Pink '])
print("Original series:")
print(color1)
print("\nRemove whitespace")
print(color1.str.strip())
print(color1.str.lstrip())
print(color1.str.rstrip())
Sample Output:
Original series:
Index([' Green', 'Black ', ' Red ', 'White', ' Pink '], dtype='object')
Remove whitespace
Code:
import pandas as pd
df = pd.DataFrame({
})
print("Original DataFrame:")
print(df)
print(df)
Sample Output:
Original DataFrame:
4. Write a Pandas program to swap the cases of a specified character column in a given DataFrame.
Code:
import pandas as pd
df = pd.DataFrame({
'date_of_sale': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],
})
print("Original DataFrame:")
print(df)
print(df)
Sample Output:
Date: / /2022
Original DataFrame:
2 zefsalf .. ZEFSALF
[5 rows x 4 columns]
Date: / /2022
1. Write a Pandas program to join the two given dataframes along rows and assign all data.
Test Data:
student_data1:
3 S4 Ed Bernal 222
student_data2:
Code:
import pandas as pd
student_data1 = pd.DataFrame({
'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],
'name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse', 'Kaiser William', 'Madeeha Preston'],
print("Original DataFrames:")
print(student_data1)
print("-------------------------------------")
print(student_data2)
print(result_data)
Sample Output:
Original DataFrames:
3 S4 Ed Bernal 222
-------------------------------------
3 S4 Ed Bernal 222
2. Write a Pandas program to append a list of dictioneries or series to a existing DataFrame and display
the combined data
Test Data:
3 S4 Ed Bernal 222
Dictionary:
student_id S6
marks 205
dtype: object
Code:
import pandas as pd
student_data1 = pd.DataFrame({
'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],
print("Original DataFrames:")
print(student_data1)
print("\nDictionary:")
print(s6)
print("\nCombined Data:")
print(combined_data)
Sample Output:
Original DataFrames:
3 S4 Ed Bernal 222
Dictionary:
student_id S6
marks 205
Date: / /2022
dtype: object
Combined Data:
3 S4 Ed Bernal 222
3. Write a Pandas program to join the two dataframes with matching records from both sides where
available.
Test Data:
student_data1:
3 S4 Ed Bernal 222
student_data2:
Code:
import pandas as pd
student_data1 = pd.DataFrame({
'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],
student_data2 = pd.DataFrame({
'name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse', 'Kaiser William', 'Madeeha Preston'],
print("Original DataFrames:")
print(student_data1)
print(student_data2)
print(merged_data)
Sample Output:
Original DataFrames:
3 S4 Ed Bernal 222
e) Current date.
Code:
import datetime
print(datetime(2012, 1, 15))
print(datetime.now())
print(datetime.date(datetime(2012, 5, 22)))
print("\nCurrent date:")
print(datetime.now().date())
print(datetime.now().time())
Sample Output:
2012-01-15 00:00:00
2011-01-15 21:20:00
2020-08-17 09:56:17.459790
2012-05-22
Current date:
2020-08-17
18:12:00
09:56:17.461250
Date: / /2022
2. Write a Pandas program to create a date from a given year, month, day and another date from a
given string formats.
Code:
print(date1)
print(date2)
Sample Output:
2020-12-25 00:00:00
2021-01-01 00:00:00
Date: / /2022
3. Write a Pandas program to create a time-series with two index labels and random values. Also print
the type of the index.
Code:
import pandas as pd
import numpy as np
import datetime
print(time_series)
print(type(time_series.index))
Sample Output:
2011-09-01 -0.257567
2011-09-02 0.947341
dtype: float64
<class 'pandas.core.indexes.datetimes.DatetimeIndex'>
Date: / /2022
Consider dataset:
1. Write a Pandas program to split the following dataframe into groups based on school code. Also
check the type of GroupBy object
Code:
import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
student_data = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
print("Original DataFrame:")
print(student_data)
result = student_data.groupby(['school_code'])
print("\nGroup:")
print(name)
print(group)
print(type(result))
Sample Output:
Original DataFrame:
[6 rows x 8 columns]
Group:
s001
[2 rows x 8 columns]
Group:
s002
[2 rows x 8 columns]
Group:
s003
[1 rows x 8 columns]
Date: / /2022
Group:
s004
[1 rows x 8 columns]
<class 'pandas.core.groupby.groupby.DataFrameGroupBy'>
2. Write a Pandas program to split the following dataframe by school code and get mean, min, and
max value of age for each school.
Code:
import pandas as pd
pd.set_option('display.max_rows', None)
#pd.set_option('display.max_columns', None)
student_data = pd.DataFrame({
'school_code': ['s001','s002','s003','s001','s002','s004'],
'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Gino Mcneill', 'David Parkes'],
print("Original DataFrame:")
print(student_data)
print('\nMean, min, and max value of age for each value of the school:')
print(grouped_single)
Sample Output:
Original DataFrame:
[6 rows x 8 columns]
Mean, min, and max value of age for each value of the school:
age
school_code
s001 12.5 12 13
s002 13.0 12 14
s003 13.0 13 13
s004 12.0 12 12
Date: / /2022
Pandas styling
⦁ Create a dataframe of ten rows, four columns with random values. Write a Pandas program to
highlight the negative numbers red and positive numbers black
Code:
import pandas as pd
import numpy as np
np.random.seed(24)
axis=1)
print("Original array:")
print(df)
def color_negative_red(val):
df.style.applymap(color_negative_red)
Original array:
A B C D E
Sample Output:
⦁ Create a dataframe of ten rows, four columns with random values. Write a Pandas program to
highlight the maximum value in each column.
Code:
import pandas as pd
import numpy as np
np.random.seed(24)
axis=1)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
Date: / /2022
print("Original array:")
print(df)
def highlight_max(s):
'''
'''
is_max = s == s.max()
Original array:
A B C D E
Sample Output:
⦁ Create a dataframe of ten rows, four columns with random values. Write a Pandas program to
highlight dataframe's specific columns.
Code:
import pandas as pd
import numpy as np
np.random.seed(24)
axis=1)
df.iloc[0, 2] = np.nan
df.iloc[3, 3] = np.nan
df.iloc[4, 1] = np.nan
df.iloc[9, 4] = np.nan
print("Original array:")
print(df)
def highlight_cols(s):
color = 'grey'
Original array:
Original array:
Date: / /2022
A B C D E
Sample Output:
Date: / /2022
Pandas Excel
⦁Write a Pandas program to import given excel data (coalpublic2013.xlsx ) into a Pandas dataframe.
Excel Data:
coalpublic2013.xlsx:
Code:
import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
print(df.head)
Sample Output:
⦁Write a Pandas program to find the sum, mean, max, min value of 'Production (short tons)' column of
coalpublic2013.xlsx file
Excel Data:
coalpublic2013.xlsx:
Code:
import pandas as pd
import numpy as np
df = pd.read_excel('E:\coalpublic2013.xlsx')
print("Sum: ",df["Production"].sum())
print("Mean: ",df["Production"].mean())
print("Maximum: ",df["Production"].max())
print("Minimum: ",df["Production"].min())
Sample Output:
Sum: 1611713
Mean: 402928.25
Maximum: 14,40,115
Minimum: 28,807
Date: / /2022
Excel:
coalpublic2013.xlsx:
Sample output:
2)Write a Pandas program to find the sum, mean, max, min value of a column of file.
Output:
Sum:
Mean:
Maximum:
Minimum: 0
Date: / /2022
Plotting:
1)Write a Pandas program to create a horizontal stacked bar plot of opening, closing stock
prices of any stock dataset between two specific dates.
Date Open High Low Close Adj Volume
Close
4/1/2020 1122 1129.7 1097 1105.6 1105.6 2343100
4/2/2020 1098 1126.9 1096 1120.8 1120.8 1964900
4/3/2020 1119 1123.5 1080 1097.9 1097.9 2313400
4/6/2020 1138 1194.7 1131 1186.9 1186.9 2664700
output:
Date: / /2022
Ouput: 2)Write a Pandas program to create a histograms plot of opening, closing, high, low stock
prices of stock dataset between two specific dates.
Code:
Output:
Date: / /2022
Date: / /2022
3)Write a Pandas program to create a stacked histograms plot of opening, closing, high, low stock
prices of stock dataset between two specific dates with more bins.
Code:
Output:
import pandas as pd
employees=pd.read_csv(r"EMPLOYEES.csv")
departments=pd.read_csv(r"DEPARTMENTS.csv")
job_history=pd.read_csv(r"JOB_HISTORY.csv")
jobs=pd.read_csv(r"JOBS.csv")
countries=pd.read_csv(r"COUNTRIES.csv")
regions=pd.read_csv(r"REGIONS.csv")
locations=pd.read_csv(r"LOCATIONS.csv")
print("All the records from regions file:")
print(regions)
Output:
Date: / /2022
Output:
Date: / /2022
Features of JavaScript:
• JavaScript is a lightweight, interpreted programming language means that scripts execute
without preliminary compilation.
• It is an Object-based Scripting Language.
• Designed for creating network-centric applications.
• It is usually embedded directly into HTML Pages.
• Java script code as written between <script>-----</script> tags
• All Java script statements end with a semicolon
• Java script ignores white space
• Java script is case sensitive language
• Script program can be saved as either .js or .html
• Complementary to and integrated with Java.
• Open and cross-platform.
JAVA Vs JAVASCRIPT:
JAVA JAVASCRIPT
Object Oriented ProgrammingLanguage Object based Scripting Language
Platform Independent Browser Dependent
It is both compiled and interpreted. It is interpreted at runtime
It is used to create server side applications. It is used to make the web pages
more interactive
• Internal JavaScript: JavaScript can be added directly to the HTML file by writing the code inside the
<script> tag . We can place the <script> tag either inside <head> or the <body> tag according to
the need.
• External JavaScript: The other way is to write JavaScript code in another file having a .js extension
and then link the file inside the <head> or <body> tag of the HTML file in which we want to add this
code.
Example: This example describes the use of Internal Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Internal JS</title>
</head>
<body>
<h2>GeeksforGeeks</h2>
<script>
/*Internal Javascript*/
console.log("Hi CSE, Welcome to UR");
</script>
</body>
</html>
Output :
Hi CSE, Welcome to UR
Example: This example describes the use of External Javascript.
<title>External JavaScript</title>
<style>
h2 {
box-sizing: border-box;
width: 250px;
height: 150px;
background-color: green;
color: white;
Date: / /2022
margin: auto;
font-size: 15px;
font-family: sans-serif;
text-align: center;
padding: 20px;
</style>
</head>
<body>
<h2 class="external">CSE</h2>
<script src="GfG.js"></script>
</body>
</html>
Output
Type:
Refers to the MIME (Multipurpose Internet Mail Extensions) type of the script.
Language:
This attribute specifies what scripting language you are using. Typically, its value will be javascript.
Although recent versions of HTML have phased out the use of this attribute.
src:
Refers to the URL of another file which has script. It is used to specify external script files.
JavaScript provides 3 places to put the JavaScript code: within body tag, within head tag and external
JavaScript file.
<html>
<body>
alert("Hello Javatpoint");
</script>
</body>
</html>
Output:
Comments in JavaScript:
• Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
• Any text between the characters /* and */ is treated as a comment. This may span multiple
lines.
Date: / /2022
<!DOCTYPE html>
<html>
<head>
<title>document's Properties</title>
<style>
h1 {
color: green;
}
Date: / /2022
</style>
</head>
<body>
<h1> CSE</h1>
<button onclick="myFunction()">CLICK ME</button>
<p id="demo"></p>
<script>
function myFunction() {
var title = document.title;
var domain = document.domain;
var body = document.body;
document.getElementById("demo").innerHTML =
"the title of the document is : "
+ title
+ "<br>"
+ "domain : "
+ domain
+ "<br>"
+ "body : "
+ body;
}
</script>
</body>
</html>
Output:
Date: / /2022
Window Object: The window object is the topmost object of the DOM hierarchy. It represents a
browser window or frame that displays the contents of the webpage. Whenever a window appears on
the screen to display the contents of the document, the window object is created.
Syntax:
window.property_name;
Properties of the window:
• Closed: It holds a Boolean value that represents whether the window is closed or not.
• console: It returns a reference to the console object which provides access to the browser’s
debugging console.
• defaultStatus: It is used to define the default message that will be displayed in the status bar when
no activity is carried on by the browser.
• controllers: It returns the XUL controller objects for the current Chrome window.
• customElements: It returns a reference to the CustomElementRegistry object, which can be used
to register new custom elements and also get information about already registered custom
elements.
• crypto: It returns the browser crypto object.
• devicePixelRatio: It returns the ratio between physical pixels and device-independent pixels in the
current display.
• Document: It returns a reference to the document object of that window.
• DOMMatrix: It returns a reference to a DOMMatrix object, which represents 4×4 matrices, suitable
for 2D and 3D operations.
• frames[]: It represents an array that contains all the frames of a given window.
• DOMPoint: It returns a reference to a DOMPoint object, which represents a 2D or 3D point in a
coordinate system.
• History: It provides information on the URLs visited in the current window.
• Length: It represents the number of frames in the current window.
• DOMRect: It returns a reference to a DOMRect object, which represents a rectangle.
• fullScreen: This property indicates whether the window is displayed on full screen or not.
• Location: It contains the URL of the current window.
• innerHeight: It is used to get the height of the content area of the browser window.
• innerWidth: It is used to get the width of the content area of the browser window.
• Name: It contains the name of the referenced window.
Date: / /2022
<!DOCTYPE html>
<html>
<head>
<title> Window's Properties</title>
<style>
h1 {
color: green;
}
</style>
</head>
<body>
<h1>CSE</h1>
<button onclick="show()">Check</button>
<p id="prop"></p>
<script>
function show() {
var h = window.innerHeight;
var w = window.innerWidth;
var l = window.location;
var c = window.closed;
document.getElementById("prop").innerHTML =
"Frame's Height: "
+ h + "<br>"
+ "Frame's Width: "
+ w + "<br>"
+ "Window location:"
+l
+ "<br>"
+ "Window Closed: "
+ c;
}
</script>
Date: / /2022
</body>
</html>
Output:
➢ VARIABLES:
Creating Variables:
• Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows:
<script type="text/javascript">
Date: / /2022
var name;
var rollno;
</script>
• Storing a value in a variable is called variable initialization. You can do variable initialization at
the time of variable creation or at a later point in time when you need that variable.
<html>
<head>
<title>First Javascript Page</title>
</head>
<body>
<p style="color: red">In this example, i is defined as a variable.
Then, i is assigned the value of 500</p>
<script type=”text/javascript”>
//defining variable i
var i;
//assigning value 500 to i
i=500;
document.write(i);
</script>
</body>
</html>
Output:
➢ Operators:
An operator performs some operation on single or multiple operands (data value) and produces a
result. For example 1 + 2, where + sign is an operator and 1 is left operand and 2 is right operand.
Syntax:
1. Arithmetic Operators
Date: / /2022
2. Logical Operators
3. Assignment Operators
4. Comparison Operators
5. Bitwise Operators
1.Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations between numeric operands.
Operator Description
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var x = 5, y = 10;
x++;
document.write(x+"<br>"); //returns 6
x--;
document.write(x+"<br>"); //returns 5
</script>
</body>
</html>
Output:
2. Logical Operators:
Logical operators are used to combine two or more conditions. JavaScript includes following logical
operators.
3. Assignment operators:
JavaScript includes assignment operators to assign values to variables with less key strokes.
= Assign 10+10 = 20
+= Add and assign var a=10; a+=20; Now a = 30
-= Subtract and assign var a=20; a-=10; Now a = 10
*= Multiply and assign var a=10; a*=20; Now a = 200
/= Divide and assign var a=10; a/=2; Now a = 5
%= Modulus and assign var a=10; a%=2; Now a = 0
4. Comparison Operators:
JavaScript language includes operators that compare two operands and return Boolean value true or false.
Example: comparison.html
Operators Description
== Compares the equality of two operands without considering type.
=== Compares equality of two operands with type.
!= Compares inequality of two operands.
> Checks whether left side value is greater than right side value. If yes then returns true
otherwise false.
< Checks whether left operand is less than right operand. If yes then returns true otherwise false.
>= Checks whether left operand is greater than or equal to right operand. If yes then returns true
otherwise false.
<= Checks whether left operand is less than or equal to right operand. If yes then returns true
otherwise false.
<!DOCTYPE html>
<html>
<script>
var x = a;
document.write((a == c)+"<br>");
document.write((a == x)+"<br>");
Date: / /2022
document.write((a != b)+"<br>");
</script>
</body>
</html>
Output:
5. Bitwise operators:
Bitwise operators perform an operation on the bitwise (0,1) representation of the arguments, rather
than decimal, hexadecimal or octal numbers.
<< left shift Shifts left by pushing zeros in from the right and let the
leftmost bits fall off
>> right shift Shifts right by pushing copies of the leftmost bit in from the
left, and let the rightmost bits fall off
>>> Zero fill right shift Shifts right by pushing zeros in from the left, and let the
rightmost bits fall off
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var a = 6;
var b = 1;
// AND Operation
// OR operation
// NOT operation
// Left Shift
</script>
</body>
</html>
Output:
➢ Datatypes:
JavaScript is a dynamic scripting language, which can assign the data type to a variable dynamically. It
is done by JavaScript script engine. Data types that are known as primitive are numbers, strings,
boolean, null, undefined.
Objects and arrays are referred as non-primitive. The fundamental difference between primitives
and non-primitives is that primitives are immutable and non-primitives are mutable.
Numbers:Numbers can contain various values. To create a number, a variable with var keyword has
to be created and value has to be stored in it.
Decimal value: A number with a normal value can be as follows.
var b=25;
Octal number: JavaScript can convert the octal value to decimal value. A number with octal value (a
number with 8 digits from 0-7) can be as follows.
var b=012; //contains the decimal value 10
Hexadecimal number: Hexadecimal value can be created using 0x and can be as follows.
var myHex1=0xF; //contains decimal value 15
Floating point number: These are defined by placing the numbers after the decimal point.
var d=2.6;
Date: / /2022
var a=””;
var res=Boolean(a); //output is falsie since empty string converts to false
var a=0;
var res=Boolean(a); //output is false since 0 converts to false
var a=”script”;
var res=Boolean(a); //output is true since a has meaningful value
null: Null type has only one special value null. Logically, null value is an empty object pointer, which
returns “object” when passed.
var name=null; //name has no meaningful value assigned currently
alert(typeof null);// “object”
undefined: Undefined type has only one special value undefined. When a variable is declared using var but
not initialized, the value of undefined is as follows:
var a;
alert(a==undefined); //true
object: An object is a collection of properties. These properties are stored in key/value pairs. Properties
can reference any type of data, including objects and/or primitive values.
var obj = {
key1: 'value',
key2: 'value',
key3: true,
key4: 32,
key5: {}
};
Date: / /2022
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<script>
var person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
document.write(person.firstName + " is " + person.age + " years old.");
</script>
</body>
</html>
Output:
String(123) + "<br>" +
String(100 + 23);
</script>
</body>
</html>
OUTPUT:
123
123
123
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math Constants</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"<p><b>Math.E:</b> " + Math.E + "</p>" +
"<p><b>Math.PI:</b> " + Math.PI + "</p>" +
"<p><b>Math.SQRT2:</b> " + Math.SQRT2 + "</p>" +
"<p><b>Math.SQRT1_2:</b> " + Math.SQRT1_2 + "</p>" +
"<p><b>Math.LN2:</b> " + Math.LN2 + "</p>" +
"<p><b>Math.LN10:</b> " + Math.LN10 + "</p>" +
Date: / /2022
Math.E: 2.718281828459045
Math.PI: 3.141592653589793
Math.SQRT2: 1.4142135623730951
Math.SQRT1_2: 0.7071067811865476
Math.LN2: 0.6931471805599453
Math.LN10: 2.302585092994046
Math.LOG2E: 1.4426950408889634
Math.Log10E: 0.4342944819032518
Math Methods:
Number to Integer
▪ Example: Math.round()
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.round()</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.round(4.6);
</script>
</body>
</html>
OUTPUT:
JavaScript Math.round()
▪ Example: Math.ceil()
<!DOCTYPE html>
Date: / /2022
<html>
<body>
<h2>JavaScript Math.ceil()</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.ceil(4.7);
</script>
</body>
</html>
OUTPUT:
JavaScript Math.ceil()
▪ Example: Math.floor()
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.floor()</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.floor(4.7);
Date: / /2022
</script>
</body>
</html>
OUTPUT:
JavaScript Math.floor()
▪ Example: Math.trunc()
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.trunc()</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.trunc(4.7);
</script>
</body>
</html>
OUTPUT:
JavaScript Math.trunc()
▪ Math.pow()
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.pow()</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.pow(8,2);
</script>
</body>
</html>
OUTPUT:
JavaScript Math.pow()
▪ Math.sqrt()
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.sqrt()</h2>
<p id="demo"></p>
Date: / /2022
<script>
document.getElementById("demo").innerHTML = Math.sqrt(64);
</script>
</body>
</html>
String manipulation
The String object lets you work with a series of characters; it wraps Javascript's string primitive data type
with a number of helper methods.
As JavaScript automatically converts between string primitives and String objects, you can call any of the
helper methods of the String object on a string primitive.
Syntax
Use the following syntax to create a String object −
var val = new String(string);
The String parameter is a series of characters that has been properly encoded.
String Properties
1 constructor
2 length
3 prototype
The prototype property allows you to add properties and methods to an object.
In the following sections, we will have a few examples to demonstrate the usage of String properties.
String Methods
Date: / /2022
Here is a list of the methods available in String object along with their description.
1 charAt()
2 charCodeAt()
Returns a number indicating the Unicode value of the character at the given index.
3 concat()
4 indexOf()
Returns the index within the calling String object of the first occurrence of the specified value, or
-1 if not found.
5 lastIndexOf()
Returns the index within the calling String object of the last occurrence of the specified value, or
-1 if not found.
6 localeCompare()
Returns a number indicating whether a reference string comes before or after or is the same as
the given string in sort order.
7 match()
8 replace()
Used to find a match between a regular expression and a string, and to replace the matched
substring with a new substring.
9 search()
Executes the search for a match between a regular expression and a specified string.
Date: / /2022
10 slice()
11 split()
Splits a String object into an array of strings by separating the string into substrings.
12 substr()
Returns the characters in a string beginning at the specified location through the specified
number of characters.
13 substring()
Returns the characters in a string between two indexes into the string.
14 toLocaleLowerCase()
The characters within a string are converted to lower case while respecting the current locale.
15 toLocaleUpperCase()
The characters within a string are converted to upper case while respecting the current locale.
16 toLowerCase()
17 toString()
18 toUpperCase()
19 valueOf()
Here is a list of the methods that return a copy of the string wrapped inside an appropriate HTML tag.
1 anchor()
2 big()
3 blink()
4 bold()
5 fixed()
6 fontcolor()
Causes a string to be displayed in the specified color as if it were in a <font color="color"> tag.
7 fontsize()
Causes a string to be displayed in the specified font size as if it were in a <font size="size"> tag.
8 italics()
9 link()
10 small()
Date: / /2022
11 strike()
12 sub()
13 sup()
▪ charAt() is a method that returns the character from the specified index.
Characters in a string are indexed from left to right. The index of the first character is 0, and the index of
the last character in a string, called stringName, is stringName.length – 1.
Syntax
Example
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
<script type = "text/javascript">
var str = new String( "This is string" );
document.writeln("str.charAt(0) is:" + str.charAt(0));
document.writeln("<br />str.charAt(1) is:" + str.charAt(1));
document.writeln("<br />str.charAt(2) is:" + str.charAt(2));
document.writeln("<br />str.charAt(3) is:" + str.charAt(3));
document.writeln("<br />str.charAt(4) is:" + str.charAt(4));
document.writeln("<br />str.charAt(5) is:" + str.charAt(5));
</script>
</body>
</html>
Date: / /2022
Output
str.charAt(0) is:T
str.charAt(1) is:h
str.charAt(2) is:i
str.charAt(3) is:s
str.charAt(4) is:
str.charAt(5) is:i
Description
This method adds two or more strings and returns a new single string.
Syntax
Argument Details
Example
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
<script type = "text/javascript">
var str1 = new String( "This is string one" );
var str2 = new String( "This is string two" );
var str3 = str1.concat( str2 );
document.write("Concatenated String :" + str3);
</script>
</body>
</html>
Output
Date: / /2022
Description
This method splits a String object into an array of strings by separating the string into substrings.
Syntax
Argument Details
• separator − Specifies the character to use for separating the string. If separator is omitted, the
array returned contains one element consisting of the entire string.
• limit − Integer specifying a limit on the number of splits to be found.
Example
<html>
<head>
<title>JavaScript String split() Method</title>
</head>
<body>
<script type = "text/javascript">
var str = "Apples are round, and apples are juicy.";
var splitted = str.split(" ", 3);
document.write( splitted );
</script>
</body>
</html>
Output
Apples,are,round,
Date: / /2022
Description
This method is used to convert the characters within a string to lowercase while respecting the current
locale. For most languages, it returns the same output as toLowerCase.
Syntax
Example
<html>
<head>
<title>JavaScript String toLocaleLowerCase() Method</title>
</head>
<body>
<script type = "text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toLocaleLowerCase( ));
</script>
</body>
</html>
Output
JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called
object-oriented if it provides four basic capabilities to developers −
• Encapsulation − the capability to store related information, whether data or methods, together in
an object.
• Aggregation − the capability to store one object inside another object.
• Inheritance − the capability of a class to rely upon another class (or number of classes) for some
of its properties and methods.
• Polymorphism − the capability to write one function or method that works in a variety of different
ways.
Date: / /2022
Object Properties
Object properties can be any of the three primitive data types, or any of the abstract data types, such as
another object. Object properties are usually variables that are used internally in the object's methods,
but can also be globally visible variables that are used throughout the page.
The syntax for adding a property to an object is −
objectName.objectProperty = propertyValue;
For example − The following code gets the document title using the "title" property of
the document object.
var str = document.title;
Object Methods
Methods are the functions that let the object do something or let something be done to it. There is a small
difference between a function and a method – at a function is a standalone unit of statements and a
method is attached to an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to performing
complex mathematical operations on a group of local properties and parameters.
For example − Following is a simple example to show how to use the write() method of document object
to write any content on the document.
document.write("This is test");
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called Object.
The new Operator
The new operator is used to create an instance of an object. To create an object, the new operator is
followed by the constructor method.
In the following example, the constructor methods are Object(), Array(), and Date(). These constructors
are built-in JavaScript functions.
The variable contains a reference to the new object. The properties assigned to the object are not
variables and are not defined with the var keyword.
Example 1
Try the following example; it demonstrates how to create an Object.
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>
<body>
<script type = "text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
Output
Book name is : Perl
Book author is : Mohtashim
Example 2
This example demonstrates how to create an object with a User-Defined Function. Here this keyword is
used to refer to the object that has been passed to a function.
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
function book(title, author) {
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
Date: / /2022
</body>
</html>
Output
Book title is : Perl
Book author is : Mohtashim
The previous examples demonstrate how the constructor creates the object and assigns properties. But
we need to complete the definition of an object by assigning methods to it.
Example
Try the following example; it shows how to add a function along with an object.
<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
this.price = amount;
}
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
JavaScript has several built-in or native objects. These objects are accessible anywhere in your program
and will work the same way in any browser running in any operating system.
Here is the list of all important JavaScript Native Objects −
• JavaScript Number Object
• JavaScript Boolean Object
• JavaScript String Object
• JavaScript Array Object
• JavaScript Date Object
• JavaScript Math Object
• JavaScript RegExp Object
➢ Array: Array is a collection of similar items. They are written within square brackets and items are
separated by commas. Array indexes are zero-based, which means the first item is [0], second is [1],
and so on.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>Array indexes are zero-based, which means the first item is [0]. </p>
<script>
document.write(cars[1]);
</script>
</body>
</html>
Output:
Date: / /2022
Objects are not compared by value. This means that even if two objects have the same properties and
values, they are not strictly equal. Same goes for arrays. Even if they have the same elements that are in
the same order, they are not strictly equal.
➢ Date:
➢ The JavaScript date object can be used to get year, month and day. You can display a timer on the
webpage by the help of JavaScript date object.
➢ You can use different Date constructors to create date object. It provides methods to get and set
day, month, year, hour, minute and seconds.
Date()
Date(milliseconds)
Date(dateString)
Example1:Program which prints current date and time using date object.
<html>
<body>
<script>
document.write(today);
</script>
Date: / /2022
</body>
</html>
Output:
<html>
<body>
<script>
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
</script>
</body>
</html>
Output:
Date: / /2022
Methods:
Methods Description
getDate() It returns the integer value between 1 and 31 that represents the day for
the specified date on the basis of local time.
getDay() It returns the integer value between 0 and 6 that represents the day of the
week on the basis of local time.
getFullYears() It returns the integer value that represents the year on the basis of local
time.
getHours() It returns the integer value between 0 and 23 that represents the hours on
the basis of local time.
getMilliseconds() It returns the integer value between 0 and 999 that represents the
milliseconds on the basis of local time.
getMinutes() It returns the integer value between 0 and 59 that represents the minutes
on the basis of local time.
getMonth() It returns the integer value between 0 and 11 that represents the month
on the basis of local time.
getSeconds() It returns the integer value between 0 and 60 that represents the seconds
on the basis of local time.
setDate() It sets the day value for the specified date on the basis of local time.
Date: / /2022
setDay() It sets the particular day of the week on the basis of local time.
setFullYears() It sets the year value for the specified date on the basis of local time.
setHours() It sets the hour value for the specified date on the basis of local time.
setMilliseconds() It sets the millisecond value for the specified date on the basis of local
time.
setMinutes() It sets the minute value for the specified date on the basis of local time.
setMonth() It sets the month value for the specified date on the basis of local time.
setSeconds() It sets the second value for the specified date on the basis of local time.
if:
if statement is the most simple decision making statement. It is used to decide whether a certain
statement or block of statements will be executed or not i.e if a certain condition is true then a
block of statement is executed otherwise not.
Syntax:
if(condition)
{
// Statements to execute if
// condition is true
}
Date: / /2022
Example:if.html
<html>
<body>
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
</body>
</html>
Output:
if-else:
if-else: The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But what if we want to do somethingelse if the condition is
false. Here comes the else statement. We can use the else statement with if statement to execute a
block of code when the condition is false.
Syntax:
if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example:else.html
<html>
<body>
<script>
var a=20;
Date: / /2022
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
</body>
</html>
Output:
➢ switch:
The switch is a conditional statement like if statement. Switch is useful when you want to execute one
of the multiple code blocks based on the return value of a specified expression.
Syntax:
<script>
var a = 3;
switch (a) {
case 1:
alert('case 1 executed');
case 2:
alert("case 2 executed");
break;
case 3:
alert("case 3 executed");
break;
case 4:
alert("case 4 executed");
break;
default:
alert("default case executed");
}
</script>
</body>
</html>
Output:
12. Looping in JS
➢ Loops:
The JavaScript loops are used to iterate the piece of code using for, while, do while. It makes the code
compact. It is mostly used in array.There are three types of loopsin JavaScript.
▪ for loop
▪ while loop
▪ do-while loop
Date: / /2022
for:
The JavaScript for loop iterates the elements for the fixed number of times. It should be used if number
of iteration is known. The syntax of for loop is given below.
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
Output:
while:
The while loop iterates the elements for the infinite number of times. It should be used if number of
iteration is not known. The syntax of while loop is given below.
Syntax:
while (condition)
{
code to be executed
}
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
Date: / /2022
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
Output:
do-while:
The do while loop iterates the elements for the infinite number of times like while loop. But, code
is executed at leastonce whether condition is true or false. The syntax of do while loop is given below.
Syntax:
do{
code to be executed
}while (condition);
Example:do.html
<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>
Output:
Date: / /2022
Jump Statements:
break: The break statement "jumps out" of a loop. It breaks the loop and continues executing the code
after the loop
Example:
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output:
Date: / /2022
continue:
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.
Example:
<!DOCTYPE html>
<html>
<body>
<p>A loop which will skip the step where i = 3.</p>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output:
13. Functions
➢ Functions:
• A function is a group of reusable code which can be called anywhere in your program.
This eliminates the need of writing the same code again and again.
• It helps programmers in writing modular codes. Functions allow a programmer to divide a big
program into a number of small and manageable functions.
Date: / /2022
Function Definition:
• Before we use a function, we need to define it.
• The most common way to define a function in JavaScript is by using keyword function followed by a
unique function name, a list of parameters (that might be empty) and a statement block surrounded
by curly braces.
Syntax:
<script type="text/javascript">
//defining a function
function function-name()
{
Statements; // code to be executed
};
//calling a function
function-name();
</script>
Example:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
function sayHello()
{
document.write("Hello.. How are You");
}
sayHello();
</script>
</body>
</html>
Output:
Function Parameters:
A function can have one or more parameters, which will be supplied by the calling code and can be used
inside a function. JavaScript is a dynamic type scripting language, so a function parameter can have value
of any data type.
Date: / /2022
Example:
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript function parameters</h1>
<script>
function ShowMessage(firstName, lastName) {
document.write("Hello " + firstName + " " + lastName+"<br>");
}
ShowMessage("Steve", "Jobs");
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);
</script>
</body>
</html>
Output:
Return Statement: There are some situations when we want to return some values from a function after
performing some operations. In such cases, we can make use of the return statement in JavaScript. This
is an optional statement and most of the times the last statement in a JavaScript function.
Syntax: return value;
The return statement begins with the keyword return separated by the value which we want to return
from it.
Example: Create a html document which adds two numbers and returns the value.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript</h1>
<script>
function Sum(val1, val2)
{
return val1 + val2;
};document.write(Sum(10,20));
</script>
</body>
</html>
Date: / /2022