0% found this document useful (0 votes)
257 views296 pages

Print

The document discusses Python Numpy and Pandas libraries. It provides an overview of Numpy, describing it as a general-purpose array processing package that provides multidimensional array objects and tools. It then discusses arrays in Numpy, including how they are indexed and accessed. It also covers creating Numpy arrays, accessing array indices through slicing and indexing, and performing basic array operations. The document then discusses data types in Numpy before introducing Pandas, covering its advantages, history, and the Series and DataFrame data structures.

Uploaded by

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

Print

The document discusses Python Numpy and Pandas libraries. It provides an overview of Numpy, describing it as a general-purpose array processing package that provides multidimensional array objects and tools. It then discusses arrays in Numpy, including how they are indexed and accessed. It also covers creating Numpy arrays, accessing array indices through slicing and indexing, and performing basic array operations. The document then discusses data types in Numpy before introducing Pandas, covering its advantages, history, and the Series and DataFrame data structures.

Uploaded by

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

Python Numpy

Numpy is a general-purpose array-processing package. It provides a high-


performance multidimensional array object, and tools for working with these
arrays. It is the fundamental package for scientific computing with Python.
Besides its obvious scientific uses, Numpy can also be used as an efficient multi-
dimensional container of generic data.
Arrays in Numpy
Array in Numpy is a table of elements (usually numbers), all of the same type,
indexed by a tuple of positive integers. In Numpy, number of dimensions of the
array is called rank of the array.A tuple of integers giving the size of the array
along each dimension is known as shape of the array. An array class in Numpy
is called as ndarray. Elements in Numpy arrays are accessed by using square
brackets and can be initialized by using nested Python Lists.
Creating a Numpy Array
Arrays in Numpy can be created by multiple ways, with various number of
Ranks, defining the size of the Array. Arrays can also be created with the use of
various data types such as lists, tuples, etc. The type of the resultant array is
deduced from the type of the elements in the sequences. Note: Type of array can
be explicitly defined while creating the array.
# Python program for Creation of Arrays
import numpy as np
# Creating a rank 1 Array
arr = np.array([1, 2, 3])
print("Array with Rank 1: \n",arr)
# Creating a rank 2 Array
arr = np.array([[1, 2, 3],
[4, 5, 6]])
print("Array with Rank 2: \n", arr)
# Creating an array from tuple
arr = np.array((1, 3, 2))
print("\nArray created using "
"passed tuple:\n", arr)
Output:
Array with Rank 1:
[1 2 3]
Array with Rank 2:
[[1 2 3]
[4 5 6]]
Array created using passed tuple:
[1 3 2]
Accessing the array Index
In a numpy array, indexing or accessing the array index can be done in multiple
ways. To print a range of an array, slicing is done. Slicing of an array is defining
a range in a new array which is used to print a range of elements from the original
array. Since, sliced array holds a range of elements of the original array,
modifying content with the help of sliced array modifies the original array
content.
# Python program to demonstrate indexing in numpy array
import numpy as np
# Initial Array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
print("Initial Array: ")
print(arr)
# Printing a range of Array
# with the use of slicing method
sliced_arr = arr[:2, ::2]
print ("Array with first 2 rows and"
" alternate columns(0 and 2):\n", sliced_arr)
# Printing elements at
# specific Indices
Index_arr = arr[[1, 1, 0, 3],
[3, 2, 1, 0]]
print ("\nElements at indices (1, 3), "
"(1, 2), (0, 1), (3, 0):\n", Index_arr)
Output:
Initial Array:
[[-1. 2. 0. 4. ]
[ 4. -0.5 6. 0. ]
[ 2.6 0. 7. 8. ]
[ 3. -7. 4. 2. ]]
Array with first 2 rows and alternate columns(0 and 2):
[[-1. 0.]
[ 4. 6.]]

Elements at indices (1, 3), (1, 2), (0, 1), (3, 0):
[ 0. 54. 2. 3.]
Basic Array Operations
In numpy, arrays allow a wide range of operations which can be performed on a
particular array or a combination of Arrays. These operation include some basic
Mathematical operation as well as Unary and Binary operations.
# Python program to demonstrate basic operations on single array
import numpy as np
# Defining Array 1
a = np.array([[1, 2],
[3, 4]])
# Defining Array 2
b = np.array([[4, 3],
[2, 1]])
# Adding 1 to every element
print ("Adding 1 to every element:", a + 1)
# Subtracting 2 from each element
print ("\nSubtracting 2 from each element:", b - 2)
# sum of array elements
# Performing Unary operations
print ("\nSum of all array "
"elements: ", a.sum())
# Adding two arrays
# Performing Binary operations
print ("\nArray sum:\n", a + b)
Run on IDE

Output:
Adding 1 to every element:
[[2 3]
[4 5]]
Subtracting 2 from each element:
[[ 2 1]
[ 0 -1]]
Sum of all array elements: 10
Array sum:
[[5 5]
[5 5]]

Data Types in Numpy


Every Numpy array is a table of elements (usually numbers), all of the same type,
indexed by a tuple of positive integers. Every ndarray has an associated data
type (dtype) object. This data type object (dtype) provides information about the
layout of the array. The values of an ndarray are stored in a buffer which can be
thought of as a contiguous block of memory bytes which can be interpreted by
the dtype object. Numpy provides a large set of numeric datatypes that can be
used to construct arrays. At the time of Array creation, Numpy tries to guess a
datatype, but functions that construct arrays usually also include an optional
argument to explicitly specify the datatype.
Constructing a Datatype Object
In Numpy, datatypes of Arrays need not to be defined unless a specific datatype
is required. Numpy tries to guess the datatype for Arrays which are not
predefined in the constructor function.
# Python Program to create a data type object
import numpy as np
# Integer datatype
# guessed by Numpy
x = np.array([1, 2])
print("Integer Datatype: ")
print(x.dtype)
# Float datatype
# guessed by Numpy
x = np.array([1.0, 2.0])
print("\nFloat Datatype: ")
print(x.dtype)
# Forced Datatype
x = np.array([1, 2], dtype = np.int64)
print("\nForcing a Datatype: ")
print(x.dtype)
Output:
Integer Datatype:
int64
Float Datatype:
float64
Forcing a Datatype:
int64
Math Operations on DataType array
In Numpy arrays, basic mathematical operations are performed element-wise on
the array. These operations are applied both as operator overloads and as
functions. Many useful functions are provided in Numpy for performing
computations on Arrays such as sum: for addition of Array elements, T: for
Transpose of elements, etc.
# Python Program to create
# a data type object
import numpy as np
# First Array
arr1 = np.array([[4, 7], [2, 6]],
dtype = np.float64)
# Second Array
arr2 = np.array([[3, 6], [2, 8]],
dtype = np.float64)
# Addition of two Arrays
Sum = np.add(arr1, arr2)
print("Addition of Two Arrays: ")
print(Sum)
# Addition of all Array elements
# using predefined sum method
Sum1 = np.sum(arr1)
print("\nAddition of Array elements: ")
print(Sum1)
# Square root of Array
Sqrt = np.sqrt(arr1)
print("\nSquare root of Array1 elements: ")
print(Sqrt)
# Transpose of Array
# using In-built function 'T'
Trans_arr = arr1.T
print("\nTranspose of Array: ")
print(Trans_arr)
Output:
Addition of Two Arrays:
[[ 7. 13.]
[ 4. 14.]]
Addition of Array elements:
19.0
Square root of Array1 elements:
[[2. 2.64575131]
[1.41421356 2.44948974]]
Transpose of Array:
[[4. 2.]
[7. 6.]]
Introduction to Pandas in Python
Pandas is an open-source library that is made mainly for working with relational
or labeled data both easily and intuitively. It provides various data structures
and operations for manipulating numerical data and time series. This library is
built on top of the NumPy library. Pandas is fast and it has high performance &
productivity for users.

History
Pandas were initially developed by Wes McKinney in 2008 while he was working
at AQR Capital Management. He convinced the AQR to allow him to open source
the Pandas. Another AQR employee, Chang She, joined as the second major
contributor to the library in 2012. Over time many versions of pandas have been
released. The latest version of the pandas is 1.0.1

Advantages
• Fast and efficient for manipulating and analyzing data.
• Data from different file objects can be loaded.
• Easy handling of missing data (represented as NaN) in floating point as
well as non-floating-point data
• Size mutability: columns can be inserted and deleted from DataFrame and
higher dimensional objects
• Data set merging and joining.
• Flexible reshaping and pivoting of data sets
• Provides time-series functionality.
• Powerful group by functionality for performing split-apply-combine
operations on data sets.

Working With Pandas


After the pandas have been installed into the system, you need to import the
library. This module is generally imported as:
import pandas as pd
Here, pd is referred to as an alias to the Pandas. However, it is not necessary to
import the library using the alias, it just helps in writing less amount code every
time a method or property is called.

Pandas generally provide two data structures for manipulating data, They are:
• Series
• DataFrame
Series:
Pandas Series is a one-dimensional labelled array capable of holding data of any
type (integer, string, float, python objects, etc.). The axis labels are collectively
called indexes. Pandas Series is nothing but a column in an excel sheet. Labels
need not be unique but must be a hashable type. The object supports both
integer and label-based indexing and provides a host of methods for performing
operations involving the index.

Creating a Series

In the real world, a Pandas Series will be created by loading the datasets from
existing storage, storage can be SQL Database, CSV file, an Excel file. Pandas
Series can be created from the lists, dictionary, and from a scalar value etc.

EXAMPLE
import pandas as pd
import numpy as np
# Creating empty series
ser = pd.Series()
print(ser)
# simple array
data = np.array(['g', 'e', 'e', 'k', 's'])
ser = pd.Series(data)
print(ser)

Output:
Series([], dtype: float64)
0 g
1 e
2 e
3 k
4 s
dtype: object

DataFrame

Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous


tabular data structure with labeled axes (rows and columns). A Data frame is a
two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows
and columns. Pandas DataFrame consists of three principal components, the
data, rows, and columns.

Creating a DataFrame:

In the real world, a Pandas DataFrame will be created by loading the datasets
from existing storage, storage can be SQL Database, CSV file, an Excel file.
Pandas DataFrame can be created from the lists, dictionary, and from a list of
dictionaries, etc.

Example:

import pandas as pd
# Calling DataFrame constructor
df = pd.DataFrame()
print(df)
# list of strings
lst = ['Geeks', 'For', 'Geeks', 'is',
'portal', 'for', 'Geeks']
# Calling DataFrame constructor on list
df = pd.DataFrame(lst)
print(df)

Output:

Empty DataFrame
Columns: []
Index: []
0
0 Geeks
1 For
2 Geeks
3 is
4 portal
5 for
6 Geeks

Why Pandas is used for Data Science


Pandas are generally used for data science but have you wondered why? This is
because pandas are used in conjunction with other libraries that are used for
data science. It is built on the top of the NumPy library which means that a lot
of structures of NumPy are used or replicated in Pandas. The data produced by
Pandas are often used as input for plotting functions of Matplotlib, statistical
analysis in SciPy, machine learning algorithms in Scikit-learn.

Pandas program can be run from any text editor but it is recommended to use
Jupyter Notebook for this as Jupyter given the ability to execute code in a
particular cell rather than executing the entire file. Jupyter also provides an easy
way to visualize pandas data frames and plots.
Python | Introduction to Matplotlib
Matplotlib is an amazing visualization library in Python for 2D plots of arrays.
Matplotlib is a multi-platform data visualization library built on NumPy arrays
and designed to work with the broader SciPy stack. It was introduced by John
Hunter in the year 2002.
One of the greatest benefits of visualization is that it allows us visual access to
huge amounts of data in easily digestible visuals. Matplotlib consists of several
plots like line, bar, scatter, histogram etc.
Installation :
Windows, Linux and macOS distributions have matplotlib and most of its
dependencies as wheel packages. Run the following command to install
matplotlib package :
python -mpip install -U matplotlib
Importing matplotlib :
from matplotlib import pyplot as plt
or
import matplotlib.pyplot as plt

Basic plots in Matplotlib :


Matplotlib comes with a wide variety of plots. Plots helps to understand trends,
patterns, and to make correlations. They’re typically instruments for reasoning
about quantitative information.

Line plot :
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot
plt.plot(x,y)
# function to show the plot
plt.show()
Output :

Bar plot
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot the bar
plt.bar(x,y)
# function to show the plot
plt.show()
output:
Histogram :
# importing matplotlib module
from matplotlib import pyplot as plt
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot histogram
plt.hist(y)
# Function to show the plot
plt.show()

Scatter Plot :
# importing matplotlib module
from matplotlib import pyplot as plt
# x-axis values
x = [5, 2, 9, 4, 7]
# Y-axis values
y = [10, 5, 8, 4, 2]
# Function to plot scatter
plt.scatter(x, y)
# function to show the plot
plt.show()
PYTHON PROGRAMMING
By
Dr. R. VASANTHSELVAKUMAR
Assistant Professor
Dept. of Computer Science and Engineering
Viswam Engineering College
Madanapalle
INTRODUCTION TO PYTHON
Python is a high level, multipurpose, interpreted, interactive and object-oriented programming
language. Python is easy to learn and versatile scripting language Python is a programming
language which supports structured and functional methods and that have built in data structure,
Portable, Extensible. Also, it is an extensible language.

Interpreted means it is processed at runtime by using interpreter. There is no need to compile


program before execution. It is used to give the capability to interact to databases, to build the
applications which can be run in a Windows environment, to build the CGI scripts which can be
run from a Web browser etc. It is used in everywhere from business Web sites to online games,
from simple conversion scripts to complex Internet update routines for banks and other financial
institutions.

Python is a programming language that can be applied in many different platforms. It comes with
standard library that includes almost for all Internet protocols, OS interfaces, testing and string
processing.

✓ String Processing - Regular Expressions, Calculate differences between files, Unicode.


✓ Internet Protocols - HTTP, SMTP, FTP, XML-RPC, IMAP, POP, CGI programming
✓ Software Engineering - Unit Testing, Logging, Profiling and Parsing Python code
✓ Operating System Interfaces - System Calls, File Systems and TCP/IP Sockets

FEATURES OF PYTHON
Python has following Features –

✓ Object-Oriented
✓ Free
✓ Portable
✓ Powerful
✓ Scalable
✓ Mixable
✓ Easy to Use
✓ Easy to Learn-
✓ Stable
✓ GUI Programming

HISTORY OF PYTHON
Python was created in early 1980s by Guido van Rossum as a successor of a language called ABC.
Currently it is managed by the Python Software Foundation (PSF). It is an independent and non-
profit organization which manages the open source licensing for python 2.1 and newer version of
python. Python is influenced by programming languages like: ABC, modulo – 3, C, C++ etc.

DATA TYPES

Python data types are categorized into two as follows:


Mutable Data Types: Data types in python where the value assigned to a variable can be changed
Immutable Data Types: Data types in python where the value assigned to a variable cannot be
changed

Fig. 1 Python data types


Let’s discuss on the above-mentioned standard data types in Python.

✓ Numbers: The number data type in Python is used to store numerical values. It is used to
carry out the normal mathematical operations.

✓ Strings: Strings in Python are used to store textual information. They are used to carry out
operations that perform positional ordering among items.

✓ Lists: The list data type is the most generic Python data type. Lists can consist of a
collection of mixed data types, stored by relative positions.

✓ Tuples: Tuples are one among the immutable Python data types that can store values of
mixed data types. They are basically a list that cannot be changed.

✓ Sets: Sets in Python are a data type that can be considered as an unordered collection of
data without any duplicate items.

✓ Dictionaries: Dictionaries in Python can store multiple objects, but unlike lists, in
dictionaries, the objects are stored by keys and not by positions.

