You are on page 1of 109

Date: / /2022

Pandas Data series:

⦁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("Pandas Series and type")

print(ds)

print(type(ds))

print("Convert Pandas Series to Python list")

print(ds.tolist())

print(type(ds.tolist()))

Sample Output:

Pandas Series and type

0 2

1 4

2 6

3 8

4 10

dtype: int64

<class 'pandas.core.series.Series'>

Convert Pandas Series to Python list

[2, 4, 6, 8, 10]

<class 'list'>
Date: / /2022

⦁Write a Pandas program to add, subtract, multiple and divide two Pandas Series

Sample Series: [2, 4, 6, 8, 10], [1, 3, 5, 7, 9]

Code:

import pandas as pd

ds1 = pd.Series([2, 4, 6, 8, 10])

ds2 = pd.Series([1, 3, 5, 7, 9])

ds = ds1 + ds2

print("Add two Series:")

print(ds)

print("Subtract two Series:")

ds = ds1 - ds2

print(ds)

print("Multiply two Series:")

ds = ds1 * ds2

print(ds)

print("Divide Series1 by Series2:")

ds = ds1 / ds2

print(ds)

Sample Output:

Add two Series:

0 3

1 7

2 11

3 15

4 19
Date: / /2022

dtype: int64

Subtract two Series:

0 1

1 1

2 1

3 1

4 1

dtype: int64

Multiply two Series:

0 2

1 12

2 30

3 56

4 90

dtype: int64

Divide Series1 by Series2:

0 2.000000

1 1.333333

2 1.200000

3 1.142857

4 1.111111

dtype: float64
Date: / /2022

⦁Write a Pandas program to convert a NumPy array to a Pandas series.

Sample NumPy array: d1 = [10, 20, 30, 40, 50]

Code:

import numpy as np

import pandas as pd

np_array = np.array([10, 20, 30, 40, 50])

print("NumPy array:")

print(np_array)

new_series = pd.Series(np_array)

print("Converted Pandas series:")

print(new_series)

Sample Output:

NumPy array:

[10 20 30 40 50]

Converted Pandas series:

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'],

'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],

'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],

'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'],

'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],

'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],

'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:

attempts name qualify score

a 1 Anastasia yes 12.5

b 3 Dima no 9.0

c 2 Katherine yes 16.5


Date: / /2022

d 3 James no NaN

e 2 Emily no 9.0

f 3 Michael yes 20.0

g 1 Matthew yes 14.5

h 1 Laura no NaN

i 2 Kevin no 8.0

j 1 Jonas yes 19.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'],

'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],

'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],

'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("\nChange the name 'James' to ‘Suresh’:")

df['name'] = df['name'].replace('James', 'Suresh')

print(df)
Date: / /2022

Sample Output:

Original rows:

attempts name qualify score

a 1 Anastasia yes 12.5

b 3 Dima no 9.0

c 2 Katherine yes 16.5

d 3 James no NaN

e 2 Emily no 9.0

f 3 Michael yes 20.0

g 1 Matthew yes 14.5

h 1 Laura no NaN

i 2 Kevin no 8.0

j 1 Jonas yes 19.0

Change the name 'James' to \‘Suresh\’:

attempts name qualify score

a 1 Anastasia yes 12.5

b 3 Dima no 9.0

c 2 Katherine yes 16.5

d 3 Suresh no NaN

e 2 Emily no 9.0

f 3 Michael yes 20.0

g 1 Matthew yes 14.5

h 1 Laura no NaN
Date: / /2022

i 2 Kevin no 8.0

j 1 Jonas yes 19.0

3.Write a Pandas program to insert a new column in existing DataFrame.

Code:

import pandas as pd

import numpy as np

exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura',
'Kevin', 'Jonas'],

'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],

'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],

'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("\nNew DataFrame after inserting the 'color' column")

print(df)

Sample Output:

Original rows:

attempts name qualify score


Date: / /2022

a 1 Anastasia yes 12.5

b 3 Dima no 9.0

c 2 Katherine yes 16.5

d 3 James no NaN

e 2 Emily no 9.0

f 3 Michael yes 20.0

g 1 Matthew yes 14.5

h 1 Laura no NaN

i 2 Kevin no 8.0

j 1 Jonas yes 19.0

New DataFrame after inserting the 'color' column

attempts name qualify score color

a 1 Anastasia yes 12.5 Red

b 3 Dima no 9.0 Blue

c 2 Katherine yes 16.5 Orange

d 3 James no NaN Red

e 2 Emily no 9.0 White

f 3 Michael yes 20.0 White

g 1 Matthew yes 14.5 Blue

h 1 Laura no NaN Green

i 2 Kevin no 8.0 Green

j 1 Jonas yes 19.0 Red


Date: / /2022

4. Write a Pandas program to get list from DataFrame column headers.

Code:

import pandas as pd

import numpy as np

exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James'],

'score': [12.5, 9, 16.5, np.nan,],

'attempts': [1, 3, 2, 3],

'qualify': ['yes', 'no', 'yes', 'no']}

labels = ['a', 'b', 'c', 'd']

df = pd.DataFrame(exam_data , index=labels)

print(list(df.columns.values))

Sample Output:

Original rows

Name score attempt qualify

A Anastasia 12.5 1 yes

B Dima 9 3 no

C Katherine 16.5 2 yes

D James nan 3 no

['attempts', 'name', 'qualify', 'score']


Date: / /2022

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:

0 s001 V Alberto Franco 15/05/2002 35 street1 t1

1 s002 V Gino Mcneill 17/05/2002 32 street2 t2

2 s003 VI Ryan Parkes 16/02/1999 33 street3 t3

3 s001 VI Eesha Hinton 25/09/1998 30 street1 t4

4 s002 V Gino Mcneill 11/05/2002 31 street2 t5

5 s004 VI David Parkes 15/09/1997 32 street4 t6

Code:

import pandas as pd

df = pd.DataFrame({ 'school_code': ['s001','s002','s003','s001','s002','s004'],

'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],

'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'],

'weight': [35, 32, 33, 30, 31, 32],

'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4'],

't_id':['t1', 't2', 't3', 't4', 't5', 't6']})

print("Default Index:")

print(df.head(10))

print("\nschool_code as new Index:")

df1 = df.set_index('school_code')
Date: / /2022

