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]]
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.
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
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
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
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.
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.
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
✓ 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.
1. Number
>> x = 5
>> print(type(x))
2. Strings
>> x = "Hello World"
>> 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))
6. Tuples
>> x = ("apple", "banana", "cherry")
>> print(x)
>> print(type(x))
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))
>> 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))
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.
Depending on the type of operations that the operators perform, they are categorized into
the following categories:
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
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.
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
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 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.
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
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:
Access Modes
Modes Description
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
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()
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:
Example
import os
os.rename("abc.txt","xyz.txt")
os.remove(file_name)
Example
import os
os.remove("abc.txt")
os.chdir("new directory")
Example
import os
os.chdir("new directory path")
os.rmdir("directory name")
Example
>> import os
>> os.rmdir("abc") // where abc is a directory name which you want to remove
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.
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)
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
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
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.
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
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”]
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’]
print(list1[-1])
print(list1[-3])
Output:
5
3
list1[2:-1]
output:
[3, 4]
list1[:2]
output:
[1, 2]
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.
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.
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).
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’)])
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
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.
Output:
(5, 125)
{1: 1, 2: 8, 3: 21, 4: 64}
Output:
{1: 1, 2: 8, 3: 21, 4: 64}
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, {}.
Output:
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘cubes’ is not defined
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
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
✓ 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.
Output:
(‘Viswam’, ‘ Python’, ‘tutorial’)
(1,2,3,4)
Output:
Tutorial
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.
Output:
(‘Viswam’, ‘Python’, ‘tutorial’)
Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘tup1’ is not defined
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
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
Here, we are maintaining reference of the passed object and appending values
in the same object. So, this would produce the following result –
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
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 −
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
To call the function printme(), you definitely need to pass one argument,
otherwise it gives a syntax error as follows −
#!/usr/bin/python
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
My string
The following example gives more clear picture. Note that the order of
parameters does not matter.
#!/usr/bin/python
Name: miki
Age 50
Default arguments
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
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
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
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
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.
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.
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
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.
• Positional arguments
• keywords arguments
• positional or keyword
• positional only
• keyword only
These different kind of arguments and parameters is what we are going to see
later in this article
# 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
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.
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
greetings(name="neo", msg="Welcome")
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.
>>> 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.
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)
print("{:^80}".format("_"*50))
TypeError: power() got some positional-only arguments passed as keyword arguments: ‘x, y’
Variable length keyword arguments can also be referred variable length named
arguments
Here is the simple function which makes use of all kind of arguments and
prints passed arguments by it’s kind
Let’s call the above function by passing these several kind of arguments
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?
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.
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.
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
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
>>> 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
import notamodule
ModuleNotFoundError: No module named 'notamodule'
KeyError
D1['4']
KeyError: '4'
ImportError
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
>>> '2'+2
Traceback (most recent call last):
File "<pyshell#23>", line 1, in <module>
'2'+2
TypeError: must be str, not int
ValueError
>>> 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
>>> age
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
age
NameError: name 'age' is not defined
ZeroDivisionError
>>> 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.
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:
amount = 10000
# check that You are eligible to
output
Example:
marks = 10000
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.
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
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)
def fun(a):
if a < 4:
try:
fun(3)
fun(5)
Output
ZeroDivisionError Occurred and Handled
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.
• Python3
Output:
-5.0
a/b result in 0
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)
try:
k = 5//0 # raises divide by zero exception.
print(k)
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).
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
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.
# Constructor or Initializer
def __init__(self, value):
self.value = value
try:
raise(MyError(3*2))
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
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
Aeting
Repeeting Acting on
Choices
Choosing After
Thoughtful Choosing
Considerstion Freely
Choosing
FronAmon9
Altematives
Acting on
Repeating Choices
Prizing and
Affirming Cherishing
Choosing After
Thoughtful Choosing
Freely
Considerstion Choosing
FromAmong
Altematives
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.
tjty
inly,
iphimr4,
fmi
enable an
particularly reke.
atid
good and bad et, I
wrong and the
mafn in the various situti.
conduct of man oWards
Love
Trust Respect
Human
Wisdom Faith
Values
Beauty Co-Operation
the features that guide people to take into account the human
RIGHT UNDERSTANDING
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
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
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.
ESSAY QUESTIONS
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
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
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
planet carth.
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.
individualised
Learning
Anubhava
Project Leaming
Process of
Value
Eduaction
Open Leaming Group Leaming
THE BROOK
Alfred Tennyson
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.
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.
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.