Getting the Data Type

Print the data type of the variable x:

1. Number
>> x = 5
>> print(type(x))

Output: <class 'int'>

2. Strings
>> x = "Hello World"
>> print(x)
>> print(type(x))

Output: Hello World


<class 'str'>
3. Float
>> x = 20.5
>> print(x)
>> print(type(x))

Output: 20.5
<class 'float'>

4. Complex
>> x = 1jssss
>> print(x)
>> print(type(x))

Output: lj
<class 'complex'>

5. List
>> x = ["apple", "banana", "cherry"]
>> print(x)
>> print(type(x))

Output: ['apple', 'banana', 'cherry']


<class 'list'>

6. Tuples
>> x = ("apple", "banana", "cherry")
>> print(x)
>> print(type(x))

Output:('apple', 'banana', 'cherry')


<class 'tuple'>

7. Range
>> x = range(6)
>> print(x)
>> print(type(x))
Output: range(0, 6)
<class 'range'>

8. Dict
>> x = {“name”: “John”, “age”:36}
>> print(x)

>>print(type(x))

Output: {'name': 'John', 'age': 36}


<class 'dict'>
9. Set
>> x = {"apple", "banana", "cherry"}
>> print(x)
>> print(type(x))
Output: {'banana', 'apple', 'cherry'}
<class 'set'>
10. frozenset
>> x = frozenset({"apple", "banana", "cherry"})
>> print(x)
>> print(type(x))

Output: frozenset({'cherry', 'banana', 'apple'})


<class 'frozenset'>
11. bool

>> x = True
>> print(x)
>> print(type(x))

Output: True
<class 'bool'>
12. Bytes
>> x = b"Hello"
>> print(x)
>> print(type(x))

Output: b'Hello'
<class 'bytes'>
13. Bytearray
>> x = bytearray(5)
>> print(x)
>> print(type(x))

Output: bytearray(b'\x00\x00\x00\x00\x00')
<class 'bytearray'>

14. Memoryview
>> x = memoryview(bytes(5))
>> print(x)
>> print(type(x))

Output: <memory at 0x00B08FA0>


<class 'memoryview'>
OPERATORS IN PYTHON

In Python, we have a set of special symbols that perform various kinds of operations such
as logical operations, mathematical operations, and more. These symbols are called Python
operators. For every symbol or operator, there is a unique kind of operation. The values on
which the operators perform their respective operations are known as operands.

Types of Operators in Python

Depending on the type of operations that the operators perform, they are categorized into
the following categories:

1. Arithmetic Operators in Python


2. Relational Operators in Python
3. Assignment Operators in Python
4. Logical Operators in Python
5. Membership Operators in Python
6. Identity Operators in Python
7. Bitwise Operators in Python

Arithmetic Operators in Python

Arithmetic Operator
Description Example
Operator Name
I=40, J=20
+ Addition Performs addition >>>I+ J
>>>60
I=40, J=20
– Subtraction Performs subtraction >>>I – J
>>>20
I=40, J=20
* Multiplication Performs multiplication >>>I * J
>>> 800
I=30, J=20
/ Division Performs division >>>I /J
>>> 2.5
I=40, J=20
% Modulus Returns the remainder after the division >>>I /J
>>> 0
I=4, J=20
** Exponent Performs exponential (power) calculation >>>I /J
>>> 204
I=30, J=20
Performs division, removes the decimal
// Floor Division >>>I//J
value, and returns the quotient value
>>> 1

Relational Operators in Python


They are also known as comparison operators because they compare the values on both sides of
the operator and conclude on the relation between the values. After comparison, it returns the
Boolean value, i.e., either true or false

Operator
Operator Description Example
Name
If values of two operands are equal, then it returns I = 20, J = 20
== Equal to
true. (I == J) is True
I = 20, J = 20
If values of two operands are not equal, then it
!= Not Equal to (I == J)
returns true.
is False
If the value of the left operand is less than the value I = 40, J = 20
< Less than
of the right operand, then it returns true. (I < J) is False
If the value of the left operand is greater than the I= 40, J = 20
> Greater than
value of the right operand, then it returns true. (I > J) is True
I = 40, J = 20
Less than or If the value of the left operand is less than or equal to
<= (I <= J)
equal to the value of the right operand, then it returns true.
is False
If the value of the left operand is greater than or
Greater than or I = 40, J = 20
>= equal to the value of the right operand, then it returns
equal to (I >= J) is True
true.
I=40, J = 20
Not equal to If values of two operands are not equal, then the
<> (I <> J)
(similar to !=) condition becomes true.
is True.

Assignment Operators in Python


Assignment operators are used to assign values to Python Variables. Assignment is sometimes
done directly, and sometimes the operator first performs some kind of mathematical operation and
then assigns the value to the operand.
Operator Operator Name Description Example
It assigns a value from the right-side operand to I = 40
= Assignment
the left-side operand. It assigns 40 to I
It performs addition, and then the result is I+=J
+= Add then assign
assigned to the left-hand operand. that means I = I + J
Subtract then It performs subtraction, and then the result is I-=J
-=
assign assigned to the left-hand operand. that means I = I – J
Multiply the It performs multiplication, and then the result is I*=J
*=
assign assigned to the left-hand operand. that means I = I * J
It performs division, and then the result is I/=J
/= Divide then assign
assigned to the left-hand operand. that means I = I / J
Modulus then It performs modulus, and then the result is I%=J
%=
assign assigned to the left-hand operand. that means I = I % J
Exponent then It performs exponent, and then the result is I**=J
**=
assign assigned to the left-hand operand. that means I = I ** J
Floor division It performs floor division, and then the result is I//=J
//=
then assign assigned to the left-hand operand. that means I = I // J

Logical Operators in Python


Logical operators are mainly used for conditional statements. There are three types of logical
operators, namely, AND, OR, and NOT.

Operator
Operator Description Example
Name

When both sides’ conditions are true, the result is true; 2<1 and 2<3
and Logical AND
otherwise false. False

When at least one condition is true, then result is true; 2<1 or 2<3
or Logical OR
otherwise false. True

Not (5>4)
not Logical NOT Reverse the condition
False
Membership Operators in Python
Membership operators are used to test if a value is available in a sequence or not. It can be any
sequence such as (Python String, Python List, Python Set, Python Tuple, and Python Dictionary).
There are two types of membership operators, namely, in and not in.
Operator Description Example
List = [1,2,3,4,5,6,7,8]
i=1
if i in List:
It returns true if it finds a variable in the
in print(‘i is available in list’)
sequence; otherwise false.
else:
print(‘i is not available in list’)
Output – i is available in list
List = [1,2,3,4,5,6,7,8]
j=10
if j not in List:
It returns true if it does not find a variable in
not in print (‘j is not available in list’)
the sequence; otherwise false.
else:
print (‘j is available in list’)
Output – j is not available in list

Bitwise Operator in Python


It performs bit-by-bit operations.
For instance, suppose there are two variables,
I = 10 and J = 20
And their binary values are:
I = 10 = 0000 1010
J = 20 = 0001 0100
Now, let us see how bitwise operator in Python works.
Operator
Operator Description Example
Name
I&J
& Binary AND If both bits are 1, then 1; otherwise 0.
0000 0000
I|J
| Binary OR If one of the bits is 1, then 1; otherwise 0.
0001 1110
I^J
^ Binary XOR If both bits are the same, then 0; otherwise 1
0001 1110
Binary If the bit is 1 then makes it 0, and if the bit is 0 the ~I
~
Complement makes it 1 1111 0101
Binary Left The left operand is moved left by the number of bits I << 2
<<
Shift specified by the right operand. 240 i.e. 1111 0000

Binary Right The left operand is moved right by the number of I >> 2
>>
Shift bits specified by the right operand. 15 i.e. 1111

Identity Operators in Python

Identity operators are used to compare the memory addresses of two different objects. The two
types of identity operators in Python are is and is not. Following table contains the description of
these two operators, along with their respective examples.

Operator Description Example

I = 20
J = 20
if (I is J):
It returns true if both operands’ identities
is print (‘I and J have same identity’)
are the same; otherwise, false.
else:
print (‘I and J have not same identity’)
Output – I and J have same identity

I = 20
J = 230
if (I is not J):
It returns true if both operands’ identities
is not print (‘I and J have not same identity’)
are not the same; otherwise, false.
else:
print (‘I and J have same identity’)
Output – I and J have not same identity
PYTHON INPUT AND OUTPUT
User Input
The input Function
The input () function is used to get data from the user in Python Command Line programs.

Syntax

<return> = input( "<prompt>")


Program
>> i = "Hello SVTM"
>> x = input ("enter a value:")
enter a value: i
>> print i
Output
Hello SVTM

raw_input() function
raw_input() function is used to take input from the user. It takes the input from the Standard input
in the form of a string and reads the data from a line at once.
Syntax

raw_input(?statement?)
Program
>> i=raw_input ("Enter value ");
>> print i
Output:
Enter value
Hello SVTM
raw_input() does not deal with numbers, at least not directly.

Program
>> x = raw_input ("Enter your marks: ")
>> Enter your marks: 20
>> print x
Then it shows error because numbers are not handled by raw_input () directly. To use numbers
conversion is used.
Program
>> x = int (raw_input ("Enter your marks: "))
>> Enter your marks: 20
>> print x
Then it displays 20.

User Output
Print statement is used to get the output.
Syntax
print expression
program
>> x=20
>> print x
Output
20
FILE HANDLING
File is an external storage on hard disk from where data can be stored and retrieved. Python
supports reading data form files and writing data to the files.

Operations on Files:
Opening a file
To open file built in function open () is used. It returns an object of File which is used with other
functions.
Syntax:

obj=open (file_name, access_mode, buffer)

file_name specify that file which you want to open.


access_mode specify the access_mode in which the file has to be open, i.e., read, write, append,
etc.
buffer – It represents that buffering is performed or not, if buffer value is 0 then no buffering is
performed and when buffer value is 1 then line buffering is performed while accessing the file.

Access Modes

Modes Description

r Opens a file for reading


rb Opens a file for reading only in binary format.
w Opens a file for writing only. Overwrites the file if the file exists.

wb Opens a file for writing only in binary format.

Opens a file for appending. It does not overwrite the file just add the data in the
a
file and if file is not created then it creates new file

ab Opens a file for appending in binary format.


Closing a File:
It is used to close a file. For this purpose close() function is used.
Syntax:

File_object.close()
Writing to a File:
write() method is used to write a string into the file.
Syntax:
>> File_object.write(string str)
>> i=open("viswam.txt","w")
>> i.write("Hello Viswam")
>> i.close()

Reading from a File:


read () method is used to read data from the File.
Syntax:
File_object.read(data)

Program
>> j=open("SVTM.txt","r")
>> k=j.read()
>> print k
>> j.close()

Output
Hello SVTM
Methods in File Handling
There are different methods are used which are as follows:
rename (): This is used to rename a file.
Syntax:

os.rename(existing file_name, new file_name)

Example
import os
os.rename("abc.txt","xyz.txt")

remove(): This method is used to delete a file.


Syntax:

os.remove(file_name)

Example
import os
os.remove("abc.txt")

chdir(): This method is used to change the current directory.


Syntax:

os.chdir("new directory")

Example
import os
os.chdir("new directory path")

mkdir() : This method is used to create a directory.


Syntax:
Example
import os
os.mkdir("abc")
rmdir() : This method is used to remove the directory.
Syntax

os.rmdir("directory name")

Example
>> import os
>> os.rmdir("abc") // where abc is a directory name which you want to remove

getcwd() This method is used to show the current working directory.


Syntax

os.getcwd()

Example
>> import os
>> print os.getcwd()
PYTHON CONTROL STATEMENTS
Control flow statements in Python
A program’s control flow is the order in which the program’s code executes. The control flow of
a Python program is regulated by conditional statements, loops, and function calls.

Python has three types of control structures:

1. Sequential - default mode


2. Selection - used for decisions and branching
3. Repetition - used for looping, i.e., repeating a piece of code multiple times.

Sequential statements
Sequential statements are a set of statements whose execution process happens in a sequence.
The problem with sequential statements is that if the logic has broken in any one of the lines,
then the complete source code execution will break.
Example
>> a=20
>> b=10
>> c=a-b
>> print("Subtraction is : ",c)

Selection/Decision control statements


In Python, the selection statements are also known as Decision control statements or branching
statements. The selection statement allows a program to test several conditions and execute
instructions based on which condition is true.
Some Decision Control Statements are:

1. Simple if
2. if-else
3. nested if
4. if-elif-else
Simple if: If statements are control flow statements that help us to run a particular code, but only
when a certain condition is met or satisfied. A simple if only has one condition to check.

Example
>> n = 10
>> if n % 2 == 0:
>> print("n is an even number")

Output
n is an even number

if-else: The if-else statement evaluates the condition and will execute the body of if if the test
condition is True, but if the condition is False, then the body of else is executed.
Example
>> n = 5
>> if n % 2 == 0:
>> print("n is even")
>> else:
>> print("n is odd")
Output
n is odd

nested if: Nested if statements are an if statement inside another if statement.

Example
>> a = 5
>> b = 10
>> c = 15
>> if a > b:
>> if a > c:
>> print("a value is big")
>> else:
>> print("c value is big")
>> elif b > c:
>> print("b value is big")
>> else:
>> print("c is big")
Output
c is big

if-elif-else: The if-elif-else statement is used to conditionally execute a statement or a block of


statements.

Example
x = 15
y = 12
if x == y:
print("Both are Equal")
elif x > y:
print("x is greater than y")
else:
print("x is smaller than y")
Output:
x is greater than y

Repetition
A repetition statement is used to repeat a group(block) of programming instructions.
In Python, we generally have two loops/repetitive statements:
1) for loop
2) while loop
for loop: A for loop is used to iterate over a sequence that is either a list, tuple, dictionary, or a
set. We can execute a set of statements once for each item in a list, tuple, or dictionary.

Example
lst = [1, 2, 3, 4, 5]
for i in range(len(lst)):
print(lst[i], end = " ")

for j in range(0,10):
print(j, end = " ")
Output
123450123456789
while loop: In Python, while loops are used to execute a block of statements repeatedly until a
given condition is satisfied. Then, the expression is checked again and, if it is still true, the body
is executed again. This continues until the expression becomes false.

Example
m=5
i=0
while i < m:
print(i, end = " ")
i=i+1
print("End")
Output
0 1 2 3 4 End
Control statements in python
Control statements in python are used to control the flow of execution of the program based on the
specified conditions.Python supports 3 types of control statements such as,
1) Break
2) Continue
3) Pass

Break in Python
The break statement in Python is used to terminate a loop. This means whenever the interpreter
encounters the break keyword, it simply exits out of the loop. Once it breaks out of the loop, the
control shifts to the immediate next statement. Also, if the break statement is used inside a nested
loop, it terminates the innermost loop and the control shifts to the next statement in the outer loop.

Flowchart of Break Statement in Python


Example of Break Statement in Python
# program to check if letter 'A' is present in the input
a = input ("Enter a word")
for i in a:
if (i == 'A'):
print ("A is found")
breakelse:
print ("A not found")
Input: FACE Prep
Output:
A not found
A is found
Continue in Python
Whenever the interpreter encounters a continue statement in Python, it will skip the execution of
the rest of the statements in that loop and proceed with the next iteration. This means it returns the
control to the beginning of the loop. Unlike the break statement, continue statement does not
terminate or exit out of the loop. Rather, it continues with the next iteration. Here is the flow of
execution when continue statement is used.

Flowchart of Continue Statement in Python


Example of Continue Statement in Python
# Program to check if letter 'A' is present in the input
a = input ("Enter a word")
for i in a:
if (i != 'A'):
continueelse:
print ("A is found")