print(df1)

print("\nt_id as new Index:")

df2 = df.set_index('t_id')

print(df2)

Sample Output:

Default Index:

school_code class name date_Of_Birth weight address t_id

0 s001 V Alberto Franco 15/05/2002 35 street1 t1

1 s002 V Gino Mcneill 17/05/2002 32 street2 t2

2 s003 VI Ryan Parkes 16/02/1999 33 street3 t3

3 s001 VI Eesha Hinton 25/09/1998 30 street1 t4

4 s002 V Gino Mcneill 11/05/2002 31 street2 t5

5 s004 VI David Parkes 15/09/1997 32 street4 t6

t_id as new Index:

school_code class name date_Of_Birth weight address

t_id

t1 s001 V Alberto Franco 15/05/2002 35 street1

t2 s002 V Gino Mcneill 17/05/2002 32 street2

t3 s003 VI Ryan Parkes 16/02/1999 33 street3

t4 s001 VI Eesha Hinton 25/09/1998 30 street1

t5 s002 V Gino Mcneill 11/05/2002 31 street2

t6 s004 VI David Parkes 15/09/1997 32 street4


Date: / /2022

Reset the index:

t_id school_code class name date_Of_Birth weight address

0 t1 s001 V Alberto Franco 15/05/2002 35 street1

1 t2 s002 V Gino Mcneill 17/05/2002 32 street2

2 t3 s003 VI Ryan Parkes 16/02/1999 33 street3

3 t4 s001 VI Eesha Hinton 25/09/1998 30 street1

4 t5 s002 V Gino Mcneill 11/05/2002 31 street2

5 t6 s004 VI David Parkes 15/09/1997 32 street4


Date: / /2022

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:

0 s001 V Alberto Franco 15/05/2002 35 street1 t1

1 s002 V Gino Mcneill 17/05/2002 32 street2 t2

2 s003 VI Ryan Parkes 16/02/1999 33 street3 t3

3 s001 VI Eesha Hinton 25/09/1998 30 street1 t4

4 s002 V Gino Mcneill 11/05/2002 31 street2 t5

5 s004 VI David Parkes 15/09/1997 32 street4 t6

Code:

import pandas as pd

print("Create an Int64Index:")

df_i64 = pd.DataFrame({

'school_code': ['s001','s002','s003','s001','s002','s004'],

'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],

'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'],

'weight': [35, 32, 33, 30, 31, 32],

'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},

index=[1, 2, 3, 4, 5, 6])

print(df_i64)

print("\nView the Index:")

print(df_i64.index)

print("\nFloating-point labels using Float64Index:")

df_f64 = pd.DataFrame({

'school_code': ['s001','s002','s003','s001','s002','s004'],
Date: / /2022

'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],

'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'],

'weight': [35, 32, 33, 30, 31, 32],

'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},

index=[.1, .2, .3, .4, .5, .6])

print(df_f64)

print("\nView the Index:")

print(df_f64.index)

Sample Output:

Create an Int64Index:

school_code class name date_Of_Birth weight address

1 s001 V Alberto Franco 15/05/2002 35 street1

2 s002 V Gino Mcneill 17/05/2002 32 street2

3 s003 VI Ryan Parkes 16/02/1999 33 street3

4 s001 VI Eesha Hinton 25/09/1998 30 street1

5 s002 V Gino Mcneill 11/05/2002 31 street2

6 s004 VI David Parkes 15/09/1997 32 street4

View the Index:

Int64Index([1, 2, 3, 4, 5, 6], dtype='int64')

Floating-point labels using Float64Index:


Date: / /2022

school_code class name date_Of_Birth weight address

0.1 s001 V Alberto Franco 15/05/2002 35 street1

0.2 s002 V Gino Mcneill 17/05/2002 32 street2

0.3 s003 VI Ryan Parkes 16/02/1999 33 street3

0.4 s001 VI Eesha Hinton 25/09/1998 30 street1

0.5 s002 V Gino Mcneill 11/05/2002 31 street2

0.6 s004 VI David Parkes 15/09/1997 32 street4

View the Index:

Float64Index([0.1, 0.2, 0.3, 0.4, 0.5, 0.6], dtype='float64')


Date: / /2022

Pandas: String and Regular Expression

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("\nConvert all string values of the said Series to upper case:")

print(s.str.upper())

print("\nConvert all string values of the said Series to lower case:")

print(s.str.lower())

print("\nLength of the string values of the said Series:")

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

Convert all string values of the said Series to upper case:

0 X

1 Y

2 Z

3 AABA

4 BACA

5 NaN

6 CABA

7 None

8 BIRD

9 HORSE

10 DOG

dtype: object

Convert all string values of the said Series to lower case:

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

Length of the string values of the said Series:

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("\nRemove left sided whitespace")

print(color1.str.lstrip())

print("\nRemove Right sided whitespace")

print(color1.str.rstrip())

Sample Output:

Original series:

Index([' Green', 'Black ', ' Red ', 'White', ' Pink '], dtype='object')

Remove whitespace

Index(['Green', 'Black', 'Red', 'White', 'Pink'], dtype='object')

Remove left sided whitespace

Index(['Green', 'Black ', 'Red ', 'White', 'Pink '], dtype='object')

Remove Right sided whitespace

Index([' Green', 'Black', ' Red', 'White', ' Pink'], dtype='object')


Date: / /2022

3. Write a Pandas program to count of occurrence of a specified substring in a DataFrame column.

Code:

import pandas as pd

df = pd.DataFrame({

'name_code': ['c001','c002','c022', 'c2002', 'c2222'],

'date_of_birth ': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],

'age': [18.5, 21.2, 22.5, 22, 23]

})

print("Original DataFrame:")

print(df)

print("\nCount occurrence of 2 in date_of_birth column:")

df['count'] = list(map(lambda x: x.count("2"), df['name_code']))

print(df)

Sample Output:

Original DataFrame:

name_code date_of_birth age

0 c001 12/05/2002 18.5

1 c002 16/02/1999 21.2

2 c022 25/09/1998 22.5

3 c2002 12/02/2022 22.0

4 c2222 15/09/1997 23.0

Count occurrence of 2 in date_of_birth column:


Date: / /2022

name_code date_of_birth age count

0 c001 12/05/2002 18.5 0

1 c002 16/02/1999 21.2 1

2 c022 25/09/1998 22.5 2

3 c2002 12/02/2022 22.0 2

4 c2222 15/09/1997 23.0 4

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({

'company_code': ['Abcd','EFGF', 'zefsalf', 'sdfslew', 'zekfsdf'],

'date_of_sale': ['12/05/2002','16/02/1999','25/09/1998','12/02/2022','15/09/1997'],

'sale_amount': [12348.5, 233331.2, 22.5, 2566552.0, 23.0]

})

print("Original DataFrame:")

print(df)

print("\nSwapp cases in comapny_code:")

df['swapped_company_code'] = list(map(lambda x: x.swapcase(), df['company_code']))

print(df)

Sample Output:
Date: / /2022

Original DataFrame:

company_code date_of_sale sale_amount

0 Abcd 12/05/2002 12348.5

1 EFGF 16/02/1999 233331.2

2 zefsalf 25/09/1998 22.5

3 sdfslew 12/02/2022 2566552.0

4 zekfsdf 15/09/1997 23.0

Swapp cases in comapny_code:

company_code ... swapped_company_code

0 Abcd ... aBCD

1 EFGF ... efgf

2 zefsalf .. ZEFSALF

3 sdfslew ... SDFSLEW

4 zekfsdf ... ZEKFSDF

[5 rows x 4 columns]
Date: / /2022

Pandas Joining and merging DataFrame

1. Write a Pandas program to join the two given dataframes along rows and assign all data.

Test Data:

student_data1:

student_id name marks

0 S1 Danniella Fenton 200

1 S2 Ryder Storey 210

2 S3 Bryce Jensen 190

3 S4 Ed Bernal 222

4 S5 Kwame Morin 199

student_data2:

student_id name marks

0 S4 Scarlette Fisher 201

1 S5 Carla Williamson 200

2 S6 Dante Morse 198

3 S7 Kaiser William 219

4 S8 Madeeha Preston 201

Code:

import pandas as pd

student_data1 = pd.DataFrame({

'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'],

'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],

'marks': [200, 210, 190, 222, 199]})

student_data2 = pd.DataFrame({'student_id': ['S4', 'S5', 'S6', 'S7', 'S8'],


Date: / /2022

'name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse', 'Kaiser William', 'Madeeha Preston'],

'marks': [201, 200, 198, 219, 201]})

print("Original DataFrames:")

print(student_data1)

print("-------------------------------------")

print(student_data2)

print("\nJoin the said two dataframes along rows:")

result_data = pd.concat([student_data1, student_data2])

print(result_data)

Sample Output:

Original DataFrames:

student_id name marks

0 S1 Danniella Fenton 200

1 S2 Ryder Storey 210

2 S3 Bryce Jensen 190

3 S4 Ed Bernal 222

4 S5 Kwame Morin 199

-------------------------------------

student_id name marks

0 S4 Scarlette Fisher 201

1 S5 Carla Williamson 200

2 S6 Dante Morse 198

3 S7 Kaiser William 219

4 S8 Madeeha Preston 201


Date: / /2022

Join the said two dataframes along rows:

student_id name marks

0 S1 Danniella Fenton 200

1 S2 Ryder Storey 210

2 S3 Bryce Jensen 190

3 S4 Ed Bernal 222

4 S5 Kwame Morin 199

0 S4 Scarlette Fisher 201

1 S5 Carla Williamson 200

2 S6 Dante Morse 198

3 S7 Kaiser William 219

4 S8 Madeeha Preston 201


Date: / /2022

2. Write a Pandas program to append a list of dictioneries or series to a existing DataFrame and display
the combined data

Test Data:

student_id name marks

0 S1 Danniella Fenton 200

1 S2 Ryder Storey 210

2 S3 Bryce Jensen 190

3 S4 Ed Bernal 222

4 S5 Kwame Morin 199

Dictionary:

student_id S6

name Scarlette Fisher

marks 205

dtype: object

Code:

import pandas as pd

student_data1 = pd.DataFrame({

'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'],

'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],

'marks': [200, 210, 190, 222, 199]})

s6 = pd.Series(['S6', 'Scarlette Fisher', 205], index=['student_id', 'name', 'marks'])


Date: / /2022

dicts = [{'student_id': 'S6', 'name': 'Scarlette Fisher', 'marks': 203},

{'student_id': 'S7', 'name': 'Bryce Jensen', 'marks': 207}]

print("Original DataFrames:")

print(student_data1)

print("\nDictionary:")

print(s6)

combined_data = student_data1.append(dicts, ignore_index=True, sort=False)

print("\nCombined Data:")

print(combined_data)

Sample Output:

Original DataFrames:

student_id name marks

0 S1 Danniella Fenton 200

1 S2 Ryder Storey 210

2 S3 Bryce Jensen 190

3 S4 Ed Bernal 222

4 S5 Kwame Morin 199

Dictionary:

student_id S6

name Scarlette Fisher

marks 205
Date: / /2022

dtype: object

Combined Data:

student_id name marks

0 S1 Danniella Fenton 200

1 S2 Ryder Storey 210

2 S3 Bryce Jensen 190

3 S4 Ed Bernal 222

4 S5 Kwame Morin 199

5 S6 Scarlette Fisher 203

6 S7 Bryce Jensen 207


Date: / /2022

3. Write a Pandas program to join the two dataframes with matching records from both sides where
available.

Test Data:

student_data1:

student_id name marks

0 S1 Danniella Fenton 200

1 S2 Ryder Storey 210

2 S3 Bryce Jensen 190

3 S4 Ed Bernal 222

4 S5 Kwame Morin 199

student_data2:

student_id name marks

0 S4 Scarlette Fisher 201

1 S5 Carla Williamson 200

2 S6 Dante Morse 198

3 S7 Kaiser William 219

4 S8 Madeeha Preston 201

Code:

import pandas as pd

student_data1 = pd.DataFrame({

'student_id': ['S1', 'S2', 'S3', 'S4', 'S5'],

'name': ['Danniella Fenton', 'Ryder Storey', 'Bryce Jensen', 'Ed Bernal', 'Kwame Morin'],

'marks': [200, 210, 190, 222, 199]})