Input: FACE Prep


Output:
A is found

Pass in Python
Assume we have a loop that is not implemented yet, but needs to implemented in the future. In
this case, if you leave the loop empty, the interpreter will throw an error. To avoid this, you can
use the pass statement to construct a block that does nothing i.e contains no statements. For
example,
Example of pass statement in python
for i in 'FACE':
if (i == 'A'):
pass
print (i)

Output:
F
A
C
E
PYTHON STRING AND STRING FUNCTION IN PYTHON
Python string is an ordered collection of characters which is used to represent and store the text-
based information. Strings are stored as individual characters in a contiguous memory location. It
can be accessed from both directions: forward and backward. Characters are nothing but symbols.
Strings are immutable Data Types in Python, which means that once a string is created, they cannot
be changed.
Following is the list of all topics that are covered in this module.
1. Creating a String in python
2. Accessing Python String Characters
3. Updating or Deleting a String in Python
4. Python String Operators
5. Built-in Python String Methods and Python String Functions

Creating a String in Python


In Python, strings are created using either single quotes or double quotes. We can also use triple
quotes, but usually triple quotes are used to create docstrings or multi-line strings.
Program to create a string with single quotes
String1 = ‘Viswam’
print (String1)#creating a string with double quotes
String2 = “Python tutorial”
Print (Strings2)
Output:
Viswam
Python Tutorial

Accessing Python String Characters


In Python, the characters of string can be individually accessed using a method called indexing.
Characters can be accessed from both directions: forward and backward. Forward indexing starts
form 0, 1, 2…. Whereas, backward indexing starts form −1, −2, −3…, where −1 is the last element
in a string, −2 is the second last, and so on. We can only use the integer number type for indexing;
otherwise, the TypeError will be raised.
Example:
String1 = ‘viswam’
print (String1)
print (String1[0])
print (String1[1])
print (String1[-1])
Output:
Viswam
i
n
t
Updating or Deleting a String in Python
As discussed above, strings in Python are immutable and thus updating or deleting an individual
character in a string is not allowed, which means that changing a particular character in a string is
not supported in Python. Although, the whole string can be updated and deleted. The whole string
is deleted using a built-in ‘del’ keyword.
Example:
Python code to update an entire string
String1 = ‘Viswam Python Tutorial’
print (“original string: “)
print (String1)String1 = ‘Welcome to Viswam’
print (“Updated String: “)
print (String1)
Output:
Original String:
Viswam Python Tutorial
Updated String:
Welcome to Viswam
Example: Python code to update an entire string
String1 = ‘Viswam Python tutorial’
print (String1)
del String1
print (String1)
Output:
Viswam Python tutorial
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘String1’ is not defined

Python Operators for Strings


There are three types of operators supported by a string, which are:
➢ Basic Operators (+, *)
➢ Relational Operators (<, ><=, >=, ==, !=)
➢ Membership Operators (in, not in)
Table: Common String Constants and Operations
Operators Description
s1 = ‘ ’ Empty string
s2 = “a string” Double quotes
block = ‘‘‘…’’’ Triple-quoted blocks
s1 + s2 Concatenate
s2 * 3 Repeat
s2[i] i=Index
s2[i:j] Slice
len(s2) Length
“a %s parrot” % ‘dead’ String formatting in Python
for x in s2 Iteration
‘m’ in s2 Membership
Table: String Backslash Characters
Operators Description
\newline Ignored (a continuation)
\n Newline (ASCII line feed)
\\ Backslash (keeps one \)
\v Vertical tab
\’ Single quote (keeps ‘)
\t Horizontal tab
\” Double quote (keeps “)
\r Carriage return
\a ASCII bell
\f Form feed
\b Backspace
\0XX Octal value XX
\e Escape (usually)
\xXX Hex value XX
\000 Null (doesn’t end string)

Built-in Python String Methods and Python String Functions


String Method/String
Description of String Method/String Function in Python
Function in Python
capitalize() It capitalizes the first letter of a string.
center(width, fillchar) It returns a space-padded string with the original string centered to.
It counts how many times ‘str’ occurs in a string or in the substring
count(str, beg=
of a string if the starting index ‘beg’ and the ending index ‘end’ are
0,end=len(string))
given.
It returns an encoded string version of a string; on error, the default
encode(encoding=’UTF-
is to raise a ValueError unless errors are given with ‘ignore’ or
8′,errors=’strict’)
‘replace’.
It determines if a string or the substring of a string (if the starting
endswith(suffix, beg=0,
index ‘beg’ and the ending index ‘end’ are given) ends with a suffix;
end=len(string))
it returns true if so, and false otherwise.
It expands tabs in a string to multiple spaces; defaults to 8 spaces per
expandtabs(tabsize=8)
tab if the tab size is not provided.
It determines if ‘str’ occurs in a string or in the substring of a string
find(str, beg=0
if starting index ‘beg’ and ending index ‘end’ are given and returns
end=len(string))
the index if found, and −1 otherwise.
index(str, beg=0,
It works just like find() but raises an exception if ‘str’ not found.
end=len(string))
It returns true if a string has at least one character and all characters
isalnum()
are alphanumeric, and false otherwise.
It returns true if a string has at least one character and all characters
isalpha()
are alphabetic, and false otherwise.
isdigit() It returns true if a string contains only digits, and false otherwise.
It returns true if a string has at least one cased character and all other
islower()
characters are in lowercase, and false otherwise.
It returns true if a string has at least one cased character, and all
isupper()
other characters are in uppercase, and false otherwise.
len(string) It returns the length of a string.
max(str) It returns the max alphabetical character from the string str.
min(str) It returns the min alphabetical character from the string str.
upper() It converts lowercase letters in a string to uppercase.
rstrip() It removes all trailing whitespace of a string.
It is used to split strings in Python according to the delimiter str
split(str=””,
(space if not provided any) and returns the list of substrings in
num=string.count(str))
Python
splitlines( It splits a string at the newlines and returns a list of each line with
num=string.count(‘\n’)) newlines removed.

List in Python
Lists are Python’s most flexible ordered collection object type. It can also be referred to as a
sequence that is an ordered collection of objects that can host objects of any data type, such as
Python Numbers, Python Strings and nested lists as well. Lists are one of the most used and
versatile Python Data Types. In this module, we will learn all about lists in order to get started
with them.
Following is the list of all topics that are going to be covered in this module.
➢ Creating_Lists_in_Python
➢ Creating Multi-dimensional Lists in Python
➢ Python List Comprehension
➢ Python Lists Extension
➢ Accessing Lists in Python
Common_List_Operations_in_Python
✓ Slicing Python Lists
✓ Iterating through Python Lists
✓ Update or Add Elements in a Python List
✓ Remove elements from list in python
✓ Remove duplicates from lists in python
✓ Sorting Lists in Python
✓ Reverse a list in python
Python List Functions and Methods
Creating a Lists in python
A list can be created by putting the value inside the square bracket, and values are separated by
commas.
List_name = [value1, value2, …, value n]
Unlike strings, lists can contain any sort of objects: numbers, strings, and even other lists.
Python lists are:
• Ordered collections of arbitrary objects
• Accessed by offset
• Arrays of object references
• Of variable length, heterogeneous, and arbitrarily nestable
• Of the category, mutable sequence
• Data types in which elements are stored in the index basis with starting index as 0
• Enclosed between square brackets ‘[]’

Example:
list1 = [1,2,3,4,5]
list2 = [“hello”, “viswam”]

Creating Multi-dimensional Lists in Python


A list can hold other lists as well which can result in multi-dimensional lists. Next, we will see
how to create multi-dimensional lists, one by one.

One-dimensional Lists in Python:


init_list = [0]*3
print(init_list)
Output:
[0, 0, 0]

Two-dimensional Lists In Python:


two_dim_list = [ [0]*3 ] *3
print(two_dim_list)
Output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Three-dimensional Lists in Python:


two_dim_list = [[ [0]*3 ] *3]*3
print(two_dim_list)
Output:
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]],
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]]

Python List Comprehension


Python List comprehension helps in constructing lists in a completely natural and easy way.
List = [1,2,3,4,5]
List1 = [ i for i in range(5)]
print(List1)
Output:
[0, 1, 2, 3, 4]

Complicated Python List Comprehension Examples


Example 1:
print ([a+b for a in ‘mug’ for b in ‘lid’])
Output:
[‘ml’, ‘mi’, ‘md’, ‘ul’, ‘ui’, ‘ud’, ‘gl’, ‘gi’, ‘gd’]

Example 2:
list_fruit = [“Apple”,”Mango”,”Banana”,”Avocado”]
first_letters = [ fruits[0] for fruits in list_fruit ]
print(first_letters)
Output:
[‘A’, ‘M’, ‘B’, ‘A’]

List Extension
Python allows lists to resize in many ways. We can do that just by adding two or more of them.
Example:
two_dim = [[0]*3 for i in range(3)]print(two_dim)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
two_dim[0][2] = 1
print(two_dim)
Output:
[[0, 0, 1], [0, 0, 0], [0, 0, 0]]

extend():
Alternately, we can do extension by using the extend() method. See the following example:
L1 = [‘a’, ‘b’]
L2 = [‘c’, ‘d’]
L1.extend(L2)
print(L1)
Output:
[‘a’, ‘b’, ‘c’, ‘d’]

append():
Next, we can append a value to a list by calling the append() method. See the following
Example:
L1 = [‘a’, ‘b’]
L2 = [‘c’, ‘d’]
L1.extend(L2)
print(L1)
Output:
[‘a’, ‘b’, ‘c’, ‘d’]

Accessing Lists in Python


Much similar to strings, we can use the index number to access items in lists as shown below.
Example:
list1 = [1,2,3,4,5]

Accessing a List Using Reverse Indexing


To access a list in reverse order, we have to use indexing from −1, −2…. Here, −1 represents the
last item in the list.

print(list1[-1])
print(list1[-3])
Output:
5
3

Common List Operations in Python


Following is the list of some of the most common list operations in Python, along with their
descriptions and examples.

Slicing Python Lists


Slicing operation is used to print a list up to a specific range. We can use slice operation by
including the starting index and ending index of the range that we want to print separated by a
colon as shown below:
list1[2:4]
output:
[3, 4]

list1[2:-1]
output:
[3, 4]
list1[:2]
output:
[1, 2]

Iterating through Python Lists


Iterating is quite simple in lists. We can just use Python for loop to iterate, as shown below:
list1 = [1,2,3,4,5]
for element in list1:
print(element)
Output:
1
2
3
4
5
Update or Add Elements in a Python List
We can update a particular item or multiple items of a list by using the slice operation, and then
add an element using the append () method as shown below.
Example:
list1[4] = ‘number’print(list1)list1[4:7] = [“Apple”,”Mango”,”Banana”]
print(list1)list1.insert(0,33)
print(list1)list1.insert(6,29)
print(list1)
Output:
[1, 2, 3, 4, ‘number’]
[1, 2, 3, 4, ‘Apple’, ‘Mango’, ‘Banana’]
[33, 1, 2, 3, 4, ‘Apple’, ‘Mango’, ‘Banana’]
[33, 1, 2, 3, 4, ‘Apple’, 29, ‘Mango’, ‘Banana’]

Remove elements from list in python


There are three ways of removing elements from lists. We can either use the del keyword to remove
a particular element or we can use the remove () method, and the last way is using the pop ()
method, as shown in the following code block:
list1 = [1,2,3,4,5]
del list1[2]
list2 = [1,2,3,4,5]
list2.remove(4)
print(list2)
list3 = [1,2,3,4,5]
print(list3.pop(1))
print(list3)

Output:
[1, 2, 4, 5][1, 2, 3, 5]
2
[1, 3, 4, 5]
Remove duplicates from lists in python
Here’s an example of list where some items are repeating. Let us see how we can remove duplicates
from list in python.

mylist = ["a", "b", "c", "d", "c"]


mylist = list(dict.fromkeys(mylist))
output:
[“a”, “b”,”c”,”d”]
Reverse a list in python
lst = [10, 11, 12, 13, 14, 15]
lst.reverse()
print(lst)
output:
[15, 14, 13, 12, 11, 10]

Sorting Lists in Python


Python list implements the sort() method for ordering (in both ascending and descending order) its
elements in place.
list1.sort()

Sorting in ascending order:


list1 = [1,3,2,4,5,9,6]
list1.sort()
print(list1)
output:
[1, 2, 3, 4, 5, 6, 9]

Sorting in descending order:


list1 = [1,3,2,4,5,9,6]
list1.sort(reverse=True)
print(list1)
output:
[9, 6, 5, 4, 3, 2, 1]
Python List Functions and Methods
Method Description
min(list_name) Returns the minimum value from a list in Python
max(list_name) Returns the largest value from a list in Python
len(list_name) Returns the number of elements in a list in Python
cmp(list1,list2) Compares two lists in Python
list.reverse() Reverses a list in Python
list.sort Sorts a list in Python
list(sequence) Converts the sequence of a list in Python
list.append(value) Adds a value into a list in Python

Dictionary in Python
Python dictionary is yet another unordered collection of elements. The difference between Python
dictionary and other unordered Python data types such as sets lies in the fact that unlike sets, a
dictionary contains keys and values rather than just elements.

Like lists, Python dictionaries can also be changed and modified, but unlike Python lists the values
in dictionaries are accessed using keys and not by their positions. All the keys in a dictionary are
mapped to their respective values. The value can be of any data type in Python.

Following is the list of topics that we will be covering in this module.


✓ Create a Dictionary in Python
✓ Access Items in Dictionary in Python
✓ Operations in Dictionary in Python
✓ Loop Through a Dictionary in Python
✓ Add Items to a Dictionary in Python
✓ Remove Items from a Dictionary and Delete the Whole Dictionary in Pyhton
✓ Python Dictionary Length
✓ Checking All Keys in a Dictionary in Python
✓ Common Python Dictionary Methods

Create a Dictionary in Python


While creating a dictionary in Python, there are some rules that we need to keep in mind as
follows:

i. The keys are separated from their respective values by a colon (:) between them, and each
key–value pair is separated using commas (,).
ii. All items are enclosed in curly braces.
iii. While the values in dictionaries may repeat, the keys are always unique.
iv. The value can be of any data type, but the keys should be of immutable data type, that is,
(Python Strings, Python Numbers, Python Tuples).

Here is a few Python dictionary examples:


dict1 ={“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921}
print (dict1)
Output:
{‘Brand’: ‘gucci’, ‘Industry’: ‘fashion’, ‘year’: 1921}

We can also declare an empty dictionary as shown below:


dict2 = {}

We can also create a dictionary by using an in-built method dict () as shown in the following
example:
dict3 = dict([(1, ‘Viswam’), (2,’Python’)])

Access Items in Dictionary in Python


As discussed above, to access elements in a dictionary, we have to use keys instead of indexes.
Now, there are two different ways of using keys to access elements as shown below:

Using the key inside square brackets like we used to use the index inside square brackets.
Example:
dict1 = {“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921}
print(dict1[‘year’])
Output:
1921

Using the get() method and passing the key as a parameter inside this method.
Example:
dict1 = {“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921}
print (dict1.get(‘year’))

Output:
1921

Operations in Dictionary in Python


There are various operations in a dictionary, and in this section we will learn about some of the
most basic and most frequently used operations such as iterating through a dictionary, adding new
elements, updating already existing elements, removing some specific elements, along with
deleting the whole dictionary at once, and many more.
Loop Through a Dictionary in Python
To iterate through a dictionary, we can use the Python for loop. Let’s say, we want to print all
elements in a dictionary, then we will use for loop as shown in the below example:
cubes = {1:1, 2:8, 3:21, 4:64, 5:125}
for i in cubes:
print(cubes[i])

Output:
1
8
21
64
125
Add Items to a Dictionary in Python
Python dictionary is a mutable data type that means that we can add new elements or change the
value of the existing elements in it. While adding or changing an existing value, we have to use
keys. If the key already exists, then the value gets updated; if the key does not exist, then a new
key–value pair is generated.
Example:
dict1 = {“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921}
print(dict1)
Program to create new key-value pair
dict1[‘product’] = “Tote Handbag”
print(dict1)
#updating existing value
dict1[‘Industry’] = “Fashion and Luxury”
print(dict2)
Output:
{‘Brand’: ‘gucci’, ‘Industry’: ‘fashion’, ‘year’: 1921}
{‘Brand’: ‘gucci’, ‘Industry’: ‘fashion’, ‘year’: 1921, ‘product’: ‘Tote Handbag’}
{‘Brand’: ‘gucci’, ‘Industry’: ‘Fashion and Luxury’, ‘year’: 1921, ‘product’: ‘Tote Handbag’}

Remove Items from a Dictionary and Delete the Whole Dictionary in Python
There are various ways in which we can remove elements from a dictionary such as using the pop()
method, the popitem() method, or using the del keyword. Let’s understand all of these individually
with the help of examples.

Remove elements using the pop() method:


We use the pop() Python Function to remove a particular element from a dictionary by providing
the key of the element as a parameter to the method as shown in the example below:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}


print(cubes.pop(4))
print(cubes)
Output:
64
{1: 1, 2: 8, 3: 21, 5: 125}

Remove Elements Using the popitem() Method:


We can use the popitem() method to remove any randomly picked element as shown in the
example below.

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}


print(cubes.popitem())
print(cubes)

Output:
(5, 125)
{1: 1, 2: 8, 3: 21, 4: 64}

Remove Items Using the del Keyword in a Dictionary:


We use the del keyword to delete an item as shown in the following example:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}


del cubes[5]
print (cubes)

Output:
{1: 1, 2: 8, 3: 21, 4: 64}

Delete All Elements Using the Clear() Method:


We can use the clear() method, and it will clear out or delete all elements from a dictionary at
once as shown in the following example:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}


cubes.clear()
print(cubes)

Output:
{}

As discussed above, curly braces with nothing inside represents an empty dictionary. Since the
clear() method deletes all elements at once, the output of printing the dictionary after using the
clear() method on it is an empty dictionary, that is, {}.

Deleting the Whole Dictionary:


As we have already seen, we can use the del keyword to delete a particular item by passing the
key of that particular item, but that is not all we can do using the del keyword. We can also delete
a whole dictionary at once using the del keyword as shown in the example below:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}


cubes.del()
print(cubes)

Output:
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘cubes’ is not defined

Python Dictionary Length


To check the length of the dictionary, that is, to check how many key–value pairs are there in a
dictionary, we use the len() method as shown in the example below:

dict1 = {“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921}
print(len(dict1))

Output:
3
Checking All Keys in a Dictionary in Python
To find a particular key or to check if a particular key exists in a dictionary, we use the Python if
statement and the ‘in’ keyword as shown in the example below:

dict1 = {“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921}
if “industry” in dict1:
print (“Yes, ‘Industry’ is one of the Keyword in dictionary named dict1”)

Output:
Yes, ‘Industry’ is one of the Keyword in dictionary named dict1

Common Python Dictionary Methods

Method Description
clear() It removes all elements from a dictionary.
copy() It returns a copy of a dictionary.
fromkeys() It returns a dictionary with the specified keys and values.
get() It returns the value of a specified key.
items() It returns a list containing a tuple for each key–value pair.
keys() It returns a list containing the dictionary’s keys.
pop() It removes an element with a specified key.
popitem() It removes the last inserted (key, value) pair.
setdefault() It returns the value of a specified key.
update() It updates a dictionary with the specified key–value pairs.
values() It returns a list of all values in a dictionary.
Tuple in Python
Tuple data type in Python is a collection of various immutable Python objects separated by
commas. Tuples are much similar to Python Lists, but they are syntactically different, i.e., in lists
we use square brackets while in tuples we use parentheses. In this module, we will learn all about
the tuple data type in order to get started with it.

Following is the list of all topics that we will cover in this module.
✓ Advantages of Tuples in Python over Lists
✓ Creating a Tuple in Python
✓ Accessing Python Tuple Elements
✓ Indexing of Tuples in Python
✓ Reveres Indexing of Tuples in Python
✓ Slicing Operator of Tuples in Python
✓ Performing Operations in Tuples in Python
✓ Modifying Elements in a Python Tuple
✓ Deleting Python Tuple Elements

Advantages of Tuples in Python over Lists


The main difference between Python tuples and lists is that the elements of a tuple cannot be
changed once they are assigned; whereas, the elements of a list can be changed. As tuples and lists
are quite similar to each other, they are often used in similar kinds of situations. Although, a tuple
in Python has a bunch of advantages over lists. Following are some of the main advantages:

✓ Iteration in a tuple is faster as compared to lists since tuples in Python are immutable.
✓ Tuples are generally used for different Python Data Types; whereas, lists are used for
similar data types.
✓ Whenever, we need to make sure that the data remains unchanged and write protected,
Python tuple is the best option.

Creating a Tuple in Python


A Python tuple is created using parentheses around the elements in the tuple. Although using
parentheses is only optional, it is considered a good practice to use them. Elements in the tuple
can be of different data types or of the same data type. A tuple in Python can have any number
of elements.

Following is the code block that shows how to create a tuple:


tup1 = (‘Viswam’, ‘ Python’, ‘tutorial’)
tup2 = 1,2,3,4
Print (tup1)
print (tup2)

Output:
(‘Viswam’, ‘ Python’, ‘tutorial’)
(1,2,3,4)

Accessing Python Tuple Elements


We can use three different ways of accessing elements in a tuple, that is, Indexing, reverse
indexing, and using the slice operator.

Indexing of Tuples in Python


To access an element of a tuple, we simply use the index of that element. We use square
brackets around that index number as shown in the example below:

tup1 = (‘Viswam’, ‘Python’, ‘tutorial’)


print (tup1[0])
Output:
Viswam
Reverse Indexing of Tuples in Python
Much similar to regular indexing, here, we use the index inside the square brackets to access
the elements, with only one difference, that is, we use the index in a reverse manner. Meaning,
the indexing of the elements would start from the last element. Here, we use indexes as −1, −2,
−3, and so on, where −1 represents the last element.

Following code block is an example to access elements using reverse indexing.

tup1= (‘Viswam’, ‘Python’, ‘tutorial’)


print (tup1[-1])

Output:
Tutorial

Slicing Operator of Tuples in Python


Using the slicing operator to access elements is nothing new, as we have seen this in previous
modules as well. As the name suggests, we will slice, that is, extract some elements from the
tuple and display them. To do this, we use a colon between the index from where we want to
start slicing and the index till where we want to perform it.

Following code block is an example to show how to access elements using the slicing operator.
tup3 = (1,2,3,4,5,6)
tup3[1:]
tup3[2:4]

Output:
(2, 3, 4, 5, 6)
(3, 4)
Performing Operations in Tuples in Python
Following is the list of some of the most frequently used operations in a Python tuple along
with their descriptions and examples.

Deleting Python Tuple Elements


Since a tuple in Python is an immutable data type in Python, deleting particular elements in a
tuple is not possible. But, the whole tuple can be deleted using the del keyword as shown in
the following example:

tup1 = (‘Viswam’, ‘Python’, ‘tutorial’)


print (tup1)
del tup1
print (tup1)

Output:
(‘Viswam’, ‘Python’, ‘tutorial’)
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘tup1’ is not defined

Modifying Elements in a Python Tuple


Again, since tuple is immutable, it is impossible to change or modify the value of a particular
element. Although, we can take some portion of an existing tuple and create a new tuple using
the concatenating operator, as shown in the example below:

tup1 = (‘Viswam’, ‘Python’, ‘tutorial’)


tup2 = (1,2,3)
tup3 = tup1 + tup2
print (tup3)

Output:
(‘Viswam’, ‘Python’, ‘tutorial’,1,2,3)
Python – Functions
A function is a block of organized, reusable code that is used to perform a
single, related action. Functions provide better modularity for your application
and a high degree of code reusing.

As you already know, Python gives you many built-in functions like print(), etc.
but you can also create your own functions. These functions are called user-
defined functions.

Defining a Function

You can define functions to provide the required functionality. Here are simple
rules to define a function in Python.

• Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these
parentheses. You can also define parameters inside these parentheses.
• The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
• The code block within every function starts with a colon (:) and is
indented.
• The statement return [expression] exits a function, optionally passing
back an expression to the caller. A return statement with no arguments
is the same as return None.

Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]

By default, parameters have a positional behavior and you need to inform them
in the same order that they were defined.

Example

The following function takes a string as input parameter and prints it on


standard screen.
The following function takes a string as input parameter and prints it on
standard screen.

def printme( str ):


"This prints a passed string into this function"
print str
return

Calling a Function

Defining a function only gives it a name, specifies the parameters that are to be
included in the function and structures the blocks of code.

Once the basic structure of a function is finalized, you can execute it by calling
it from another function or directly from the Python prompt. Following is the
example to call printme() function −

#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")

When the above code is executed, it produces the following result –

I'm first call to user defined function!


Again second call to the same function

Pass by reference vs value

All parameters (arguments) in the Python language are passed by reference. It


means if you change what a parameter refers to within a function, the change
also reflects back in the calling function. For example –
#!/usr/bin/python

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending values
in the same object. So, this would produce the following result –

Values inside the function: [10, 20, 30, [1, 2, 3, 4]]

Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

There is one more example where argument is being passed by reference and
the reference is being overwritten inside the called function.

#!/usr/bin/python

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist within
the function does not affect mylist. The function accomplishes nothing and
finally this would produce the following result −

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]

Function Arguments

You can call a function by using the following types of formal arguments −

• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments

Required arguments

Required arguments are the arguments passed to a function in correct


positional order. Here, the number of arguments in the function call should
match exactly with the function definition.

To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows −

#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme()

When the above code is executed, it produces the following result –


Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

Keyword arguments

Keyword arguments are related to the function calls. When you use keyword
arguments in a function call, the caller identifies the arguments by the
parameter name.
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the values
with parameters. You can also make keyword calls to the printme() function in
the following ways −

#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme( str = "My string")

When the above code is executed, it produces the following result –

My string

The following example gives more clear picture. Note that the order of
parameters does not matter.

#!/usr/bin/python

# Function definition is here


def printinfo( name, age ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )

When the above code is executed, it produces the following result –

Name: miki
Age 50
Default arguments

A default argument is an argument that assumes a default value if a value is


not provided in the function call for that argument. The following example
gives an idea on default arguments, it prints default age if it is not passed −
Live Demo
#!/usr/bin/python

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

When the above code is executed, it produces the following result −


Name: miki
Age 50
Name: miki
Age 35

Variable-length arguments

You may need to process a function for more arguments than you specified
while defining the function. These arguments are called variable-
length arguments and are not named in the function definition, unlike
required and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all
nonkeyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call. Following is a simple
example −
Live Demo
#!/usr/bin/python

# Function definition is here


def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

When the above code is executed, it produces the following result −


Output is:
10
Output is:
70
60
50

The Anonymous Functions

These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. You can use the lambda keyword
to create small anonymous functions.
• Lambda forms can take any number of arguments but return just one
value in the form of an expression. They cannot contain commands or
multiple expressions.
• An anonymous function cannot be a direct call to print because lambda
requires an expression
• Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
• Although it appears that lambda's are a one-line version of a function,
they are not equivalent to inline statements in C or C++, whose purpose
is by passing function stack allocation during invocation for
performance reasons.

Syntax

The syntax of lambda functions contains only a single statement, which is as


follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
Live Demo
#!/usr/bin/python

# Function definition is here


sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function


print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

When the above code is executed, it produces the following result −


Value of total : 30
Value of total : 40

The return Statement

The statement return [expression] exits a function, optionally passing back an


expression to the caller. A return statement with no arguments is the same as
return None.
All the above examples are not returning any value. You can return a value
from a function as follows −
Live Demo
#!/usr/bin/python

# Function definition is here


def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;

# Now you can call sum function


total = sum( 10, 20 );
print "Outside the function : ", total

When the above code is executed, it produces the following result −


Inside the function : 30
Outside the function : 30

Scope of Variables
All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python

• Global variables
• Local variables

Global vs. Local variables

Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.
This means that local variables can be accessed only inside the function in
which they are declared, whereas global variables can be accessed throughout
the program body by all functions. When you call a function, the variables
declared inside it are brought into scope. Following is a simple example −
Live Demo
#!/usr/bin/python

total = 0; # This is global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total

When the above code is executed, it produces the following result −


Inside the function local total : 30
Outside the function global total : 0

First Class functions in Python


First class objects in a language are handled uniformly throughout. They may
be stored in data structures, passed as arguments, or used in control
structures. A programming language is said to support first-class functions if it
treats functions as first-class objects. Python supports the concept of First
Class functions.
Properties of first class functions:
• A function is an instance of the Object type.
• You can store the function in a variable.
• You can pass the function as a parameter to another function.
• You can return the function from a function.
• You can store them in data structures such as hash tables, lists, …
Examples illustrating First Class functions in Python
1. Functions are objects: Python functions are first class objects. In the
example below, we are assigning function to a variable. This assignment
doesn’t call the function. It takes the function object referenced by shout and
creates a second name pointing to it, yell.

# Python program to illustrate functions


# can be treated as objects
def shout(text):
return text.upper()

print (shout('Hello'))

yell = shout

print (yell('Hello'))

Output:
HELLO
HELLO
2. Functions can be passed as arguments to other functions: Because
functions are objects we can pass them as arguments to other functions.
Functions that can accept other functions as arguments are also called higher-
order functions. In the example below, we have created a function greet which
takes a function as an argument.

# Python program to illustrate functions


# can be passed as arguments to other functions
def shout(text):
return text.upper()
def whisper(text):
return text.lower()

def greet(func):
# storing the function in a variable
greeting = func("""Hi, I am created by a function
passed as an argument.""")
print (greeting)

greet(shout)
greet(whisper)

Output
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
hi, i am created by a function passed as an argument.

3. Functions can return another function: Because functions are objects we


can return a function from another function. In the below example, the
create_adder function returns adder function.

# Python program to illustrate functions


# Functions can return another function

def create_adder(x):
def adder(y):
return x+y

return adder

add_15 = create_adder(15)

print (add_15(10))

Output:

25

Parameters vs Arguments
Arguments are values that are passed into function(or method) when the
calling function

Parameters are variables(identifiers) specified in the (header of) function


definition

Following image shows difference between parameters and arguments.

Function Parameters VS Arguments

With function call arguments are what you pass into the function parameters.
Or it can be said, parameters are names(variables) in a function(or method)
definition that specifies types of arguments that the function can accept.

In call-by-value programming languages arguments are copied into parameter


(variables) by their position

Python is based on call by object reference or sometimes called call by sharing,


where reference of formal arguments will be assigned to actual parameters

These words are sometimes used interchangeably but aware of context

Python supports two kind of arguments

• Positional arguments

• keywords arguments

And python supports total five kind of parameters

• positional or keyword

• positional only

• keyword only

• variable positional (var-positional)


• Variable Keyword

These different kind of arguments and parameters is what we are going to see
later in this article

Formal vs Actual Arguments

Formal arguments are identifiers used in the function definition to represent


corresponding actual arguments.

Actual arguments are values(or variables)/expressions that are used inside


the parentheses of a function call.

Above definition and terminology of Formal/Actual arguments is same across


different programming languages.