student_data2 = pd.DataFrame({

'student_id': ['S4', 'S5', 'S6', 'S7', 'S8'],


Date: / /2022

'name': ['Scarlette Fisher', 'Carla Williamson', 'Dante Morse', 'Kaiser William', 'Madeeha Preston'],

'marks': [201, 200, 198, 219, 201]})

print("Original DataFrames:")

print(student_data1)

print(student_data2)

merged_data = pd.merge(student_data1, student_data2, on='student_id', how='outer')

print("Merged data (outer join):")

print(merged_data)

Sample Output:

Original DataFrames:

student_id name marks

0 S1 Danniella Fenton 200

1 S2 Ryder Storey 210

2 S3 Bryce Jensen 190

3 S4 Ed Bernal 222

4 S5 Kwame Morin 199

student_id name marks

0 S4 Scarlette Fisher 201

1 S5 Carla Williamson 200

2 S6 Dante Morse 198

3 S7 Kaiser William 219

4 S8 Madeeha Preston 201


Date: / /2022

Merged data (outer join):

student_id name_x marks_x name_y marks_y

0 S1 Danniella Fenton 200.0 NaN NaN

1 S2 Ryder Storey 210.0 NaN NaN

2 S3 Bryce Jensen 190.0 NaN NaN

3 S4 Ed Bernal 222.0 Scarlette Fisher 201.0

4 S5 Kwame Morin 199.0 Carla Williamson 200.0

5 S6 NaN NaN Dante Morse 198.0

6 S7 NaN NaN Kaiser William 219.0

7 S8 NaN NaN Madeeha Preston 201.0


Date: / /2022

Pandas Time Series

1. Write a Pandas program to create

a) Datetime object for Jan 15 2012.

b) Specific date and time of 9:20 pm.

c) Local date and time.

d) A date without time.

e) Current date.

f) Time from a datetime.

g) Current local time.

Code:

import datetime

from datetime import datetime

print("Datetime object for Jan 15 2012:")

print(datetime(2012, 1, 15))

print("\nSpecific date and time of 9:20 pm")

print(datetime(2011, 1, 15, 21, 20))

print("\nLocal date and time:")

print(datetime.now())

print("\nA date without time: ")

print(datetime.date(datetime(2012, 5, 22)))

print("\nCurrent date:")

print(datetime.now().date())

print("\nTime from a datetime:")

print(datetime.time(datetime(2012, 12, 15, 18, 12)))


Date: / /2022

print("\nCurrent local time:")

print(datetime.now().time())

Sample Output:

Datetime object for Jan 15 2012:

2012-01-15 00:00:00

Specific date and time of 9:20 pm

2011-01-15 21:20:00

Local date and time:

2020-08-17 09:56:17.459790

A date without time:

2012-05-22

Current date:

2020-08-17

Time from a datetime:

18:12:00

Current local time:

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:

from datetime import datetime

date1 = datetime(year=2020, month=12, day=25)

print("Date from a given year, month, day:")

print(date1)

from dateutil import parser

date2 = parser.parse("1st of January, 2021")

print("\nDate from a given string formats:")

print(date2)

Sample Output:

Date from a given year, month, day:

2020-12-25 00:00:00

Date from a given string formats:

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

from datetime import datetime, date

dates = [datetime(2011, 9, 1), datetime(2011, 9, 2)]

print("Time-series with two index labels:")

time_series = pd.Series(np.random.randn(2), dates)

print(time_series)

print("\nType of the index:")

print(type(time_series.index))

Sample Output:

Time-series with two index labels:

2011-09-01 -0.257567

2011-09-02 0.947341

dtype: float64

Type of the index:

<class 'pandas.core.indexes.datetimes.DatetimeIndex'>
Date: / /2022

Pandas Grouping and Aggregating

Consider dataset:

school class name date_Of_Birth age height weight address

S1 s001 V Alberto Franco 15/05/2002 12 173 35 street1

S2 s002 V Gino Mcneill 17/05/2002 12 192 32 street2

S3 s003 VI Ryan Parkes 16/02/1999 13 186 33 street3

S4 s001 VI Eesha Hinton 25/09/1998 13 167 30 street1

S5 s002 V Gino Mcneill 11/05/2002 14 151 31 street2

S6 s004 VI David Parkes 15/09/1997 12 159 32 street4

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'],

'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],

'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'],

'age': [12, 12, 13, 13, 14, 12],

'height': [173, 192, 186, 167, 151, 159],

'weight': [35, 32, 33, 30, 31, 32],


Date: / /2022

'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},

index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])

print("Original DataFrame:")

print(student_data)

print('\nSplit the said data on school_code wise:')

result = student_data.groupby(['school_code'])

for name,group in result:

print("\nGroup:")

print(name)

print(group)

print("\nType of the object:")

print(type(result))

Sample Output:

Original DataFrame:

school_code class name ... height weight address

S1 s001 V Alberto Franco ... 173 35 street1

S2 s002 V Gino Mcneill ... 192 32 street2

S3 s003 VI Ryan Parkes ... 186 33 street3

S4 s001 VI Eesha Hinton ... 167 30 street1

S5 s002 V Gino Mcneill ... 151 31 street2

S6 s004 VI David Parkes ... 159 32 street4


Date: / /2022

[6 rows x 8 columns]

Split the said data on school_code wise:

Group:

s001

school_code class name ... height weight address

S1 s001 V Alberto Franco ... 173 35 street1

S4 s001 VI Eesha Hinton ... 167 30 street1

[2 rows x 8 columns]

Group:

s002

school_code class name ... height weight address

S2 s002 V Gino Mcneill ... 192 32 street2

S5 s002 V Gino Mcneill ... 151 31 street2

[2 rows x 8 columns]

Group:

s003

school_code class name ... height weight address

S3 s003 VI Ryan Parkes ... 186 33 street3

[1 rows x 8 columns]
Date: / /2022

Group:

s004

school_code class name ... height weight address

S6 s004 VI David Parkes ... 159 32 street4

[1 rows x 8 columns]

Type of the object:

<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'],

'class': ['V', 'V', 'VI', 'VI', 'V', 'VI'],

'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'],

'age': [12, 12, 13, 13, 14, 12],

'height': [173, 192, 186, 167, 151, 159],


Date: / /2022

'weight': [35, 32, 33, 30, 31, 32],