Regular Positional Arguments

These are regular positional argument as it sounds regular. Regular positional


arguments are very much similar to arguments that you see in any kind of
programming language. These are just (variables) identifiers that values of
actual arguments are copied to formal arguments by their position in the
function call *.

def add(a, b):


return a + b

# function call
add(2, 3)

If count of actual arguments and formal arguments don’t match interpreter will
throw TypeError exception
>>> add(2)
Traceback (most recent call last):
File "", line 1, in <module>
TypeError: add() missing 1 required positional argument: 'b'

Default Arguments
Default arguments allow us to provide defaults for corresponding formal
arguments in the function definition. Python uses these defaults if
corresponding actual arguments are not passed in the function call.

Note : Default arguments should always be followed by non-default arguments in function definition

def greetings(name, msg="Welcom, Good Morning"):


message = "Hello {}! {}".format(name, msg)
print(message)

As we can see here, the argument msg got it’s default in the function
definition. If the argument msg is not passed in the function call it’s default
given in the definition will be used. So called default arguments.
>>> greetings("neo")
Hello neo! Welcom, Good Morning

Note: Default arguments are mandatory to pass in a function call. If default arguments are not passed,
corresponding default parameter values will be used. To override defaults pass corresponding arguments in a
function call

The concept of default arguments is very powerful and helpful when writing
APIs or utility function. We can define a function with some default parameters
which are not required to make a function but can be used by those who want
more control. Let’s look at following example

For suppose we are writing a function to fetch home page of arbitrary website .
As we know default port for HTTP is 80. We can write a function in such a way
that, which will accept one positional argument which address and one default
argument which port.

def fetchHomePage(domain, port=80):


import urllib.request
url = f"http://{domain}:{port}/"
page = urllib.request.urlopen(url).read()
print(page)
Calling above function by excluding port argument, where default value 80 will
be used
fetchHomePage("example.com")

Let’s say, your web site is running on port 8000. In such a case we can make
function call with port argument value 8000 which overrides default value 80

fetchHomePage("example.com", port=8000)
If default arguments are specified prior non-default arguments it is a syntax
error with following message
SyntaxError: non-default argument follows default argument
Following code causes a syntax error since non-default argument follows
default argument
def foo(a=3, b, c): #invalid default arguments order/ syntax error pass

Keyword Arguments

Keyword arguments are passed by it’s name instead of their position as


opposed to positional arguments in the function call. As a result we don’t have
to mind about position of arguments when calling a function.

Keyword arguments are also referred as named arguments.

Keyword arguments should always be followed by positional arguments in the function


call

Let’s call above defined function greetings using keyword arguments

greetings(name="neo", msg="Welcome")

Since we are passing arguments by their names/keywords order or position


doesn’t matter

greetings(msg="Welcome", name="neo")

We can mix both positional and keyword arguments but keyword arguments
should follow positional arguments

greetings("neo", msg="Welcome")

If you break the rule and pass arguments in such a way that positional
arguments follow keyword arguments which is a syntax error.

>>> greetings(msg="Welcome", "neo")


... ...

SyntaxError: positional argument follows keyword argument

Variable Length Positional Arguments


Variable length positional arguments are useful when we are not certain about
number of arguments that are required in the function definition or function
would receive. It is quite useful to write functions that take countless number
of positional arguments for certain use cases.

Syntax to receive variable length positional arguments

def foo(a, b, c, *varargs):


....
Python first fills the slots given formal arguments by passed positional actual
arguments. Any left over actual (positional) arguments are captured by python
as a tuple, which is available through variable which is having prefixed * in the
function definition.

As we can see in the above syntax. variables a, b, c need to be filled by actual


arguments any left over passed arguments can be accessed as tuple using
varargs.

def foo(a, b, c, *varargs):


print("Regular Positional Arguments", a, b, c)
print("Variable Length Positional arguments", varargs)
>>> foo(2, 3, 4)
Regular Positional Arguments 2 3 4
Variable Length Positional arguments ()
Since there are no extra positional arguments are passed in the above function
call. The variable varargs is a empty tuple

>>> foo(1, 2, 3, 4, 5, 7)
Regular Positional Arguments 1 2 3
Variable Length Positional arguments (4, 5, 7)
As you can see in the above function call, left over arguments are added to
tuple and can be accessed using given variable varargs.

You can unpack and pass each element in the sequence as individual argument just by
prefixing * in front of the sequence
>>> foo(1, 2, 3, *'hello')
Regular Positional Arguments 1 2 3
Variable Length Positional arguments ('h', 'e', 'l', 'l', 'o')
Where as, if you don’t put * in front of a string or sequence in the function call.
Which will be taken as single argument as a whole.

>>> foo(1, 2, 3, 'hello')


Regular Positional Arguments 1 2 3
Variable Length Positional arguments ('hello',)

Positional Only Parameters


Positional-only parameters syntax was added in Python 3.8 . This feature
allows to define a function to accept certain parameters positional only and
those parameters cannot be passed as keyword arguments in a function call.
Positional-only and other parameters are differentiated using forward slash
(/) in a function definition. All parameters prior forward slash ( /
) are positional only and parameters followed by forward slash ( / ) can be
any kind of (mixed)parameters. Passed arguments in a function call are
mapped to parameters solely based on their position.
Positional-only parameters are with out an externally usable name up on calling a
function. Arguments are mapped to parameters based on their position for positional-
only parameters

All parameters prior forward slash (/) in function definition are positional only
Following simple code explains function definition with position only
arguments
def foo(a, b, /, x, y):
print(f"positional only arguments: {a}, {b}")
print(f"positional or keyword arguments: {x}, {y}")

In the above example, parameters a and b are positional only while x and y can
be either positional or keyword arguments
Following function calls are valid
foo(2, 3, 4, 5)
foo("a", "b", "x", y=99)
foo(10, 20, x=66, y=99)

Following is a invalid function call


#Arguments a and b must be positional only
foo(a=3, b=30, x=99, y=999)

Following example shows positional only parameters mixed with other

def foo(a, b, c, /, x, y, z="default", *, name, operation, **kwargs):

print(f"Position-only parameters {a}, {b}, {c}")

print(f"Positional or Keyword arguments {x}, {y}, {z}")

print(f"Keyword Only Arguments {name}, {operation}")

print(f"Variable length keyword arguments {kwargs}") #Since params


left to / are not keywords those parameter names remain avaialbe in
kwargs

print("{:^80}".format("_"*50))

#Valid Function Calls

foo(1, 3, 4, 8, 9, 2, name="test", operation="noop")

foo(1, 2, 9, "x-val", y="hello", name="test", operation="nooop",


a=3.3, b=33, c=9, alpha=33)

#Invalid Function Calls

#Following function call will cause an error "missing 3 required


positional arguments: 'a', 'b', and 'c'"

foo(a=2, b=3, c=99, x=2, y=9, name="test", operation="noop") # a, b


and c are given as keywords

Function can be defined to accept only positional arguments by suffixing


forward slash (/) in parameter list

def power(x, y, /):


return x ** y

In the above example parameters x and y have to be passed as positional


arguments in function call. Calling the above function by keyword arguments
raises TypeError as follows

TypeError: power() got some positional-only arguments passed as keyword arguments: ‘x, y’

keyword Only Arguments

Keyword Only arguments are new feature in python 3. Main purpose of


keyword only arguments is to be able to pass arguments by it’s keyword only
for selected arguments.

There are two types of keyword only arguments

Non-Default Keyword-Only ArgumentsDefault Keyword-Only Arguments

Variable Length Keyword Arguments


Variable length keyword arguments are very much similar to variable length
positional arguments. It is the mechanism to accept variable length arguments
in the form keyword arguments which is useful if we are not certain about
number of keyword arguments that function receives. Python captures all extra
keyword arguments as dictionary and makes it available by name(variable)
which is prefixed by ** in the function definition.

Variable length keyword arguments can also be referred variable length named
arguments

Variable Length Keyword Arguments Syntax

def foo(a, b, c, **kwargs):


. . .
kwargs gets left over keyword arguments after formal arguments are filled up by passed keyword
arguments.

def printKWArgs(a, b, c, **kwargs):


print("Regular Positional Arguments", a, b, c)
print("Variable Length keyword arguments", kwargs)
>>> printKWArgs(2, 3, c=5)
Regular Positional Arguments 2 3 5
Variable Length keyword arguments {}
In the above function call since we haven’t passed any extra keyword
arguments variable kwargs is a empty dictionary.

>>> printKWArgs(2, 3, c=4, d=9, e=10)


Regular Positional Arguments 2 3 4
Variable Length keyword arguments {'d': 9, 'e': 10}
In the above function call left over keyword arguments d and e can be accessed
through variable kwargs which is dictionary. Where key will be the passed
keyword name and value will be value given for corresponding keyword in the
function call.

Combining both varargs and kwargs


You can use both variable length positional arguments and variable length
keyword arguments combined.

def foo(a, b, *varargs, **kwargs):


Different Types Of Function Arguments In Action

Here is the simple function which makes use of all kind of arguments and
prints passed arguments by it’s kind

def printArgsByKind(a, b, c, default=None, intype=int, *more, operation,


print_result=False, return_type, ignore_exceptions=True, **kwargs):
print("Regular Positional Arguments a: {}, b: {}, c: {}".format(a, b, c))
print("Default Arguments default: {}, intype: {}".format(default, intype) )
print("Variable length positional arguments(tuple) more: {}".format(more))
print("Non-Default Keyword-Only Arguments operation: {}, return_type:
{}".format(operation, return_type))
print("Default Keyword-Only Arguments print_result: {}, ignore_exception:
{}".format(print_result, ignore_exceptions))
print("Variable length keyword arguments kwargs: {}".format(kwargs))

Let’s call the above function by passing these several kind of arguments

printArgsByKind(1, 2, 3, 3.15, float, 4, 5, 6,


operation="count", return_type=int, abc=3, xyz=9)

The above function call would print the given arguments by it’s kind as follows,
Regular Positional Arguments a: 1, b: 2, c: 3
Default Arguments default: 3.15, intype: <class 'float'>
Variable length positional arguments(tuple) more: (4, 5, 6)
Non-Default Keyword-Only Arguments operation: count,
return_type: <class 'int'>
Default Keyword-Only Arguments print_result: False,
ignore_exception: True
Variable length keyword arguments kwargs: {'abc': 3, 'xyz':
9}

What is recursion?

Recursion is the process of defining something in terms of itself.

A physical world example would be to place two parallel mirrors facing each
other. Any object in between them would be reflected recursively.
Python Recursive Function

In Python, we know that a function can call other functions. It is even possible
for the function to call itself. These types of construct are termed as recursive
functions.

The following image shows the working of a recursive function called recurse.

Following is an example of a recursive function to find the factorial of an


integer.

Factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.

Example of a recursive function


def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))

Output
The factorial of 3 is 6
Recursion methodology

Python - Error Types

The most common reason of an error in a Python program is when a certain


statement is not in accordance with the prescribed usage. Such an error is
called a syntax error. The Python interpreter immediately reports it, usually
along with the reason.

>>> print "hello"


SyntaxError: Missing parentheses in call to 'print'. Did you
mean print("hello")?

In Python 3.x, print is a built-in function and requires parentheses. The


statement above violates this usage and hence syntax error is displayed.

Many times though, a program results in an error after it is run even if it


doesn't have any syntax error. Such an error is a runtime error, called an
exception. A number of built-in exceptions are defined in the Python library.
Let's see some common error types.
The following table lists important built-in exceptions in Python.

Exception Description
AssertionError Raised when the assert statement fails.
AttributeError Raised on the attribute assignment or reference fails.
EOFError Raised when the input() function hits the end-of-file
condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raised when a generator's close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when the index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+c or
delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in the local or
global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when a system operation causes a system-
related error.
OverflowError Raised when the result of an arithmetic operation is
too large to be represented.
ReferenceError Raised when a weak reference proxy is used to access
a garbage collected referent.
RuntimeError Raised when an error does not fall under any other
category.
StopIteration Raised by the next() function to indicate that there is
no further item to be returned by the iterator.
SyntaxError Raised by the parser when a syntax error is
encountered.
IndentationError Raised when there is an incorrect indentation.
TabError Raised when the indentation consists of inconsistent
tabs and spaces.
SystemError Raised when the interpreter detects internal error.
SystemExit Raised by the sys.exit() function.
TypeError Raised when a function or operation is applied to an
object of an incorrect type.
UnboundLocalError Raised when a reference is made to a local variable in
a function or method, but no value has been bound to
that variable.
Exception Description
UnicodeError Raised when a Unicode-related encoding or decoding
error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during
encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during
decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during
translation.
ValueError Raised when a function gets an argument of correct
type but improper value.
ZeroDivisionError Raised when the second operand of a division or
module operation is zero.

IndexError

The IndexError is thrown when trying to access an item at an invalid index.

>>> L1=[1,2,3]
>>> L1[3]
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>

L1[3]
IndexError: list index out of range
ModuleNotFoundError

The ModuleNotFoundError is thrown when a module could not be found.

>>> import notamodule


Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>

import notamodule
ModuleNotFoundError: No module named 'notamodule'
KeyError

The KeyError is thrown when a key is not found.

>>> D1={'1':"aa", '2':"bb", '3':"cc"}


>>> D1['4']
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>

D1['4']
KeyError: '4'

ImportError

The ImportError is thrown when a specified function cannot be found.

>>> from math import cube


Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>

from math import cube


ImportError: cannot import name 'cube'
StopIteration

The StopIteration is thrown when the next() function goes beyond the iterator
items.

>>> it=iter([1,2,3])
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>

next(it)
StopIteration
TypeError

The TypeError is thrown when an operation or function is applied to an object


of an inappropriate type.

>>> '2'+2
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>

'2'+2
TypeError: must be str, not int

ValueError

The ValueError is thrown when a function's argument is of an inappropriate


type.

>>> int('xyz')
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>

int('xyz')
ValueError: invalid literal for int() with base 10: 'xyz'

NameError

The NameError is thrown when an object could not be found.

>>> age
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>

age
NameError: name 'age' is not defined
ZeroDivisionError

The ZeroDivisionError is thrown when the second operator in the division is


zero.

>>> x=100/0
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>

x=100/0
ZeroDivisionError: division by zero

KeyboardInterrupt

The KeyboardInterrupt is thrown when the user hits the interrupt key
(normally Control-C) during the execution of the program.

>>> name=input('enter your name')


enter your name^c
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>

name=input('enter your name')


KeyboardInterrupt

Python Exception Handling


Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors
are the problems in a program due to which the program will stop the
execution. On the other hand, exceptions are raised when some internal events
occur which changes the normal flow of the program.

Difference between Syntax Error and Exceptions

Syntax Error: As the name suggests this error is caused by the wrong syntax
in the code. It leads to the termination of the program.

Example:

# initialize the amount variable

amount = 10000
# check that You are eligible to

# purchase Dsa Self Paced or not

if(amount > 2999)

print("You are eligible to purchase Dsa Self Paced")

output

Exceptions: Exceptions are raised when the program is syntactically correct,


but the code resulted in an error. This error does not stop the execution of the
program, however, it changes the normal flow of the program.

Example:

# initialize the amount variable

marks = 10000

# perform division with 0

a = marks / 0

print(a)

output
Try and Except Statement – Catching Exceptions

Try and except statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are kept inside the try clause and the
statements that handle the exception are written inside except clause.

Example: Let us try to access the array element whose index is out of bound
and handle the corresponding exception.

# Python program to handle simple runtime error


#Python 3

a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))

# Throws error since there are only 3 elements in array


print ("Fourth element = %d" %(a[3]))

except:
print ("An error occurred")

Output
Second element = 2
An error occurred