'address': ['street1', 'street2', 'street3', 'street1', 'street2', 'street4']},

index=['S1', 'S2', 'S3', 'S4', 'S5', 'S6'])

print("Original DataFrame:")

print(student_data)

print('\nMean, min, and max value of age for each value of the school:')

grouped_single = student_data.groupby('school_code').agg({'age': ['mean', 'min', 'max']})

print(grouped_single)

Sample Output:

Original DataFrame:

school_code class name ... height weight address

S1 s001 V Alberto Franco ... 173 35 street1

S2 s002 V Gino Mcneill ... 192 32 street2

S3 s003 VI Ryan Parkes ... 186 33 street3

S4 s001 VI Eesha Hinton ... 167 30 street1

S5 s002 V Gino Mcneill ... 151 31 street2

S6 s004 VI David Parkes ... 159 32 street4

[6 rows x 8 columns]

Mean, min, and max value of age for each value of the school:

age

mean min max


Date: / /2022

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)

df = pd.DataFrame({'A': np.linspace(1, 10, 10)})

df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],

axis=1)

print("Original array:")

print(df)

def color_negative_red(val):

color = 'red' if val < 0 else 'black'

return 'color: %s' % color

print("\nNegative numbers red and positive numbers black:")

df.style.applymap(color_negative_red)

Original array:

A B C D E

0 1.0 1.329212 -0.770033 -0.316280 -0.990810

1 2.0 -1.070816 -1.438713 0.564417 0.295722


Date: / /2022

2 3.0 -1.626404 0.219565 0.678805 1.889273

3 4.0 0.961538 0.104011 -0.481165 0.850229

4 5.0 1.453425 1.057737 0.165562 0.515018

5 6.0 -1.336936 0.562861 1.392855 -0.063328

6 7.0 0.121668 1.207603 -0.002040 1.627796

7 8.0 0.354493 1.037528 -0.385684 0.519818

8 9.0 1.686583 -1.325963 1.428984 -2.089354

9 10.0 -0.129820 0.631523 -0.586538 0.290720

Negative numbers red and positive numbers black:

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)

df = pd.DataFrame({'A': np.linspace(1, 10, 10)})

df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],

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):

'''

highlight the maximum in a Series green.

'''

is_max = s == s.max()

return ['background-color: green' if v else '' for v in is_max]

print("\nHighlight the maximum value in each column:")

df.style.apply(highlight_max,subset=pd.IndexSlice[:, ['B', 'C', 'D', 'E']])

Original array:

A B C D E

0 1.0 1.329212 -0.770033 -0.316280 -0.990810

1 2.0 -1.070816 -1.438713 0.564417 0.295722

2 3.0 -1.626404 0.219565 0.678805 1.889273

3 4.0 0.961538 0.104011 -0.481165 0.850229

4 5.0 1.453425 1.057737 0.165562 0.515018

5 6.0 -1.336936 0.562861 1.392855 -0.063328

6 7.0 0.121668 1.207603 -0.002040 1.627796

7 8.0 0.354493 1.037528 -0.385684 0.519818

8 9.0 1.686583 -1.325963 1.428984 -2.089354

9 10.0 -0.129820 0.631523 -0.586538 0.290720

Highlight the maximum value in each column:


Date: / /2022

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)

df = pd.DataFrame({'A': np.linspace(1, 10, 10)})

df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],

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'

return 'background-color: %s' % color

print("\nHighlight specific columns:")

df.style.applymap(highlight_cols, subset=pd.IndexSlice[:, ['B', 'C']])

Original array:

Original array:
Date: / /2022

A B C D E

0 1.0 1.329212 -0.770033 -0.316280 -0.990810

1 2.0 -1.070816 -1.438713 0.564417 0.295722

2 3.0 -1.626404 0.219565 0.678805 1.889273

3 4.0 0.961538 0.104011 -0.481165 0.850229

4 5.0 1.453425 1.057737 0.165562 0.515018

5 6.0 -1.336936 0.562861 1.392855 -0.063328

6 7.0 0.121668 1.207603 -0.002040 1.627796

7 8.0 0.354493 1.037528 -0.385684 0.519818

8 9.0 1.686583 -1.325963 1.428984 -2.089354

9 10.0 -0.129820 0.631523 -0.586538 0.290720

Highlight specific columns:

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:

Year MSHA ID Mine_Name Production Labor_Hours

2013 103381 Highwall Miner 56,004 22,392

2013 103404 Reid School Mine 28,807 8,447

2013 100759 Underground Min 14,40,115 4,74,784

2013 103246 Bear Creek 87,587 29,193

Code:

import pandas as pd

import numpy as np

df = pd.read_excel('E:\coalpublic2013.xlsx')

print(df.head)

Sample Output:

Year MSHA ID Mine_Name Production Labor_Hours

0 2013 103381 Highwall Miner 56004 22392

1 2013 103404 Reid School Mine 28807 28447

2 2013 100759 Underground Min 1440115 474784

3 2013 103246 Bear Creek 87587 29193


Date: / /2022

⦁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:

Year MSHA ID Mine_Name Production Labor_Hours

2013 103381 Highwall Miner 56,004 22,392

2013 103404 Reid School Mine 28,807 8,447

2013 100759 Underground Min 14,40,115 4,74,784

2013 103246 Bear Creek 87,587 29,193

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:

1) Write a Pandas program to import excel data into a Pandas dataframe.


Excel Data:

coalpublic2013.xlsx:

Year MSHA ID Mine_Name Production Labor_Hours


2013 103381 TacoaHighwall Miner 56,004 22,392
2013 103404 Reid School Mine 28,807 8,447
2013 100759 North River 14,40,115 4,74,784
2013 103246 Bear Creek 87,587 29,193
2013 103451 Knight Mine 1,47,499 46,393
2013 103433 Crane Central Mine 69,339 47,195
import pandas aspd
importnumpyas np
df=pd.read_excel('E:\coalpublic2013.xlsx')
print(df.head)

Sample output:

Year MSHA ID Mine_Name Production Labor_Hours


0 2013 103381TacoaHighwall Miner 56004 22392
1 2013 103404 Reid School Mine 28807 28447
2 2013 100759 North River 1440115 474784
3 2013 103246 Bear Creek 87587 29193
4 2013 103451 Knight Mine 147499 46393
5 2013 103433 Crane Central Mine 69339 47195
Date: / /2022

2)Write a Pandas program to find the sum, mean, max, min value of a column of file.

Year MSHA ID Mine_Name Production Labor_Hours


2013 103381 TacoaHighwall Miner 56,004 22,392
2013 103404 Reid School Mine 28,807 8,447
2013 100759 North River #1 Underground Min 14,40,115 4,74,784
2013 103246 Bear Creek 87,587 29,193
2013 103451 Knight Mine 1,47,499 46,393
2013 103433 Crane Central Mine 69,339 47,195
2013 100329 Concord Mine 0 1,44,002

import pandas aspd


importnumpyas 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())

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

import pandas aspd


importmatplotlib.pyplotasplt
df=pd.read_csv("alphabet_stock_data.csv")
start_date=pd.to_datetime('2020-4-1')
end_date=pd.to_datetime('2020-4-30')
df['Date']=pd.to_datetime(df['Date'])
new_df=(df['Date']>=start_date)&(df['Date']<=end_date)
df1 =df.loc[new_df]
df2 =df1[['Date','Open','Close']]
df3 = df2.set_index('Date')
plt.figure(figsize=(20,20))
df3.plot.barh(stacked=True)
plt.suptitle('Opening/Closing stock prices Alphabet Inc.,\n01-04-2020 to 30-04-2020',fontsize=12,
color='black')
plt.show()

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.

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

Code:

import pandas aspd


importmatplotlib.pyplotasplt
df=pd.read_csv("alphabet_stock_data.csv")
start_date=pd.to_datetime('2020-4-1')
end_date=pd.to_datetime('2020-9-30')
df['Date']=pd.to_datetime(df['Date'])
new_df=(df['Date']>=start_date)&(df['Date']<=end_date)
df1 =df.loc[new_df]
df2 = df1[['Open','Close','High','Low']]
#df3 = df2.set_index('Date')
plt.figure(figsize=(25,25))
df2.plot.hist(alpha=0.5)
plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet Inc.,\n From 01-04-2020 to 30-09-
2020',fontsize=12, color='blue')
plt.show()

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.

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

Code:

import pandas aspd


importmatplotlib.pyplotasplt
df=pd.read_csv("alphabet_stock_data.csv")
start_date=pd.to_datetime('2020-4-1')
end_date=pd.to_datetime('2020-9-30')
df['Date']=pd.to_datetime(df['Date'])
new_df=(df['Date']>=start_date)&(df['Date']<=end_date)
df1 =df.loc[new_df]
df2 = df1[['Open','Close','High','Low']]
plt.figure(figsize=(30,30))
df2.hist();
plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet Inc., From 01-04-2020 to 30-09-
2020',fontsize=12, color='black')
plt.show()
Date: / /2022

Output:

Pandas SQL Query:


Date: / /2022

1) Write a Pandas program to display all the records of a student file.

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

2)Write a Pandas program to select distinct department id from employees file.

import pandas aspd


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("Distinct department_id:")
print(employees.department_id.unique())

Output:
Date: / /2022

1. Introduction to Java Script:


• JavaScript was introduced and designed by Brendan Eich in December, 1995 under the name of
LiveScript.
• Netscape Navigator developed JavaScript and Microsoft’s version of JavaScriptis Jscript.
• The official name was ECMAScript as it was standardized by European Computer Manufacturer’s
Association(ECMA).
• Script means small piece of Code.
• Scripting Language is a high-level programming language, whose programs are interpreted by
another program at run time rather than compiled by the computer processor.
• Scripting languages are of 2 types.
client-side scripting languages
server-side scripting languages
• In general client-side scripting is used for performing simple validations at client-side. Server-side
scripting is used for database verifications.
Examples: VBScript, JavaScript and Jscript are examples for client-side scripting.ASP, JSP,
Servlets etc. are examples of server-side scripting.
• Simple HTML code is called static web page, if you add script to HTML page it is called dynamic page.

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

Java is a strongly typed language JavaScript is not strongly typed(Loosely Typed)

Developed by sun Microsystems. Developed by Netscape


Date: / /2022

2. Applying javascript (internal and external)

• 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

3. understanding JavaScript syntax

Embedding JavaScript in an HTML Page:


Embed a JavaScript in an HTML document by using <script> and </script> html tags.
Syntax:
<script ...>
JavaScript code
</script>
Date: / /2022

<script> tag has the following attributes:

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.

Example:Creating a script in an html document:

<html>

<body>

<script type="text/javascript" language=”javascript”>

alert("Hello Javatpoint");

</script>

</body>

</html>

Output:

Comments in JavaScript:

JavaScript supports both C-style and C++-style comments. Thus:

• 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

4. Introduction to document and window object


Document Object: The document object represent a web page that is loaded in the browser. By
accessing the document object, we can access the element in the HTML page. With the help of
document objects, we can add dynamic content to our web page. The document object can be
accessed with a window.document or just document.
Syntax:
document.property_name;
Properties of document:
• activeElement: It returns the currently active elements in the document.
• body: It returns the contents of the body element.
• anchors: It returns all <a> elements that have a name attribute.
• baseURI: It returns a string value that represents the base URI of the document.
• cookie: It returns the cookie of the current document.
• charSet: It returns a string, representing the document’s character encoding.
• defaultView: It returns the current Window Object.
• designMode: It is used to set documents as editable or read-only.
• domain: It returns the domain name of the document server.
• doctype: It returns the document’s doctype.
• embeds: It returns the collection of all embedded elements.
• URL: It returns the complete URL of the document.
• forms: It returns all the elements of the form.
• fullScreenElement: It returns the element that is currently present in full-screen mode.
• title: It returns the title element of the document.
• head: It returns the head element of the document.
• links: It returns all <area> and <a> elements that have a href attribute.
• lastModified: It returns the date and time of the current document that was last modified.
• images: It returns the collection of <img> elements in the document.
• implementation: It returns the DOMImplementation object associated with the current document.
• readyState: It returns the loading status of the current document.
• referrer: It returns the URI of the page that is linked to the current page.
• scripts: It returns all script elements present in the document.
• strictErrorChecking: It sets or returns whether strict error checking can be enforced on a document
or not.

<!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

• Window: It returns the current window or frame.