In the above example, the statements that can cause the error are placed inside
the try statement (second print statement in our case). The second print
statement tries to access the fourth element of the list which is not there and
this throws an exception. This exception is then caught by the except
statement.
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for
different exceptions. Please note that at most one handler will be executed. For
example, we can add IndexError in the above code. The general syntax for
adding specific exceptions are –

try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)

Example: Catching specific exception in Python


• Python3
# Program to handle multiple errors with one
# except statement
# Python 3

def fun(a):
if a < 4:

# throws ZeroDivisionError for a = 3


b = a/(a-3)

# throws NameError if a >= 4


print("Value of b = ", b)

try:
fun(3)
fun(5)

# note that braces () are necessary here for


# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

Output
ZeroDivisionError Occurred and Handled

If you comment the line fun(3), the output will be


NameError Occurred and Handled
The output above is so because as soon as python tries to access the value of
b, NameError occurs.

Try with Else Clause

In python, you can also use the else clause on the try-except block which must
be present after all the except clauses. The code enters the else block only if the
try clause does not raise an exception.

Example: Try with else clause

• Python3

# Program to depict else clause with try-except


# Python 3
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)

# Driver program to test above function


AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

Output:
-5.0
a/b result in 0

Finally Keyword in Python

Python provides a keyword finally, which is always executed after the try and
except blocks. The finally block always executes after normal termination of try
block or after try block terminates due to some exception.

Syntax:

try:
# Some Code....

except:
# optional block
# Handling of exception (if required)

else:
# execute if no exception

finally:
# Some code .....(always executed)

# Python program to demonstrate finally

# No exception Exception raised in try block

try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')

Output:
Can't divide by zero
This is always executed

Raising Exception
The raise statement allows the programmer to force a specific exception to
occur. The sole argument in raise indicates the exception to be raised. This
must be either an exception instance or an exception class (a class that derives
from Exception).

# Program to depict Raising Exception

try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or not

The output of the above code will simply line printed as “An exception” but a
Runtime error will also occur in the last due to raise statement in the last line.
So, the output on your command line will look like

Traceback (most recent call last):

File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in <module>

raise NameError("Hi there") # Raise Error

NameError: Hi there
User defined Exception

Python throws errors and exceptions when there is a code gone wrong, which
may cause the program to stop abruptly. Python also provides an exception
handling method with the help of try-except. Some of the standard exceptions
which are most frequent include IndexError, ImportError, IOError,
ZeroDivisionError, TypeError, and FileNotFoundError. A user can create his
own error using the exception class.

Creating User-defined Exception

Programmers may name their own exceptions by creating a new exception


class. Exceptions need to be derived from the Exception class, either directly or
indirectly. Although not mandatory, most of the exceptions are named as
names that end in “Error” similar to the naming of the standard exceptions in
python. For example:

# A python program to create user-defined exception

# class MyError is derived from super class Exception


class MyError(Exception):

# Constructor or Initializer
def __init__(self, value):
self.value = value

# __str__ is to print() the value


def __str__(self):
return(repr(self.value))

try:
raise(MyError(3*2))

# Value of Exception is stored in error


except MyError as error:
print('A New Exception occured: ',error.value)

Output:
('A New Exception occured: ', 6)
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
Scanned with FlashScan
UNIT-4(LSC_HVP1EM)
5. Anubhava:
The direct experience of a 2
as his anubhava. People learn many thin person is }
known
This experiential ife
learning is a
through experience.
opener for many.
In Indian philosophy, there eye
five means
are

to have proper cooni


of valid knowledge (pramANa. ognition
the world. Of them, the first is known as ratyaksha
representing which is evident. Pratyaksha is of two
anubhava and smriti.
types
Anubhava represents direct perception while riti
denotes remembered perception.

6. Define Value. Explain the concept of Understanding


the thought provoking issues; need for Values in Our

daily life
Ans: 'Value' comes from the Latin word 'valere' which
means to be of worth, to be strong. The value literally means
something that has price, Something. precious, dear and
worthwhile.
Humans have the unique ability to define their identity,
choose their values and establish their beliefs. All three of
these directhly influence a person's behavior. People will act
congruent with their personal values what they deem to be
or

important: A value is defined as a principle that promotes


well-being or prevents harm.
Personal values are defined as Emotional beliefsin
principles regarded as particularly favorable or important for
UNIT-(LSC HVP1EM) 13
he individual.
theindividual. Our values associate emotions to our
aneriences and guide our choices, decisions and actions.
experience

Yeed of V'alues in our day life


1, Values are the enduring beliefs that a specific mode of
conduct or end-state of existence is personally or
socially preferable.
2. These are more dificult to change or alter.
3. As ethical conduct receives more visibility in the
workplace, the importance of values is increased as a
topic of discussion in management.
4. Values are general principles to regulate our day-to-day
behavior. They not only give direction to our behavior
but are also ideals and objectives in themselves.
5. They are the expression of the ultimate ends, goals or

purposes of social action.


6. Our values are the basis of our judgments about what is
desirable, beautiful, . proper, corect, important,
worthwhile and good as well as what is undesirable,
ugly, incorrect, improper and bad.
Types of Values
1. Values related to Right Conduct
a) Self-hely Skills: Care of possessions, diet, hygiene,
modesty, posture, self reliance, and tidy appearance.
b) Social Skills: Good behavior, good manners, good
relationships, helpfulness, No wastage, and good
environment, and
UNIT-(LSC HVP1EM) 14
Ethical Skills: Code of conduct, Courage,
dependability. duty.efficiencyingonuity, initiative,
perseverance. punctuality, resourcefulness, respect for all, and
responsibility
2. Values related to PEACE: Attention, calmness.
concentration. contentment, dignity, discipline, equality,
equanimity. faithfulness, focus, gratitude, happiness.
harmony. humility. inner silence, optimism, patience,
retlection, satisfaction, self-acceptance, self-confidence, self-
control. self-discipline, self-esteem, self-respect, sense
control, tolerance, and understanding.
3. Values related to Truth: Accuracy, curiosity,
discemment, fairness, fearlessness, honesty, integrity (unity
of thought, word, and deed), intuition, justice, optimism,
purity. quest for knowledge, reason, self-analysis, sincerity
sprit
sprit of enquiry, synthesis, trust, truthfulness, and
determination.
4. Values related to Love: Acceptance, affection, care
compassion, consideration, dedication, devotion, empathy,
forbearance, forgiveness, friendship, generosity, gentleness,
humanness, interdependence, kindness, patience, patriotism.
reverence, sacrifíce, selflessness, service, sharing, sympathy,
thoughtfulness, tolerance and trust.
5. Values related to Non-violence
a) Psychological: Benevolence, compassion, concen
for others, consideration, forbearance, forgiveness, manners,
happiness, loyalty, morality, and universal love
UNIT-1(LSC_HVP1EM)
15
b) Social: Appreciation of other cultures and
religions,
hrotherhood, care of
environment, citizenship, equality,
harmlessness, natio awareness, perseverance, respect for
property, and social justice.
Functions of Values
1 Value is the foundation for
understanding the level of
motivation.
2. It influences our perception.
3. Value helps to understand what ought to be or what
ought not to be.
4. It contains interpretations of right or wrong.
5. These influence attitudes and behavior.
6. It implies that certain behaviors on outcomes are
preferred over others.
7. These allow the members of an organization to interact
harmoniously. These make it easier to reach goals that
would be impossible to achieve individually.
8. These are goals set for achievements, and they motivate,
define and color all our activities cognitive, affective
add connective.
9. They are the guideposts of our lives, and they direct us
to who we want to be.
10. Values and morals can not only guide but inspire and
motivate a person, give energy and a zest for living and
for doing something meaningful.
UNIT4(LSCHVP1EM)
Describe the role of choice
making in
education. value
Ans: Decision making (Choice Making) plays a vitat
the life of students. It diverts the students from
fallino role inin
trap that manages the students and saves their falling int thehe
career
life.
The ability to distinguish between
choice and
nd needs
plays a vital role in the life of students. It
determination on how to make good decisions and promotes
self.
Here are a few strategies that choicen es
followed while talki
taking
decisions. They are as follows:
I.
Self determination:
Self-determination
-

combination of knowledge, belief, skills isa


to become
that enable
goal-directed, autonomous behavior and evenstudents
regulated. This is enhanced with selt
oneself, planning, acting, knowing and valuine
outcomes.
valuing
experiencing and learning from the
2.
Learning disabilities: These
experienced by the students for learning disabilities
acknowledge the available resources.which they have toto
disclose their weakness They should try to
may try to help the with the concerned member as
students. they
3.
student Understanding strengths and
is
capable of weakness: If the
weakness then they must understanding the strengths and
an try make effective
to
alternative method to obtain
4. it. decisions and
failure in
Helplessness:
which Helplessness deals
one can with the effects of
failures. It often leads predict the past and future
to a lack
of positive
effects o
ositive and effective
effectrve
UNIT-(LSC HVP1EM)
decision making skills. The
accuracy has
17
to be found within
the strengthand weaknesses and even the
into account. preferences taken

Aeting
Repeeting Acting on
Choices

Alfiming Prizing and


Cherishing

Choosing After
Thoughtful Choosing
Considerstion Freely
Choosing
FronAmon9
Altematives

Fig.: Values Clarification Process


5. Socialization skills: Socialization skills are usually
decided learned from special education or through individual
methods. The majority of students fail in effective
tutoring and learning
decision-making skills. It helps in understanding
the skills of making different alternatives.
clarification
was developed
A process model of values values
Harmin and Simon and is known as the
by Raths, of three
define a value in terms
clarification approach. They
key valuing processes: choosing, prizing and acting.
UNIT-(LSC_HVPIEM) 17
decision making skills. The accuracy has to be found within
the strength and weaknesses and even the preferences taken
into account.

Acting on
Repeating Choices

Prizing and
Affirming Cherishing

Choosing After
Thoughtful Choosing
Freely
Considerstion Choosing
FromAmong
Altematives

Values Clarification Process


Fig.:
5. Socialization skills: Socialization skills are usually
individual
decided learned from special education or through
students fail in effective
tutoring methods. The majority of and learning
decision-making skills. It helps in understanding
the skills ofmaking different alternatives.
clarification was developed
A process model of values
Harmin and Simon and is known as the values
by Raths,
clarification approach. Theydefine a value in terms of three
key valuing processes: choosing, prizing and acting.
U N I T -( L S C _ H V P 1 E M )

Student
Key
Valuing Actions
Criteria Key Teach
Process aza
At this level,
Questions
Repeating the How did VO
Acting action will decide you
reappear which
a had priority?
number of times
on Demonstrating How
Acting has
Choices
choices by already affectedit
integrating the your life?
choice in our life
Willing to affirm Would
Prizing Afiming you
the choice explain to others
publicly. how you feel
about this?
Prizing and The individual Are you glad
Cherishing esteems, respects you feel that
and hold the way?
value dear.
Reflective What is the basis
Choosing After
thoughtful thought base on for you choice?
consideration|research and
investigation.
Choosing Examining What ideas did
from alternatives and you reject before
alternatives then making a making this
choice. |choice?
Choosing Whare did the
Choosing
freely without idea for you
Come
Coercion. choice
from?
UNIT-(LSC HVPIEM) 19
8. Write about Classification of Value Education,
Ans: Value' comes from the Latin word 'valere'
which
means to be of worth, to be
strong. The value literally means
something that has price, something precious, dear and
worthwhile.

Humans have the unique ability to define their identity,


choose their values and establish their beliefs. All three of
5 these directly influence a person's behavior. People will act
congruent with their personal values or what they deem to be
important. A value is defined as a
principle that promotes
well-being or prevents harm.
Classification of Value Education
1. Personal Values: Personal Values are personal to an
individual both in terms of thein possession and their use. It is
a desire and cherished by the
individual irrespective of his or
her social relationship. Each and every individual like to
imbibe these values at their personal level. These values make
a person good for himself.
Examples: ambition, cleanliness,
discipline, honesty, loyalty, contentment, courage, creativity,
determination, dignity of labour, diligence, excellence, hope,
maturity, regularity, punctuality, self-confidence, self
motivation, simplicity, accomplishment, purity etc.
2. Social Values: Social values are certain behaviours
and beliefs that are shared within specific cultures and social
groups. These values are cherished and practiced because of
our association with others. It imposes the interaction of two
or more
persons. Social values are always practised in relation
U N I T A L B C V P I E M )

tjty
inly,
iphimr4,
fmi

indivulunl with he, tus


f an
the
elatmnbip
tesy,
thaiy, V I t y ,
faittes ww.y
AAIplee
neighbmliness,
tust e l truh, nntability
Hnntability
rotherhen
dutile, fongivene99, freedom, friendshin ytitude
JuVe, patienE, TEpentanue,
rest
huspitality. justice,
tean spirit, tuoleranc ett
seVICe, saring, »ymipatiy,
Mornl values are thoe
, Maral Valuen:
individual in mmak ing i dIGtjfictoon betweeri tiet

enable an
particularly reke.
atid
good and bad et, I
wrong and the
mafn in the various situti.
conduct of man oWards

which hunan beings


Cne Dera
wgether, They reveal a

self control ixmple: fairnes, justice, equality, hurnan


dignity, honely, integrity, SCnse of responsibility
compassion cte.
4. Splrltual Values: Spiritual values are characterived
hy the proceNs of °rcllecting on non-material dimensions of
ife and acquiring insights into personal cxperiences, which
are of cnduring worth. They arc related to soul and immaterial
rcality related. They are intangible and are not concemed with
material things, They necd not be religious values. They
affect the individual in his relations with himself. Sp1ritua
values are cternal and they do not change. They are real ideas
Thee arc Concerned with the realisation of the Sel a
being one with 'Divinity'. Examples: truth, beauty, gooddness
UNIT-(LSC HVP1EM) 21
unity. pure, love, joy, self-giving, contentment, wisdom,
dispassion, self-discipline, devotion to God, etc.

9. What are human values? Explain their significance?


Ans: Human values are the Principles, standards, convictions
and beliefs that people adopt as their guidelines in daily
activities. Principles human values are the foundation on
which professional ethic are built. They are a set of consistent
pleasures and behaviors that individuäl choose to practice and
behaviors that individual choose to practice in the pursuit of
doing what is right or what is expected them. by Society.
Most laws and legislations are shaped by human values.
Significance of human values:
1. Human values have been a central concept is the social
sciences since their inception.
2. Human values play a vital role in the society for leading
a better life.
3. Human values possess a significant position in the
society. Values are a Cognitive structure that describes
the ideals of life of individuals, their preferences,
Priorities, principles and the behavior
4. Human beings receive information through five senses
and it is the human values that help us to discriminate
from right and wrong, good and bad.
5. Human values play a significant role in bringing
solution to the global problems such as ecological
problems moral problems, global warming etc.,
UNIT- (LSC HVP1EM)
6. Human values is seen right from the child hood o-
person. Pre-school is the first stage or period that
the foundation of information on human values.

Love

Trust Respect
Human
Wisdom Faith
Values
Beauty Co-Operation

7. The values such as dignity, liberty, equality, justice,


ethics and morals etc. have their significant impact to
shape the human relations in a society.
8. Values play a significant role for the promotion of
realization of human rights in any society.
Different Types of human values: Human values are

the features that guide people to take into account the human

element when interact with other human. They have


one

many positive characters that create


bonds of humanity
between people and thus have value for all human beings.
UNIT- (LSC HVP1EM)
Several universal
23
human values such as truth, honesty love,
faith beauty, cooperation, respect, trust
etc. are some of the
human values required for a beter
society.
1) Trust: Trust can be understood in
many ways, but
finally it comes dowm to
reliability and truth. Without trust
the world simply would not function.
2) Love: The presence of love in human
life, the love
they have for their families, friends and for
themselves
important source of energy to lead smooth life.
3) Respect: Respect is a
feeling of
deep esteem for
someone or something express by their abilities, qualities or
achievements.
4) Faith: Faith is complete trust or confidence in
someone or something.