• Navigator: It returns a reference to the navigator object.
• outerHeight: It will get the height of the outside of the browser window.
• outerWidth: It will get the width of the outside of the browser window.
• Status: It overrides the default status and places a message in the status bar.
• Top: It returns a reference to the topmost window containing a frame if many windows are opened.
• Toolbar: It will result in the toolbar object, whose visibility can be toggled in the window.
• Opener: It contains a reference to the window that opened the current window.
• Parent: It refers to the frameset in which the current frame is contained.
• Screen: It refers to the screen object
• Self: It provides another way to refer to the current window.

<!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:

5. Variables and operators in JavaScript

➢ VARIABLES:

• Like any programming language JavaScript has variables.


• Variables store data and have a name, value and memory address.
• Name must be unique, value is the data stored in the variable and memory address refers to the
memory location of variable.
Syntax: var variable_name;
• Strict rules governing how you name your variables (Much like other languages) are:

Naming Conventions for Variables:

• Variable names must begin with a letter, underscore or dollar sign.


• You can’t use spaces in names
• Names are case sensitive so the variables fred, FRED and frEd all refer to different
variables.
• It is not a good idea to name variables with similar names
• You can’t use a reserved word as a variable name, e.g. var.
• Names cannot be enclosed in single or double quotes

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:

<Left operand> operator <right operand>

JavaScript includes following categories of operators.

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

+ Adds two numeric operands.

- Subtract right operand from left operand

* Multiply two numeric operands.

/ Divide left operand by right operand.

% Modulus operator. Returns remainder of two operands.

++ Increment operator. Increase operand value by one.

-- Decrement operator. Decrease value by one.

Example:

<!DOCTYPE html>

<html>

<body>

<h1>Demo: JavaScript Arithmetic Operators</h1>

<script>

var x = 5, y = 10;

document.write(x + y+"<br>"); //returns 15

document.write(y - x+"<br>"); //returns 5

document.write(x * y+"<br>"); //returns 50

document.write(y / x+"<br>"); //returns 2


Date: / /2022

document.write(x % 2+"<br>"); //returns 1

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.

Operator Description Example


&& Logical AND (10==20 && 20==33) = false
|| Logical OR (10==20 || 20==33) = false
! Logical Not !(10==20) = true

3. Assignment operators:

JavaScript includes assignment operators to assign values to variables with less key strokes.

Operator Description Example


Date: / /2022

= 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>

<body><h1>JavaScript Comparison Operators</h1>

<script>

var a = 5, b = 10, c = "5";

var x = a;

document.write((a == c)+"<br>");

document.write((a === c)+"<br>");

document.write((a == x)+"<br>");
Date: / /2022

document.write((a != b)+"<br>");

document.write((a > b)+"<br>");

document.write((a < b)+"<br>");

document.write((a >= b)+"<br>");

document.write((a <= b)+"<br>");

document.write((a >= c)+"<br>");