5) Cooperation: It is the procedure to work jointly to


attain some goals. But many scholars visualize
cooperation is
a luxury and not an important human value. However, it is the
most vital asset
when working through a problem.
6) Caring: It is viewed as exhibiting kindness and
concern for others, because
caring for others both physically
and spiritually is an extremely important value for human
being.
7) Honesty: An honest Person is often straight, upright
sincere and fair. An honest person brings more reward to the
Soul than the damage a lie could do.
8) Beauty: Beauty is the something that really been
UNIT- (LSC_HVP1EM) 2A
spoiled by human society. The way we think about something

that is beautiful is judged on a purely physical response. but


the true meaning of a beauty is being in a balance and

harmony with nature.


9) Wisdom: Wisdom means the quality of having

experience, good judgment and the resulting soundness of that


action or decision.

10. What are the basic things for fulfillment of basic


human aspiratións?
Ans: Everyone wants to be happy and prosperous in one's life
it is the basic human aspiration. To fulfill the human
aspiration three types of basic requirements are needed. (1)
physical Facilities (2) Relationships (3) Right understanding
1) Physical Facilities: This includes the physiological
needs of individuals and indicates the necessities as well as
comforts of life.
Wealth and prosperity contribute to our enrichment.
Having wealth means having accumulation of materialistic
comforts and possessions. Prosperity means feelings of
abundance and adequacy of wealth-having the wealth is
necessary but not sufficient condition for prosperity.
have
Prosperity means feelings of having or being able more

physical facilities than is needed.


Basic requirements for fulfilling the Aspirations:
Relationships: One cannot live in Isolation as life is the
other name of relationship living in communion with other
UNIT-1(LSC_HVP1EM) 25
Deople, things and ideas, without relationship there is no
existence. The relationship of two or more people creates
society. These relations are usually, based upon mutual
interdependence and mutual assistance that may include
mental security, power or self evolution. If that does not
gratify or satisty one, one is likely to change one's relations
with other person or things.

RIGHT UNDERSTANDING

Relation ship Physical Facilities)


Mutual happiness with Mutual Prosperity
humanbeings with rest of the nature
Relations are also means for self-revelation and self-
knowledge. To understand oneself, one must understand
relationship as relationship is a mirror in which one can see
oneself. Relationship is a process of self revelation, and
without knowing oneself, the ways of one's own mind and
heart, merely to establish an outward society has very little
meaning. What is important is to understand oneself in
relationships with another. Then relationships becomes a
process of discovering one's own motives, thoughts and
pursuits.
Right understanding: This refers to higher order human
skills, the need to learn and utilize our intelligence most
effectively. Right understanding lies in being mindful and
cultivating awareness of the moments. This is awareness of
UNIT-(LSC HVP1EM)
the moments. This awareness or right understanding does not
come through cultivation of any discipline, but being aware
from moment to moment in the practical world.

l1. Define Life Skills. Explain the key life skils and their

fulfillment
Ans: A skill is a learned ability to do something well. So Life
Skills are the abilities that individuals can develop to live a
fruitful life.
Life Skills are psychosocial abilities that enable
individuals to translate knowledge, attitudes and values
regarding their concerns into well informed and healthy
behaviours. Empowered with such skills, young people are
able to take decisions based on a logical process of "what to
do, why to do, how to do and when to do".
WHO defines Life Skills as "the abilities for adaptive
and positive behaviour that enable the individuals to deal
effectively with the demands and challenges of everyday
life".
Key Life Skills
Life Skills include psychosocial competencies and
interpersonal skills that help people make informed decisions,
solve problems, think critically and creatively, communicate
effectively, build healthy relationships, empathize with others,
and manage their lives in a healthy and productive manner.
UNIT-H(LSC HVPIEM) 27

do
ManagngEmotlons

Creatve Thnking
Skills
CrlticalThinking Empathy

1. Self Awareness: Self Awareness includes the


recognition of 'self, our character, our strengths and
weaknesses, desires and dislikes. Developing self awareness
can help us recognize when we are stressed or under pressure.
It is often a prerequisite to effective communication and
interpersonal relations, as well as for developing empathy.
2. Interpersonal skills: They help us to relate in
positive ways with people we interact. This may mean being
able to make and keep friendly relationships, which can be of
great importance to our mental and social well-being. It may
mean maintaining good relations with family members who
UNIT- (LSC_HVPIEM)
are the most important social support. It may
source of also
mean an ability to end relationships constructively.
3. Effective Communication: It means that we are able
to express ourselves, both verbally and in ways
non-verbally,
that are appropriate to our cultures and situations. This means
being able to express opinions and desires, and also needs and
fears. And, it would also mean being able to ask for advice
and help in the time of need.
4. Critical Thinking: It is an ability to analyze
information and experiences in an objective manner. Critical
Thinking can contribute to a well balanced way of life by
helping us to recognize and assess the factors that influence
attitudes and behaviour, such as values, peer pressure and the
media.
5. Creative Thinking: It is a novel way of seeing or
doing things that is characteristic of four components-fluency
(generating new ideas), flexibility (shifting perspective
easily), originality (conceiving of something new), and
elaboration (building on others' ideas).
6. Problem Solving: It helps us to deal constructively
with problems in our lives. Significant problems that are left
unresolved can cause mental stress and give rise to
accompanying physical strain.
7. Decision Making: It helps us to deal constructively
with decisions about our lives. It can teach people how to
actively make decisions about their actions in relation to a
UNIT-H (LSC_HVPIEM) 29
healthy assessment of different options and, what cffects these
different decisions are likely to have.
8. Coping with Stres: It means recognizing the sources
of stress in our lives, recognizing how they affect us, and how
we act in a way that helps us control our levels of stress by
environment or lifestyle, and learning how to
changing our

relax
9. Managing Emotions: It means recognizing emotions
within us and others, being aware of how emotions influence
behaviour and being able to respond to emotions
appropriately. Intense emotions sadness can
like anger or

have negative effects on our health if we don't respond to


them appropriately.
10. Empathy: It is required to develop a successful
relationship with our loved ones and society at large. It is the
ability to imagine what life is like for another person. Without
empathy, our communication with others will amount to a
one-way traffic. It can help us to accept others, who may be
very different from ourselves. This can improve social
interactions, especially, in situations of ethnic or cultural
diversities.
All these skills are interrelated and reinforce each
other. Together, they are responsible for our psychosocial
competence; build our self-esteem and self efficacy and
nurture holistic development.
UNIT-H (LSC HVPIEM) 30
SHORT ANSWER QUESTIONS

12. Value Education


Ans: Value Education consists of proper education of the care
human values which enables one to have a holistic view of
life and its significance. These are Fundamental values which
cut across the contours of Race, Religion, caste, creed
Country, gender and so on. These are intended to emsure

dignity of human beings. The focus is on upholding and


cherishing the Fundamental Principles of equality, Non
discrimination, Universal Peace, Justice, Non Violence and
Tolerance. A clear cut understanding of these core values help
the human beings to lead their life in a dignified manner in a

peaceful and stress free environment.


Definition: "The System of education which correctly

identify our basic aspirations, ensures the complementarity of


value and skills, facilitates the developed appropriate
technology and its Right Utilization for human welfare".

13. Human values


Ans: Human values are the Principles, standards, convictions
and beliefs that people adopt as their guidelines in daily
activities. Principles human values are the foundation on

which professional ethic are built. They are a set of consistent

pleasures and behaviors that individual choose to practice and


behaviors that individual choose to practice in the pursut o
UNIT- (LSC_HVP1EM) 31
doing what is right or what is expecled them. by Society.
Most laws and legislations are shaped by human values.

14. Right understanding


Ans: This reters to higher order human skills, the need to
learn and utilize our intelligence most effectively. Right
understanding lies in being mindful and cultivating awareness
of the moments. This is awareness of the moments. This
not come through
awareness or right understanding does
cultivation of any discipline, but being aware from moment to

moment in the practical world.

15. What is Harmony?


Ans: To ensure, continuous happiness and prosperity one's
life, one needs to cultivate harmony with others beings.
Harmony in the state of absence of conflict and experience of
silence and stillness, peace and tranquility in day to day living
feeling comfortable
of the practical world. Harmony means
with onesclf as well as with others.

the meaning of words "Conduct and"


16. Explain
Character"
Ans: Conduct: The bahaviour and conduct at a person is the

expression and manifestation at the level of self harmony


achieved by him.
UNIT-I (LSC_HVP1EM) 32
A Person's decds over a convicted period of time
become a habit and determine his bahaviour in differenm
circumstances, Habit is Spontancous and automatic due
internalization of the set pattern of actions in a given
situation.
Character: A dignified and worthy conduct is required
for leading a fulfilling life. A person who has imbibed
internalized good virtues always maintains his mental poise
and equilibrium whether it is success or failure. He is a role
model for other not by words but by his own life.

17. Technology and human values.


Ans: The present education system has become largely skill.
based. The prime emphasis is on science and technology.
However, science and technology can only help to provide the
means to achieve what is considered valuable. It is not within
the scope of science and technology to provide the
competence of deciding what really is valuable. Value
Education is a crucial missing link in the present education
system. Because of this deficiency, most of our efforts may
prove to be counterproductive and serious crises at the
individual, societal and environmental level are manifesting

18. Personal Values.


Ans: Personal Values are personal to an individual both in
terms of their possession and their use. It is a desire and
cherished by the individual irrespective of his or her social
UNIT-(LSC HVP1EM) 33kde

elationship. Each and every individual like to imbibe these


alues at their personal level. These values make a person
ood for himself. Examples: ambition, cleanliness, discipline,
goo

honesty. loyalty, contentment, courage, creativity,


determination, dignity of labour, diligence, excellence, hope,
maturity, regularity, punctuality, self-confidence, self-

motivation, simplicity, accomplishment, purity etc.

19. Social Values

Ans: Social values are certain behaviours and beliefs that are
shared within specific cultures and social groups. These
values are cherished and practiced because of our association
with others. It imposes the interaction of two or more persons.

Social values are always practised in relation to our

neighbours, community, society, nation and world. These


values are good for the society and form the basis of the

relationship of an individual with other people in society.


Examples: courtesy, charity, civic duty, fairness, goodness,
neighbourliness, trust and truth, accountability, brotherhood,
dutifulness, forgiveness, freedom, friendship, gratitude,
hospitality, justice, love, patience, repentance, responsibility,
tolerance etc.
service, sharing, sympathy, team spirit,

20. Moral Values.


Ans: Moral values those values that enable an individual
are
and good
in making a distinction between right and wrong
conduct of man
and bad etc. It particularly refer to the
UNIT-(LSC HVP1EM)
towards man in the various situations in which human beings
come together. They reveal a person's self-control. Example
fairness, justice, equality, human dignity, honesty, integrity,
sense of responsibility, compassion etc.

21. Spiritual Values


Ans: Spiritual values are characterized by the process of
'reflecting on non-material dimensions of life and acquiring
insights into personal experiences, which are of enduring
worth. They are related to soul and immaterial reality related.
They are intangible and are not concerned with material
things. They need not be religious values. They affect the
individual in his relations with himself. Spiritual values are
etemal and they do not change. They are real ideas. These are
concerned with the realisation of the "Self and being one
with 'Divinity'. Examples: truth, beauty, goodness, unity,
pure, love, joy, self-giving, contentment, wisdom, dispassion,
self-discipline, devotion to God, etc.
UNIT-
INTRODUCTION

ESSAY QUESTIONS

1. What is 'Value Education'? What is the need or

purpose of value education?


Ans: Introduction:- Value Education consists of proper
education of the care human values which enables one to have
a holistic view of life and its significance. These are
Fundamental values which cut across the contours of Race,
and so These are
Religion, caste, creed, Country, gender on.

intended to ensure dignity of human beings. The focus is on

upholding and cherishing the Fundamental Principles of


equality, Non discrimination, Universal Peace, Justice, Non
Violence and Tolerance. A clear cut understanding of these
core values help the human beings to lead their life in a

dignified manner in a peaceful and stress free environment.


Definition: "The System of education which correctly
identify our basic aspirations, ensures the complementarily of
value and skils, facilitates the developed appropriate
technology and its Right Utilization for human welfare".
1
UNIT- (LSC HVPIEM)
2
Happy and
Complementing
values and skills
fulfilled living
m

M
/Living in harmony
Right and peace with the
understanding of self and
our Aspirations surrounding
VVVVW
Need for
W M Right evaluation
Sustainable Value
of our beliefs and
development Education «
belief systems
W W

WM Right useo
Understanding Technology
Universal Values
of fulfill our
Science
Aspirations
W
Need for value education:
) Happy and fulfilled living: Value education is
needed to make life happy and complete. Happy life is a life
of real significance, a life infused with understanding purpose
and fulfillment. Skills are needed to make one's. life

successful, but this is external phenomenon. If one is not


happy and fulfilled being, one feels empty and in emotional
or

existential crisis because of lacking something. with


cultivation of human values, one can understand oneself and

wwwww
UNIT-(LSC HVP1EM) 3
and fulfilled.
feel liberated
I) Right understanding of our Aspirations: All human
heings have diflerent aspirations and wishes-one may want to
become doctor or enginer or manager and consequently have
different plans and programmes of future. This planning and
programmes may be related with personal, professional and
family, life besides participation in social or other domains.
Human values can guide to understand one's aspirations and
the plans to fulfill them.
Sustainable development: Sustainable
development aims at development of the physical and
material resources and various facilities for the humanity
without causing depletion or inflicting harm for the next
generations. It is unfortunate that present development efforts
are made at the cost of sustainability. It is value education that
can guide whether the 'technology that we are using is
environmental friendly or is having the element of
Sustainability.
Understanding Universal Values to fulfill our
Aspirations: Every human being has universal aspiration to
become happy as well as prosperous in life. Prosperity is
measured in terms of material resources where as happiness is
a mental state of well being characterized by positive
emotions of intense joy, contentment and good living. To
maintain proper balance between happiness and prosperity,
one needs to understand values, In the light of which the
etemal goals of life including pursuit of wealth as well as
UNIT-(LSCHVPIEM)
to be pursued.
solace and solvation have
) Complementing values and skills: In the

achieving our aspirations,


we need to be
mentally pursuit of
spiritually elevated. on
the other hand we we nced
happy
need to andnd
methods for accomplishment of the goals of life, For have
For pursu'y
directinut
wisdom guide the
of happiness, values and
direction in
light which human happiness
is to be pursued. For achievingthe
For ao:e
the ends we need means. For this, we need to
to need leam the
methods and practices to achieve the goals.

V) Living in harmony and peace with the self


and
surrounding: For living a happy life, one needs to cultivate
harmony and peace with oneself as well as with the
surrounding. Harmony means feeling comfortable with
oneself, as well as with others. Once a person feels
comfortable with one self, one is likely to be at harmony and
peace with the surrounding. The basis of happiness and
tranquility is the absence of personal doership and the absence
of hatred and malice, and cultivation of the sense the other
beings are just extension of his or her consciousness.
VI) Right evaluation of our beliefs and belief
systems: In our daily and practical life we develop so many
beliefs and our behavior is conditioned by these beliefs. For
example, we develop a belief that " a particular brand of soap

is the best.
VI) Right use of Technology and Science: Science
and Technology have given us abundant
gifts and tremendous
power to amellorate the human conditions. We can over come
UNITH(LSCHVPIEM)
the evils conditions
of poverty and starvation, abolish hnger
and malnutrition. control diseases. solve environmentai
problems of polhution. etc But at the same time we have
enough nuclear powCT TO destrOy the human race many times

Over. to commit not oniy racial suicide but the destruction of

planet carth.

2. What is the Nature and scope of value education?


4S: Nature and scope of value education: Value education

plays a creating a better society, more


very important role in

ethical organizations, and groups, and better human beings


Let us take a look at how it does this.
1. Value education can help to build human beings who

possess strength, integrity and fortitude.


2. Value education builds the values of cooperation and
peace as well as tolerance.
3. Efficiency can step up if a person possesses the right
values. This may include punctuality, keeping one's
word professionalism, lack of bias or prejudices etc,
4. Creating cordial relationships between people by
encouraging the values of respect, love and affection.
5. Promoting personality development and social cohesion
6. Regeneration values of national pride and integration
towards nation building.
1. Building character in the young people who will lead
the country in the future
a
8. .Promoting harmony between nations and ereatng
UNIT- (LSC_HVP1EM) 6
peaceful world order.
9. Identifying the core universal values of:
a) Truth (Satya)
b) Righteous Conduct (Dharma)
c) Peace (Shanti)
d) Non- Voilence (Ahimsa)
e) Love (Prema)
10. To help create a foundation of the quality of life and
strike a balance between external and internal values.

3. What are the Contents of Value Education?


Ans: The purpose of value education is harmonious
development for an individual with inculcating values. The
value education covers all dimensions of an individual like
his thought, behavior, work and realization. It also includes
the living of an individual an different levels-individual,
family, society, nature and existence. The contents of value
education shall be:
1. Understanding oneself.
2. Understanding one's aspirations.
3. Understanding the happiness and prosperity of one's
being
4. Understanding the goal ofhuman life.
5. Understanding the interconnectedness of all beings.
6. Understanding the co-existence of different beings.
7. Understanding the way of creating harmony at
different levels: at individual level, at family level and
UNIT-(LSC HVP1EM) 7
in professional life.
Understanding one's mind thought patterns, behavior
and self regulations.

4. Explain the Basic Guidelines for Value Education?


4ns: The subject that enables us to understand, "what is
Valuable for human happiness is called value education.
Here is need to identify and develop certain
guidelines that can help us to develop framework of value
education. These guidelines should be effective to practically
implement the value education. At the same time, these
should be acceptable to various persons belonging to
different religious sects and cults. The purpose of these
guidelines is to generate more light than heat or to help
human beings than to harm.
1) Universal: "The value education should be
universally acceptable and applicable to all human
beings. It should not be restricted to particular caste, creed
or community. At the same time, it should also cross the
barriers to nations in the present era of globalised world.
Its emphasis should be universal human values.
2) Rational and verifiable: The value education should
be based on rationality and reasons. The element of
dogmatism or blind faith should not be there. Therefore it
should be free from set of sermons or Do's It It should be
verifiable on the basis of sound reasoning. We should not
assume as it has been stated in some particular religious book.
UNIT- (LSC HVP1EM)
3) Natural: The value education should be natura
i.e. it should be acceptable to all human beings i
natural manner. If we are living on the basis of certai
values that are natural to us, it will lead to happiness an
harmony in daily living. It will not only lead to fulfillmer
but also peace and harmony with people with whom w
interact.
/NVVVI
Leading too
Harmony and
peace in daily
N
atural living Universal

Guidelines
All
for value
Encompassing
Education

Rat
Aqeuejsns Sensitivity to
erifivaeRbrailftteiiaoobnnaalell andand
other human
beingsand
creatureS
A
UNIT-(LSC_ HVP1EM) 9
9
4) Al Encompassing:
Value education is not just
transfer of intormation but transformation of the total bcing
as harmonious individual. This value education should
permeate all dimensions of the individual: his thought
patterns, his actions, his behavior, his personal as well as
professional life. Itaims at development of universal
consciousness and outlook.
5) Leading to Harmony and peace in daily
living:
Value education should lead to harmony and
peace in daily
living. Harmony means feeling comfortable with oneself as
well aswith others. It will inculcate
peace in our human
relations. It should lead the individual to the
understanding
that the other person interacting with him is
just extension
of his consciousness. We all are the same but
we, think
differently and are separate without separation.
6) Sustainability: Value education should inculcate
the concept of sustainability among the various individuals.
Sustainability aims at use of material resources without
causing harm or depletion or denying them for the future
generation.
7) Sensitivity to other human beings and creatures:
Value education should develop
sensitivity among
individuals for other human beings and creatures. It should
lead one to realize and understand that the other
persons
belonging to different caste, community, creed or country
are the same at the level of consciousness. Each one of us
has unique existence and essence. With this understanding,
UNIT- (LSC_HVP1EM) 0
one islikely become harmless being and will not
to
inflice
harm among other persons and creatures.

5. Explain the Process ofvalue education?


Ans The Process of value Education has to be
ascertained
before we proceed. Let us now acquaint ourselves with the
process of value education which we are going to adopt. In
this course, various aspects of Reality
facilitating the
understanding of human values will be presented as
proposals. You need to verify these proposals for yourself and
examine your living in this light. Let us see how we
can
verify these principles.

individualised
Learning
Anubhava
Project Leaming
Process of
Value
Eduaction
Open Leaming Group Leaming

1. Individualized Learning: This approach focuses on


the specific learning needs of each student. This facilitates
active learning and makes it more meaningful and interesting
The student is encouraged to participate in organizatio
of learming, selecting the learming tasks as well as the pace of
learning. This individualized approach also makes the studet
more responsible besides being motivational. The teacher cal
value
also supplement and complement the varying
UNIT-4(LSC_HVP1EM) 1
ntations provided
by the family of the student.
All the
above cannot be achieved in the nomal traditional apptoach
2. Project Learning: This is
a' modern approach to
alue education. In this etfective method, the learning content
is tactfully classitied and transformed into
project tasks
These are in turn related to real life situations. This kindles
the interests in the students and attracts them. This
helps the
students harness their creativity and
to
sharpen their problem
solving capabilities. This teaches the concepts of self-
discipline. tolerance and co-operation. Important lessons are
learnt for the present and future as well.
3. Group Learning : The Group learning process is
highly useful as it fosters team building skills. This makes the
students understand the importance of two-way
communication, co-operation collaboration and co-ordination
among the various members of the group.
4. Open Learning : This stems from the reformation-
oriented school of thought. This approach fills the various
gaps noticed in the traditional education system. This
helps
the students to develop the special parts of the learning
contents both individually and as a group.
Implementation of value education in terms of concrete
themes and tasks by Roping together the students and teachers
is none the less a formidable Endeavour but worth
undertaking considerable the benefits that brings to the
society as a whole.
Page 1 of 15
Page 2 of 15
Page 3 of 15
Page 4 of 15
Page 5 of 15
Page 6 of 15
Page 7 of 15
Page 8 of 15
Page 9 of 15
Page 10 of 15
Page 11 of 15
Page 12 of 15
Page 13 of 15
Page 14 of 15
Page 15 of 15
Page 1 of 10
Page 2 of 10
Page 3 of 10
Page 4 of 10
Page 5 of 10
Page 6 of 10
Page 7 of 10
Page 8 of 10
Page 9 of 10
Page 10 of 10
Page 1 of 4
Page 2 of 4
Page 3 of 4
Page 4 of 4
UNIT – 2

THE BROOK
Alfred Tennyson

I Answer the following questions in 50-100 words.

1. What kind of landscape is described in the first three stanzas?

About the poet: The poem ”The Brook”, was written by Alfred Tennyson. He was Poet
Laureate of United Kingdom for much of the Victorian Period. He was a master of rhythm and
rich, descriptive imagery. In this poem, a small stream narrates its journey from its origin in
the hills to its destination.

While describing the movements of the brook and its passage through various places, the poet
describes the beauty of nature that surrounds the brook as it passes through. The brook (a small
river) takes its birth from a place which is regularly visited by water birds like coots and herons.
The small river bursts out all of a sudden. Sparkling or shining through the flowerless plants or
ferns in the sunlight, it flows noisily down to a valley. The river hurries down through thirty
hills. It slips quickly unnoticed between the mountain ranges. In the end, the small river flows
near the Philip’s farm. Here, it joins with another river which is full of water—to the brim.

2. What are the types of water bodies and plant life that are talked about in the poem?

About the poet: The poem ”The Brook”, was written by Alfred Tennyson. He was Poet
Laureate of United Kingdom for much of the Victorian Period. He was a master of rhythm and
rich, descriptive imagery. In this poem, a small stream narrates its journey from its origin in
the hills to its destination.

The poet has mentioned some water bodies like lakes, large rivers, streams, pools, etc. The
brook flows silently through lawns and grassy plots. It slides through the bushes of hazelnuts.
In its flow the brook sweeps away ‘forget-me-nots’ flowers which grow for the happy lovers.
The poem is about the writer's journey along the river-side where he closely observes
nature. He reminds the readers that humans are supposed to born and die but brook is eternal.

3. Explain the Line: ”I make the netted sunbeam dance/Against my sandy shallows.”

About the poet: The poem ”The Brook”, was written by Alfred Tennyson. He was Poet
Laureate of United Kingdom for much of the Victorian Period. He was a master of rhythm and
rich, descriptive imagery. In this poem, a small stream narrates its journey from its origin in
the hills to its destination.

The ‘netted sunbeam’ refers to the sunrays filtering through the leaves and bushes that fall on
the surface of sandy shallow water in a net-like pattern. The movement of water makes it
dancing. In other words the interplay of sunshine and shadow makes the sunbeam appear to be
trapped on the surface of the brook; it appears to dance due to the movement of the brook.

4. What is the mood of the poem?


About the poet: The poem ”The Brook”, was written by Alfred Tennyson. He was Poet
Laureate of United Kingdom for much of the Victorian Period. He was a master of rhythm and
rich, descriptive imagery. In this poem, a small stream narrates its journey from its origin in
the hills to its destination.

As the brook flows towards the river, it is very happy. However, the brook changes its mood
at times. Sometimes it becomes very playful and sometimes like a mature person. It makes
noise as it flows over the stones and pebbles. It babbles, bubbles and quarrels. As it rubs against
its banks, it produces a musical sound showing the energetic mood the Brook is in . Brook finds
its way through the forget- me- nots flowers and goes on slipping, dancing, sliding and
lingering. Very slow and steady movements show its unwilling mood. At last it murmurs
reaching its destination.

II. Answer the following questions in 200-300 words.

1. What are the various words the poet uses to describe the sound of the brook? How does it
contribute to the effect of the poem?

About the poet: The poem,”The Brook”, was written by Alfred Tennyson. He was Poet
Laureate of United Kingdom for much of the Victorian Period. He was a master of rhythm and
rich, descriptive imagery. In this poem, a small stream narrates its journey from its origin in
the hills to its destination.

The brook’s varying movements create an exhilarating musical effect. Some words relating to
sound scattered throughout the poem are clatters, frets, slips, slides, murmurs etc. The brook
flows on making different kinds of noises and sounds at different places. It seems to chatter
while flowing through its stony ways. “Chattering over stony ways” creates the effect of a
rhythmic movement combining high and low musical notes. It also makes sharp and high-
pitched sounds and noises. When it flows in the spiral movement of water, its noise is lost. “I
steal by lawns” creates a slow, lethargic and rhythmic movement. The “Lingering”, “Loitering”
movements are followed by speedy “pace, curve and flow”. But when it strikes on the shingles
and pebbles, it creates a sound as if it is talking gaily to them.

2. How has the poet described landscape, flowers, plants and colours in the poem? How does
it make you feel as a reader? Substantiate your answer with examples from the poem?

About the poet: The poem,”The Brook”, was written by Alfred Tennyson. He was Poet
Laureate of United Kingdom for much of the Victorian Period. He was a master of rhythm and
rich, descriptive imagery. In this poem, a small stream narrates its journey from its origin in
the hills to its destination.

The poet has given wonderful description about the brook. The brook originates from a hilly
place which is so high that it is usually visited by the birds like coot and heron. The brook then
suddenly emerges and flows down the valley. The river hurries down through thirty hills. It
slips quickly unnoticed between the mountain ranges. In the end, the small river flows near the
Philip’s farm. Here, it joins with another river which is full of water—to the brim. Men may
come or go (take birth or die) from this world but the brook continues to flow forever. The
brook flows through those parts of land which extend into the sea and look like lands of fairies.
It passes through bushes of willow and plants of mallow growing near its banks.
The brook goes on flowing in a zig-zag way sometimes shrinking and sometimes expanding.
We can find a blossom sailing over its surface. Here and there we can find a big and fat trout
and at other places we can find a grayling swimming in and out of it. As the brook flows on,
foamy flakes are formed over its surface. When it passes over the golden shingles and pebbles
many silvery waves are formed over them.

The brook flows silently through lawns and grassy plots. It slides through the bushes of
hazelnuts. In its flow the brook sweeps away ‘forget-me-not’ flowers which grow for the happy
lovers. It looks bright and happy in the sunlight. The swallows fly over it touching its surface.
The rays of the sun fall on its surface and are trapped in. The reflected rays seem to be dancing
brightly in the sun against the sandy shallows. Then the brook comes out curving and flowing
to join the big river that is filled with water to the brim.

3. Explain what you think is meant by the lines "For men may come and men may go, But I go
on forever". What does it say about Nature?

About the poet: The poem,”The Brook”, was written by Alfred Tennyson. He was Poet
Laureate of United Kingdom for much of the Victorian Period. He was a master of rhythm and
rich, descriptive imagery. In this poem, a small stream narrates its journey from its origin in
the hills to its destination.

The poet, through a series of sound images and onomatopoeic words, describes the movement
of the brook and brings out certain universal truth which forms the central idea of the poem;
that human life is transitory, but nature is eternal; that there is an end to every form of life, but
the brook, a representation of nature, is everlasting. This idea is expressed in the line which
forms the refrain of the poem.: The lines “For men may come and men may go, But I go on
forever” have been repeated in the poem several times in order to lay emphasis on the brook
being immortal. It is ironical that man is so arrogant though he is merely a mortal. On a deeper
level, the poet uses the brook to draw a parallel with the life of a man. Like the brook, man is
energetic, lively and moves swiftly when he is young but slows down later on in life just like
the brook does before it reaches the river.

4. Who is the speaker of the poem? What is this technique of investing human qualities into
non-living things called? Why do you think the poet has chosen to use this technique here?
How does it contribute to the effect of the poem?

About the poet: The poem,”The Brook”, was written by Alfred Tennyson. He was Poet
Laureate of United Kingdom for much of the Victorian Period. He was a master of rhythm and
rich, descriptive imagery. In this poem, a small stream narrates its journey from its origin in
the hills to its destination.

Alfred, Lord Tennyson makes great use of personification in his poem “The Brook.”
Personification is giving human qualities to inanimate objects. In Tennyson’s poem, he uses
personification to help the reader actually see and hear the brook he is describing. The fourth
stanza is a really excellent example of this: When the author uses the words chatter and babble,
he is using personification. People chatter and babble; yet, when Tennyson uses these words,
we can hear the sound of the brook, which is his intention.
This happens again in the tenth stanza: In this case, the words steal and slide imply sneaking
by something. Instead of just saying that, though, Tennyson lets the reader see if by using
words that conjure up a picture of someone sneaking around. He implies that the brook is
capable not just of slipping and sliding (implying slippery) but of emotion “gloom” and sight
“glance.” These words make the reader think of how a brook “acts” as it flows. The water
slips and slides, but in other cases it may be quiet and dark—gloomy.

In this poem, Tennyson not only tells us how a brook flows, he lets us hear and see it through
his use of personification.

You might also like