document.write((a <= c)+"<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.

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1


Date: / /2022

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< 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>

<h2>JavaScript Bitwise </h2>

<script>

var a = 6;

var b = 1;

// AND Operation

document.write("A & B = " + (a & b) + '<br>');

// OR operation

document.write("A | B = " + (a | b) + '<br>');

// NOT operation

document.write("~A = " + (~a) + '<br>');

// Sign Propagating Right Shift

document.write("A >> B = " + (a >> b) + '<br>');

// Zero Fill Right Shift


Date: / /2022

document.write("A >>> B = " + (a >>> b) + '<br>');

// Left Shift

document.write("A << B = " + (a << b) + '<br>');

</script>

</body>

</html>

Output:

6. Data types and num type conversion in javascript

➢ 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 f=3.; // considered as 3 only


var f=6e5;
// the output will be 60000. Large/small numbers can use e to represent.
var h=2e-4; // the output will be 0.0002
Strings:
Text in JavaScript is called as “Strings” and is a sequence of characters. To store the string value in a
variable, it must be enclosed between double quotes (” “) or single quotes(‘ ‘). But, the quotes must be
consistent. If started with single quote, one should end with single quote only.
Example:
var a=”javascript”; //valid
var b=” javascript”; //valid
var c=’ javascript”; //invalid
var d=” javascript’; //invalid
String Conversion: The values of other data types can be converted to strings. A string can be
concatenated with other string using +.
var a=”Hello”;
a=a+”World”; // outputs is Hello World
Boolean: Boolean type can be used to test the conditions and has only two values-true and false. Any
value in JavaScript can be converted into boolean using Boolean() function.

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:

Num type conversion in JavaScript


Converting Numbers to Strings
<!DOCTYPE html>
<html>
<body>
<h2>The JavaScript String() Method</h2>
<p>The String() method can convert a number to a string.</p>
<p id="demo"></p>
<script>
let x = 123;
document.getElementById("demo").innerHTML =
String(x) + "<br>" +
Date: / /2022

String(123) + "<br>" +
String(100 + 23);
</script>
</body>
</html>
OUTPUT:

The JavaScript String() Method

The String() method can convert a number to a string.

123
123
123

7. Math and String manipulation


Math Properties (Constants)

The syntax for any Math property is : Math.property.

JavaScript provides 8 mathematical constants that can be accessed as Math properties:

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

"<p><b>Math.LOG2E:</b> " + Math.LOG2E + "</p>" +


"<p><b>Math.Log10E:</b> " + Math.LOG10E + "</p>";
</script>
</body>
</html>
OUTPUT:

JavaScript Math Constants

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:

The syntax for Math any methods is : Math.method(number)

Number to Integer

There are 4 common methods to round a number to an integer:

Math.round(x) Returns x rounded to its nearest integer

Math.ceil(x) Returns x rounded up to its nearest integer


Date: / /2022

Math.floor(x) Returns x rounded down to its nearest integer

Math.trunc(x) Returns the integer part of x (new in ES6)

▪ Example: Math.round()

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Math.round()</h2>

<p>Math.round(x) returns the value of x rounded to its nearest integer:</p>

<p id="demo"></p>

<script>

document.getElementById("demo").innerHTML = Math.round(4.6);

</script>

</body>

</html>

OUTPUT:

JavaScript Math.round()

Math.round(x) returns the value of x rounded to its nearest integer: 5

▪ Example: Math.ceil()

<!DOCTYPE html>
Date: / /2022

<html>

<body>

<h2>JavaScript Math.ceil()</h2>

<p>Math.ceil() rounds a number <strong>up</strong> to its nearest integer:</p>

<p id="demo"></p>

<script>

document.getElementById("demo").innerHTML = Math.ceil(4.7);

</script>

</body>

</html>

OUTPUT:

JavaScript Math.ceil()

Math.ceil() rounds a number up to its nearest integer: 5

▪ Example: Math.floor()

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Math.floor()</h2>

<p>Math.floor(x) returns the value of x rounded <strong>down</strong> to its nearest integer:</p>

<p id="demo"></p>

<script>

document.getElementById("demo").innerHTML = Math.floor(4.7);
Date: / /2022

</script>

</body>

</html>

OUTPUT:

JavaScript Math.floor()

Math.floor(x) returns the value of x rounded down to its nearest integer: 4

▪ Example: Math.trunc()

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Math.trunc()</h2>

<p>Math.trunc(x) returns the integer part of x:</p>

<p id="demo"></p>

<script>

document.getElementById("demo").innerHTML = Math.trunc(4.7);

</script>

</body>

</html>

OUTPUT:

JavaScript Math.trunc()

Math.trunc(x) returns the integer part of x: 4

▪ Math.pow()

Math.pow(x, y) returns the value of x to the power of y:


Date: / /2022

Example:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Math.pow()</h2>

<p>Math.pow(x,y) returns the value of x to the power of y:</p>

<p id="demo"></p>

<script>

document.getElementById("demo").innerHTML = Math.pow(8,2);

</script>

</body>

</html>

OUTPUT:

JavaScript Math.pow()

Math.pow(x,y) returns the value of x to the power of y: 64

▪ Math.sqrt()

Math.sqrt(x) returns the square root of x:

Example:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Math.sqrt()</h2>

<p>Math.sqrt(x) returns the square root of x:</p>

<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

Here is a list of the properties of String object and their description.

Sr.No. Property & Description

1 constructor

Returns a reference to the String function that created the object.

2 length

Returns the length of the string.

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.

Sr.No. Method & Description

1 charAt()

Returns the character at the specified index.

2 charCodeAt()

Returns a number indicating the Unicode value of the character at the given index.

3 concat()

Combines the text of two strings and returns a new string.

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()

Used to match a regular expression against a string.

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()

Extracts a section of a string and returns a new string.

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()

Returns the calling string value converted to lower case.

17 toString()

Returns a string representing the specified object.

18 toUpperCase()

Returns the calling string value converted to uppercase.

19 valueOf()

Returns the primitive value of the specified object.

String HTML Wrappers


Date: / /2022

Here is a list of the methods that return a copy of the string wrapped inside an appropriate HTML tag.

Sr.No. Method & Description

1 anchor()

Creates an HTML anchor that is used as a hypertext target.

2 big()

Creates a string to be displayed in a big font as if it were in a <big> tag.

3 blink()

Creates a string to blink as if it were in a <blink> tag.

4 bold()

Creates a string to be displayed as bold as if it were in a <b> tag.

5 fixed()

Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag

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()

Causes a string to be italic, as if it were in an <i> tag.

9 link()

Creates an HTML hypertext link that requests another URL.

10 small()
Date: / /2022

Causes a string to be displayed in a small font, as if it were in a <small> tag.

11 strike()

Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.

12 sub()

Causes a string to be displayed as a subscript, as if it were in a <sub> tag

13 sup()

Causes a string to be displayed as a superscript, as if it were in a <sup> tag

▪ 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

Use the following syntax to find the character at a particular index.


string.charAt(index);

Example

Try the following 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

▪ JavaScript String - concat() Method

Description

This method adds two or more strings and returns a new single string.

Syntax

Its syntax is as follows −


string.concat(string2, string3[, ..., stringN]);

Argument Details

string2...stringN − These are the strings to be concatenated.

Example

Try the following 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

Concatenated String :This is string oneThis is string two.

▪ JavaScript String - split() Method

Description

This method splits a String object into an array of strings by separating the string into substrings.

Syntax

Its syntax is as follows −


string.split([separator][, limit]);

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

Try the following 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

▪ JavaScript String - toLocaleLowerCase() Method

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

Its syntax is as follows −


string.toLocaleLowerCase( )

Example

Try the following 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

apples are round, and apples are juicy


8. Objects and Arrays

▪ JavaScript - Objects Overview

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

Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of


the object, otherwise the attribute is considered a property.

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.

var employee = new Object();


var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
The Object() Constructor
A constructor is a function that creates and initializes an object. JavaScript provides a special constructor
function called Object() to build the object. The return value of the Object() constructor is assigned to a
variable.
Date: / /2022

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

Defining Methods for an Object

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;
}

function book(title, author) {


this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>

<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);

document.write("Book title is : " + myBook.title + "<br>");


document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Output
Book title is : Perl
Book author is : Mohtashim
Book price is : 100
Date: / /2022

JavaScript Native Objects

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>

var cars = ["Saab", "Volvo", "BMW"];

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.

9. Date and Time

➢ 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 constructors to create date object are:

Date()

Date(milliseconds)

Date(dateString)

Date(year, month, day, hours, minutes, seconds, milliseconds)

Example1:Program which prints current date and time using date object.

<html>

<body>

Current Date and Time:

<script>

var today=new Date();

document.write(today);

</script>
Date: / /2022

</body>

</html>

Output:

Example2: code to print date/month/year.

<html>

<body>

<script>

var date=new Date();

var day=date.getDate();

var month=date.getMonth()+1;

var year=date.getFullYear();

document.write("<br>Date is: "+day+"/"+month+"/"+year);

</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.

toDateString() It returns the date portion of a Date object.

10. Conditional Statements

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:

11. Switch case

➢ 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:

switch(expression or literal value){


case 1:
//code to be executed
break;
case 2:
//code to be executed
break;
case n:
//code to be executed
break;
default:
//default code to be executed
//if none of the above case executed
}
Example:switch.html
<!DOCTYPE html>
<html>
<body>
<h1>Demo: switch case</h1>
Date: / /2022

<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.

for (initialization; condition; increment)


{
code to be executed
}
Example: for.html

<!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>A loop with a break.</p>

<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

You might also like