0% found this document useful (0 votes)
30 views77 pages

Python Unit1

Uploaded by

prasannadp04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
30 views77 pages

Python Unit1

Uploaded by

prasannadp04
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 77

Python For Data Science

Unit-1

Definition:

Python is a high-level, interpreted, interactive and object-oriented


scripting language. Python is designed to be highly readable. It uses English
keywords frequently where as other languages use punctuation, and it has
fewer syntactical constructions than other languages.
 Python is Interpreted: Python is processed at runtime by the interpreter.
You do not need to compile your program before executing it. This is
similar to PERL and PHP.
 Python is Interactive: You can actually sit at a Python prompt and
interact with the interpreter directly to write your programs.
 Python is Object-Oriented: Python supports Object-Oriented style or
technique of programming that encapsulates code within objects.
 Python is a Beginner's Language: Python is a great language for the
beginner-level programmers and supports the development of a wide range
of applications from simple text processing to WWW browsers to games.

History of Python

 Python was developed by Guido van Rossum in the late eighties and early
nineties at the National Research Institute for Mathematics and Computer
Science in the Netherlands.
 Python is derived from many other languages, including ABC, Modula-3, C,
C++, Algol-68, SmallTalk, Unix shell, and other scripting languages.
 At the time when he began implementing Python, Guido van Rossum was
also reading the published scripts from "Monty Python's Flying Circus" (a
BBC comedy series from the seventies, in the unlikely case you didn't
know). It occurred to him that he needed a name that was short, unique,
and slightly mysterious, so he decided to call the language Python.
 Python is now maintained by a core development team at the institute,
although Guido van Rossum still holds a vital role in directing its
progress.
 Python 1.0 was released on 20 February, 1991.
Unit-1 Page 1
Python For Data Science

 Python 2.0 was released on 16 October 2000 and had many major new
features, including a cycle detecting garbage collector and support for
Unicode. With this release the development process was changed and
became more transparent and community- backed.
 Python 3.0 (which early in its development was commonly referred to as
Python 3000 or py3k), a major, backwards-incompatible release, was
released on 3 December 2008 after a long period of testing. Many of its
major features have been back ported to the backwards-compatible Python
2.6.x and 2.7.x version series.
 In January 2017 Google announced work on a Python 2.7 to go
transcompiler, which The Register speculated was in response to Python
2.7's planned end-of-life.

Python Features:

Python's features include:


 Easy-to-learn: Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.
 Easy-to-read: Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain: Python's source code is fairly easy-to-maintain.
 A broad standard library: Python's bulk of the library is very
portable and cross- platform compatible on UNIX, Windows, and
Macintosh.
 Interactive Mode: Python has support for an interactive mode which
allows interactive testing and debugging of snippets of code.
 Portable: Python can run on a wide variety of hardware platforms
and has the same interface on all platforms.
 Extendable: You can add low-level modules to the Python interpreter.
These modules enable programmers to add to or customize their tools to
be more efficient.
 Databases: Python provides interfaces to all major commercial databases.
 GUI Programming: Python supports GUI applications that can be
created and ported to many system calls, libraries, and windows systems,
such as Windows MFC, Macintosh, and the X Window system of UNIX.

Unit-1 Page 2
Python For Data Science

 Scalable: Python provides a better structure and support for large


programs than shell scripting.

Need of Python Programming


 Software quality
Python code is designed to be readable, and hence reusable and
maintainable— much more so than traditional scripting languages. The
uniformity of Python code makes it easy to understand, even if you did
not write it. In addition, Python has deep support for more advanced
software reuse mechanisms, such as object-oriented (OO) and function
programming.
 Developer productivity
Python boosts developer productivity many times beyond compiled
or statically typed languages such as C, C++, and Java. Python code is
typically one-third to less to debug, and less to maintain after the fact.
Python programs also run immediately, without the lengthy compile and
link steps required by some other tools, further boosting programmer
speed. Program portability Most Python programs run unchanged on all
major computer platforms. Porting Python code between Linux and
Windows, for example, is usually just a matter of copying a script‘s code
between machines.
 Support libraries
Python comes with a large collection of prebuilt and portable
functionality, known as the standard library. This library supports an
array of application-level programming tasks, from text pattern matching
to network scripting.
 Component integration
Python scripts can easily communicate with other parts of an
application, using a variety of integration mechanisms. Such integrations
allow Python to be used as a product customization and extension tool.
Today, Python code can invoke C and C++ libraries, can be called from C
and C++ programs, can integrate with Java and .NET components, can
communicate over frameworks such as COM and Silverlight, can interface
with devices over serial ports, and can interact over networks with
interfaces like SOAP, XML-RPC, and CORBA. It is not a standalone tool.

Unit-1 Page 3
Python For Data Science

 Enjoyment
Because of Python‘s ease of use and built-in toolset, it can make the
act of programming more pleasure than chore. Although this may be an
intangible benefit, its effect on productivity is an important asset. Of these
factors, the first two (quality and productivity) are probably the most
compelling benefits to most Python users, and merit a fuller description.
 It's Object-Oriented
Python is an object-oriented language, from the ground up. Its class
model supports advanced notions such as polymorphism, operator
overloading, and multiple inheritance; yet in the context of Python's
dynamic typing, object-oriented programming (OOP) is remarkably easy
to apply. Python's OOP nature makes it ideal as a scripting tool for object-
oriented systems languages such as C++ and Java. For example, Python
programs can subclass (specialized) classes implemented in C++ or Java.
 It's Free
Python is freeware—something which has lately been come to be
called open source software. As with Tcl and Perl, you can get the entire
system for free over the Internet. There are no restrictions on copying it,
embedding it in your systems, or shipping it with your products.
 It's Portable
Python programs are automatically compiled to portable bytecode,
which runs the same on any platform with a compatible version of Python
installed (more on this in the section "It's easy to use"). What that means is
that Python programs that use the core language run the same on UNIX,
MS-Windows, and any other system with a Python interpreter.
 It's Powerful
From a features perspective, Python is something of a hybrid. Its
tool set places it between traditional scripting languages (such as Tcl,
Scheme, and Perl), and systems languages (such as C, C++, and Java).
Python provides all the simplicity and ease of use of a scripting language,
along with more advanced programming tools typically found in systems
development languages.
 Automatic memory management
Python automatically allocates and reclaims ("garbage collects")

Unit-1 Page 4
Python For Data Science

objects when no longer used, and most grow and shrink on demand;
Python, not you, keeps track of low- level memory details.
 Programming-in-the-large support
Finally, for building larger systems, Python includes tools such as
modules, classes, and exceptions; they allow you to organize systems into
components, do OOP, and handle events gracefully.
 It's Easy to Use
For many, Python's combination of rapid turnaround and language
simplicity make programming more fun than work. To run a Python
program, you simply type it and run it. There are no intermediate compile
and link steps (as when using languages such as C or C++). As with other
interpreted languages, Python executes programs immediately, which
makes for both an interactive programming experience and rapid
turnaround after program changes. Strictly speaking, Python programs are
compiled (translated) to an intermediate form called bytecode, which is
then run by the interpreter.
 It's Easy to Learn
This brings us to the topic of this book: compared to other
programming languages, the core Python language is amazingly easy to
learn. In fact In fact, you can expect to be coding significant Python
programs in a matter of days (and perhaps in just hours, if you're already
an experienced programmer).

 Internet Scripting
Python comes with standard Internet utility modules that allow
Python programs to communicate over sockets, extract form information
sent to a server-side CGI script, parse HTML, transfer files by FTP,
process XML files, and much more. There are also a number of peripheral
tools for doing Internet programming in Python. For instance, the
HTMLGen and pythondoc systems generate HTML files from Python
class-based descriptions, and the JPython system mentioned above
provides for seamless Python/Java integration.
 Database Programming
Python's standard pickle module provides a simple object-
persistence system: it allows programs to easily save and restore entire

Unit-1 Page 5
Python For Data Science

Python objects to files. For more traditional database demands, there are
Python interfaces to Sybase, Oracle, Informix, ODBC, and more. There is
even a portable SQL database API for Python that runs the same on a
variety of underlying database systems, and a system named gadfly that
implements an SQL database for Python programs.

 Image Processing, AI, Distributed Objects, Etc.


Python is commonly applied in more domains than can be
mentioned here. But in general, many are just instances of Python's
component integration role in action. By adding Python as a frontend to
libraries of components written in a compiled language such as C, Python
becomes useful for scripting in a variety of domains. For instance, image
processing for Python is implemented as a set of library components
implemented in a compiled language such as C, along with a Python
frontend layer on top used to configure and launch the compiled
components.
Applications of Python:
1. Systems Programming
2. GUIs
3. Internet Scripting
4. Component Integration
5. Database Programming
6. Rapid Prototyping
7. Numeric and Scientific Programming

What Are Python’s Technical Strengths?


1. It‘s Object-Oriented and Functional
2. It‘s Free
3. It‘s Portable
4. It‘s Powerful
5. It‘s Mixable
6. It‘s Relatively Easy to Use
7. It‘s Relatively Easy to Learn

Unit-1 Page 6
Python For Data Science

Python standard library or Essential python library

The Python Standard Library contains the exact syntax, semantics, and tokens of
Python. It contains built-in modules that provide access to basic system
functionality like I/O and some other core modules. Most of the Python Libraries
are written in the C programming language. The Python standard library consists
of more than 200 core modules. All these work together to make Python a high-
level programming language.
1. TensorFlow: This library was developed by Google in collaboration with
the Brain Team. It is an open-source library used for high-level
computations. It is also used in machine learning and deep learning
algorithms. It contains a large number of tensor operations. Researchers also
use this Python library to solve complex computations in Mathematics and
Physics.

2. Matplotlib: This library is responsible for plotting numerical data. And


that’s why it is used in data analysis. It is also an open-source library and
plots high-defined figures like pie charts, histograms, scatterplots, graphs,
etc.

3. Pandas: Pandas are an important library for data scientists. It is an open-


source machine learning library that provides flexible high-level data
structures and a variety of analysis tools. It eases data analysis, data
manipulation, and cleaning of data. Pandas support operations like Sorting,
Re-indexing, Iteration, Concatenation, Conversion of data, Visualizations,
Aggregations, etc.

4. Numpy: The name “Numpy” stands for “Numerical Python”. It is the


commonly used library. It is a popular machine learning library that supports
large matrices and multi-dimensional data. It consists of in-built
mathematical functions for easy computations. Even libraries like
TensorFlow use Numpy internally to perform several operations on tensors.
Array Interface is one of the key features of this library.

5. SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-


source library used for high-level scientific computations. This library is
built over an extension of Numpy. It works with Numpy to handle complex

Unit-1 Page 7
Python For Data Science

computations. While Numpy allows sorting and indexing of array data, the
numerical data code is stored in SciPy. It is also widely used by application
developers and engineers.

6. Scrapy: It is an open-source library that is used for extracting data from


websites. It provides very fast web crawling and high-level screen scraping.
It can also be used for data mining and automated testing of data.

PYTHON IDENTIFIERS
A Python identifier is a name used to identify a variable, function, class, module
or other object. An identifier starts with a letter A to Z or a to z or an underscore
(_) followed by zero or more letters, underscores and digits (0 to 9).
Python does not allow punctuation characters such as @, $, and % within
identifiers. Python is a case sensitive programming language.
Here are naming conventions for Python identifiers −
 Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
 Starting an identifier with a single leading underscore indicates that the
identifier is private.
 Starting an identifier with two leading underscores indicates a strongly
private identifier.
 If the identifier also ends with two trailing underscores, the identifier is a
language-defined special name.
Reserved Words
The following list shows the Python keywords. These are reserved words and you
cannot use them as constant or variable or any other identifier names. All the
Python keywords contain lowercase letters only.

and exec Not


assert finally or
break for pass
class from print

Unit-1 Page 8
Python For Data Science

continue global raise

def If return
del import try
elif In while
else Is with
except lambda yield

LINES AND INDENTATION


Python provides no braces to indicate blocks of code for class and function
definitions or flow control.Blocks of code are denoted by line indentation, which
is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the
block must be indented the same amount. For example −
if True:
print "True"
else:
print "False"
Thus, in Python all the continuous lines indented with same number of spaces
would form a block.
Multi-Line Statements
Statements in Python typically end with a new line. Python allow the use of the
line continuation character (\) to denote that the line should continue. For example

total = item_one + \
item_two + \
item_three
Statements contained within the [], {}, or () brackets do not need to use the line
continuation character. For example −
days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday']

Unit-1 Page 9
Python For Data Science

QUOTATION IN PYTHON
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals, as long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines. For example, all
the following are legal −
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a paragraph. It is
made up of multiple lines and sentences."""
COMMENTS IN PYTHON
A hash sign (#) that is not inside a string literal begins a comment. All characters
after the # and up to the end of the physical line are part of the comment and the
Python interpreter ignores them.

# First comment
print ("Hello, Python!") # second comment
This produces the following result −
Hello, Python!
You can type a comment on the same line after a statement or expression −
name = "Madisetti" # This is again comment
You can comment multiple lines as follows −
# This is a comment.
# This is a comment, too.
# This is a comment, too.
# I said that already.
Using Blank Lines
A line containing only whitespace, possibly with a comment, is known as a blank
line and Python totally ignores it.
Multiple Statements on a Single Line
The semicolon ( ; ) allows multiple statements on the single.

import sys; x = 'foo'; sys.stdout.write(x + '\n')

Unit-1 Page 10
Python For Data Science

Multiple Statement Groups as Suites


A group of individual statements, which make a single code block are
called suites in Python. Complex statements, such as if, while, def, and class
require a header line and a suite.
Header lines begin the statement and terminate with a colon ( : ) and are followed
by one or more lines which make up the suite. For example −
if expression :
suite
elif expression :
suite
else :
suite
VARIABLE TYPES

Variables are nothing but reserved memory locations to store values. This means
that when you create a variable you reserve some space in memory.
Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory space. The
declaration happens automatically when you assign a value to a variable. The
equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable. For
example −
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print (counter)
print (miles)
print (name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles,
and name variables, respectively. This produces the following result −
100
1000.0
John

Unit-1 Page 11
Python For Data Science

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are
assigned to the same memory location. You can also assign multiple objects to
multiple variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b
respectively, and one string object with the value "john" is assigned to the variable
c.
Standard Data Types:

The data stored in memory can be of many types. For example, a


person's age is stored as a numeric value and his or her address is stored as
alphanumeric characters. Python has various standard data types that are used
to define the operations possible on them and the storage method for each of
them.
Python has five standard data types:
 Numbers
 String
 Boolean
 List
 Tuple
 Set
 Dictionary
PYTHON NUMBERS
Number data types store numeric values. Number objects are created when you
assign a value to them. For example −

var1 = 1
var2 = 10
You can delete a single object or multiple objects by using the del statement. For
example −

Unit-1 Page 12
Python For Data Science

del var
del var_a, var_b
Python supports four different numerical types −
 int (signed integers) − They are often called just integers or ints. They are
positive or negative whole numbers with no decimal point.
 long (long integers ) − Also called longs, they are integers of unlimited
size, written like integers and followed by an uppercase or lowercase L.
 float (floating point real values) − Also called floats, they represent real
numbers and are written with a decimal points. Floats may also be in
scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x
102 = 250).
 complex (complex numbers) − are of the form a + bJ, where a and b are
floats and J (or j) represents the square root of -1 (which is an imaginary
number). The real part of the number is a, and the imaginary part is b.
Complex numbers are not used much in Python programming.
Examples :Here are some examples of numbers

int long float complex

10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-786 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEL 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j

Unit-1 Page 13
Python For Data Science

PYTHON STRINGS

A STRING is a sequence of characters enclosed in quotes. The string can be


enclosed in single or double quotes.

var1 = 'Hello World!'


var2 = "Python Programming"

To access substrings, use the square brackets for slicing along with the index or
indices to obtain your substring. For example −

var1 = 'Hello World!'


var2 = "Python Programming"
print("var1[0]: ",var1[0]);
print ("var2[1:5]: ",var2[1:5]);

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

var1[0]: H
var2[1:5]: ytho

Program:
str ="WELCOME"
print( str) # Prints complete string
print (str[0]) # Prints first character of the string
print( str[2:5]) # Prints characters starting
from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd
character
print (str * 2) # Prints string two times
print( str + "CSE") # Prints concatenated string
Output:
WELCO
ME W

Unit-1 Page 14
Python For Data Science

LCO
LCO
ME
WELCOMEWELC
OME
WELCOMECSE

STRING OPERATIONS
Concatenation operator: The ‘+’ sign is used to combine number of strings and
returns a new string.
Ex: str1 = “Hello World”
Print(str1+ “ ‘can be joined’ ”) #prints concatenated string
Output: Hello world ‘Can be joined’
Repetition Operator: The * sign is the repetition operator which is used to repeat
the string as many times as specified.
Ex: str1 = “ Hello World”
Print (str1*2)
Output: Hello world Hello world.

ACCESSING CHARACTERS IN STRING: We can access a character from the


string by specifying the index of the character. Index starts from ‘0’ indicates
beginning of the string and -1 indicates at the end of the string.

Ex:
Str1= “STRINGS IN PYTHON”
Print(str1)
STRINGS IN PYTHON
print(str1[0])
S
print (str1[-1])
N
print(str1[-3])
H

STRING METHODS: String methods performs operations on strings.

Unit-1 Page 15
Python For Data Science

1. Len() : Returns the length of the string.


Ex: len(“Hello World”) #returns value as 11
2.Lower(): Converts all uppercase letters into lower case
Ex: s1=”PYTHON”
s1.lower()
output: python
3.Upper(): Converts all lower case letters into upper case
Ex: s1=”python”
s1.upper()
output: PYTHON
4.Replace(): Returns old string replaced by new.
Ex: str= This is Python”
Str.replace (‘is’, ‘was’)
Output: Thwas was python
5. Split(): This method used to split on white spaces and returns the list of
substrings as items.
Ex: str1=”Engineering Student”
Str1.split()
Output: [‘Engineering’, ‘student’]
6. Strip(): This function returns a copy of the string with the leading and
trailing characters removed.
Ex: str = “0000000 this is string….wow!!! 000000
Print str.strip(‘0’)
Output: this is string…..Wow!!!

LIST:
A list is similar to an array that consists of a group of elements or items.
Just like an array, a list can store elements. But, there is one major difference
between an array and a list. An array can store only one type of elements
whereas a list can store different types of elements. Hence lists are more
versatile and useful than an array.
Creating a List:
Creating a list is as simple as putting different comma-separated values
between square brackets.
student = [556, “Mothi”, 84, 96, 84, 75, 84 ]

Unit-1 Page 16
Python For Data Science

We can create empty list without any elements by simply writing empty
square brackets as: student=[ ]
We can create a list by embedding the elements inside a pair of square
braces []. The elements in the list should be separated by a comma (,).
Accessing Values in list:
To access values in lists, use the square brackets for slicing along with
the index or indiceses to obtain value available at that index. To view the

elements of a list as a whole, we can simply pass the list name to print
function.
Ex:
student = [556, “Mothi”, 84, 96, 84,
75, 84 ]
print( student
student)
student[0]) # Access 0th element
print (student[0]
dent[0:2]) # Access 0th to 1st elements
print( student[0:2]
student[2: ]]) # Access 2nd to end of
print (student[2:
list elements print student[ :3] # Access
starting to 2nd elements print student[ : ] #
Access starting to ending elements print
student[-1] # Access last index value
print (student[
student[-1:-7:-1]) # Access elements in reverse order
Output:
[556, “Mothi”, 84, 96, 84, 75, 84]
Mothi
[556, “Mothi”]
[84, 96, 84, 75, 84]
[556, “Mothi”, 84]
[556, “Mothi”, 84, 96, 84, 75, 84]
84
[84, 75, 84, 96, 84, “Mothi”]
Creating lists using range() function:
Unit-1 Page 17
Python For Data Science

We can use range() function to generate a sequence of integers which


can be stored in a list. To store numbers from 0 to 10 in a list as follows.
numbers = list( range(0,11) )
print( numbers) # [0,1,2,3,4,5,6,7,8,9,10]
To store even numbers from 0 to 10in a list
as follows. numbers = list(
range(0,11,2) )
print (numbers) # [0,2,4,6,8,10]
Looping on lists:
We can also display list by using for loop (or) while loop. The len( )
function useful to know the numbers of elements in the list. while loop
retrieves starting from 0th to the last element i.e. n-1
Ex-1:
numbers =
[1,2,3,4,5] for i
in numbers:
print (i)

Output:
12345

Updating and deleting lists:


Lists are mutable. It means we can modify the contents of a list. We can
append, update or delete the elements of a list depending upon our
requirements.
Appending an element means adding an element at the end of the list.
To, append a new element to the list, we should use the append() method.
Example:
lst=[1,2,4,5,8,6]
print lst #
[1,2,4,5,8,6]
lst.append(9)
print (lst) # [1,2,4,5,8,6,9]
Updating an element means changing the value of the element in the list.
This can be done by accessing the specific element using indexing or slicing
and assigning a new value.
Unit-1 Page 18
Python For Data Science

Example:
lst=[4,7,6,8,9,3]
print( lst) # [4,7,6,8,9,3]
lst[2]=5 # updates 2nd element in
the list
lst # [4,7,5,8,9,3]
print( lst[2:5]=10,11,12)# update 2nd element to 4th
element in the list
print( lst) # [4,7,10,11,12,3]
Deleting an element from the list can be done using ‘del’ statement. The
del statement takes the position number of the element to be deleted.
Example:
lst=[5,7,1,8,9,6]
del lst[3] # delete 3rd element from the
list i.e., 8 print lst # [5,7,1,9,6]
If we want to delete entire list, we can give statement like del lst.
Concatenation of Two lists:
We can simply use „+‟ operator on two lists to join them. For example, „x‟
and „y‟ are two lists. If we wrte x+y, the list „y‟ is joined at the end of the list
„x‟.
Example:
x=[10,20,32,15,16]
y=[45,18,78,14,86]
print (x+y) # [10,20,32,15,16,45,18,78,14,86]
Membership in Lists:
We can check if an element is a member of a list by using „in‟ and „not
in‟ operator. If the element is a member of the list, then „in‟ operator returns
True otherwise returns False. If the element is not in the list, then „not in‟
operator returns True otherwise returnsFalse.
Example:
x=[10,20,30,45,5]
a=20
print a in x # True a=25
print a in x # Falsea=45

Unit-1 Page 19
Python For Data Science

print a not in x # False a=40


print a not in x # True
Built-in List Functions & Methods
Python includes the following list functions −

Sr.No. Function with Description

1 Cmp(list1,list2) Compares elements of both lists.

2 Len (list) Gives the total length of the list.

3 Max(list) Returns item from the list with max value.

4 Min(list) Returns item from the list with min value.

5 List(seq) Converts a tuple into list.

Python includes following list methods

Sr.No. Methods with Description

1 List.append(obj) Appends object obj to list

2 List.count(obj) Returns count of how many times obj occurs in


list

3 List.extend(seq) Appends the contents of seq to list

4 List.index(obj) Returns the lowest index in list that obj appears

5 List.insert(index,obj) Inserts object obj into list at offset index

6 List.pop(obj=list[-1]) Removes & returns last object or obj from


list

Unit-1 Page 20
Python For Data Science

7 List.remove(obj) Removes object obj from list

8 List.reverse() Reverses objects of list in place

9 List.sort([func]) Sorts objects of list, use compare func if


given

Nested Lists:
A list within another list is called a nested list. We know that a list
contains several elements. When we take a list as an element in another list, then
that list is called a nested list.
Example:
a=[10,20,30]
b=[45,65,a]
print b # display [ 45, 65, [ 10, 20, 30 ] ]
print b[1] # display 65
print b[2] # display [ 10, 20, 30 ]
print b[2][0] # display 10
print b[2][1] # display 20 print
b[2][2] # display 30 for x in
b[2]:
print( x); # display 10 20 30

Unit-1 Page 21
Python For Data Science

PYTHON TUPLES

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like
lists. The differences between tuples and lists are, the tuples cannot be changed
unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values.
Ex:

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

Accessing Values in Tuples


To access values in tuple, use the square brackets for slicing along with the index
or indices to obtain value available at that index.
For example −

tup1 = ('physics', 'chemistry', 1997, 2000);


tup2 = (1, 2, 3, 4, 5, 6, 7 );
print ("tup1[0]: ", tup1[0]);
print ("tup2[1:5]: ", tup2[1:5]);

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

tup1[0]: physics
tup2[1:5]: (2, 3, 4, 5)

Updating Tuples
We cannot update or change the values of tuple elements

tup1 = (12, 34.56);

Unit-1 Page 22
Python For Data Science

tup2 = ('abc', 'xyz');


# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print (tup3)

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

(12, 34.56, 'abc', 'xyz')

Delete Tuple Elements


Removing individual tuple elements is not possible. We can remove an entire
tuple, by using the del statement.
For example −

tup = ('physics', 'chemistry', 1997, 2000);


print (tup)
del tup;
print ("After deleting tup : ");
print (tup);

This produces the following result. Note an exception raised, this is because
after del tup tuple does not exist any more −

('physics', 'chemistry', 1997, 2000)


After deleting tup :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print (tup);
NameError: name 'tup' is not defined

Unit-1 Page 23
Python For Data Science

Basic Tuples Operations


Tuples use + for concatenation and * for repetition just like strings.

Python Expression Results Description

len((1, 2, 3)) 3 Length

(1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) Concatenation

('Hi!',) * 4 ('Hi!', 'Hi!', 'Hi!', 'Hi!') Repetition

3 in (1, 2, 3) True Membership

for x in (1, 2, 3): print x, 123 Iteration

Built-in Tuple Functions Python includes the following tuple functions

Sr.No. Function with Description

1 Cmp(tuple1,tuple2) Compares elements of both tuples.

2 Len(tuple) Gives the total length of the tuple.

3 Max(Tuple) Returns item from the tuple with max


value.

4 Min(Tuple) Returns item from the tuple with min


value.

5 Tuple(seq) Converts a list into tuple.

Unit-1 Page 24
Python For Data Science

Set:

Set is another data structure supported by python. Technically a set is a


mutable and an unordered collection of items. This means that we can easily
add or remove items from it.
Creating a Set:
A set is created by placing all the elements inside curly brackets {}.
Separated bycomma or by using the built-in function set( ).
Syntax:
Set_variable_name={var1, var2, var3, var4, …….}

Example:
s={1, 2.5, “abc” }
print s # display set( [ 1, 2.5, “abc” ] )

Converting a list into set:


A set can have any number of items and they may be of different data
types. set()
function is used to converting list into set.

Converting a list into set:


A set can have any number of items and they may be of different data
types. set()

s=set( [ 1, 2.5, “abc” ] print s # display set( [ 1,


2.5, “abc” ] )
function is used to converting list into set.

We can also convert tuple or string into set.


tup= ( 1, 2, 3, 4, 5 )
print( set(tup)) # set( [ 1, 2, 3, 4, 5 ] ) str= “MOTHILAL”
print( str) # set( [ 'i', 'h', 'm', 't', 'o' ] )

Unit-1 Page 25
Python For Data Science

Sno Operation Resul


t
1 len(s) number of elements in set s (cardinality)
2 x in s test x for membership in s
3 x not in s test x for non-membership in s
s.issuperset(t)
4 test whether every element in t is in s
(or)
s >= t
Returns True if two sets are equivalent and
5 s==t
returns False.
Returns True if two sets are not
6 s!=t equivalent and returns False.
s.union(t)
7 new set with elements from both s and t
(or)
s|t
s.intersection(t)(or)
8 s&t new set with elements common to s and t

Sno Operation Resul


t
s.difference(t)(or)
9 s-t new set with elements in s but not in t
s.symmetric_difference(t) (or)
10 s ^ t new set with elements in either s or t but not
both
11 s.copy() new set with a shallow copy of s
12 s.update(t) return set s with elements added from t
13 s.intersection_update(t) return set s keeping only elements also
found in t
14 s.difference_update(t) return set s after removing elements found
in t
15 s.symmetric_difference_up return set s with elements from s or t but not
date(t) both
16 s.add(x) add element x to set s
17 s.remove(x) remove x from set s; raises KeyError if not
present

Unit-1 Page 26
Python For Data Science

18 s.discard(x) removes x from set s if present


remove and return an arbitrary element
19 s.pop() from s; raises KeyError if empty
20 s.clear() remove all elements from set s
21 max(s) Returns Maximum value in a set
22 min(s) Returns Minimum value in a set
Return a new sorted list from the
23 sorted(s) elements in the set.

PYTHON DICTIONARY
Each key is separated from its value by a colon (:), the items are separated by
commas, and the whole thing is enclosed in curly braces. An empty dictionary
without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be.
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets along with
the key to obtain its value. Following is a simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


print ("dict['Name']: ", dict['Name'])
print( "dict['Age']: ", dict['Age'])

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

dict['Name']: Zara
dict['Age']: 7
Updating Dictionary: You can update a dictionary by adding a new entry or
modifying an existing entry, or deleting an existing entry as sh own below in the
simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


dict['Age'] = 8; # update existing entry

Unit-1 Page 27
Python For Data Science

dict['School'] = "DPS School"; # Add new entry


print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

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

dict['Age']: 8
dict['School']: DPS School
Delete Dictionary Elements
You can either remove individual dictionary elements or clear the entire contents
of a dictionary. To remove an entire dictionary, just use the del statement.
Following is a simple example −

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}


del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

This produces the following result. Note that an exception is raised because
after del dict dictionary does not exist any more −

dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
Print("dict['Age']: ", dict['Age']);
TypeError: 'type' object is unsubscriptable

Unit-1 Page 28
Python For Data Science

Built-in Dictionary Functions & Methods


Python includes the following dictionary functions −

Sr.No. Function with Description

1 Cmp(dict1,dict2) Compares elements of both dict.

2 Len(dict) Gives the total length of the dictionary.

3 Str(dict) Produces a printable string representation of a


dictionary

4 Type(Variable) Returns the type of the passed variable.

Python includes following dictionary methods −

Sr.No. Methods with Description

1 Dict.clear() Removes all elements of dictionary dict

2 Dict.copy() Returns a shallow copy of dictionary dict

3 Dict.fromkeys() Create a new dictionary with keys from seq

4 Dict.get(key,default=none ) For key key, returns value or default if


key not in dictionary

5 Dict.has_key(key)Returns true if key in

Unit-1 Page 29
Python For Data Science

dictionary dict, false otherwise

6 Dict.items() Returns a list of dict's (key, value) tuple pairs

7 Dict.keys() Returns list of dictionary dict's keys

8 Dict.setdefault(key,default=none) Similar to get(), but will set


dict[key]=default if key is not already in dict

9 Dict.update(dict2) Adds dictionary dict2's key-values pairs


to dict

10 Dict.values() Returns list of dictionary dict's values

Data Type Conversion:

Sometimes, you may need to perform conversions between the built-in


types. To convert between types, you simply use the type name as a function.
For example, it is not possible to perform “2”+4 since one operand is integer
and the other is string type. To perform this we have convert string to integer
i.e., int(“2”) + 4 = 6.
There are several built-in functions to perform conversion from one
data type to another. These functions return a new object representing the
converted value.
Function Descripti
on
int(x [,base]) Converts x to an integer.
long(x [,base] ) Converts x to a long integer.
float(x) Converts x to a floating-point number.
complex(real Creates a complex number.
[,imag])
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.

Unit-1 Page 30
Python For Data Science

list(s) Converts s to a list.


set(s) Converts s to a set.
dict(d) Creates a dictionary, d must be a sequence of (key,
value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.

PYTHON - BASIC OPERATORS


Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator.
Types of Operator
Python language supports the following types of operators.

 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
PYTHON ARITHMETIC OPERATORS
Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30


- Subtraction Subtracts right hand operand from left hand a – b = -10
operand.
* Multiplies values on either side of the operator a * b = 200
Multiplication

Unit-1 Page 31
Python For Data Science

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand b%a=0


and returns remainder
** Exponent Performs exponential (power) calculation on a**b =10 to
operators the power
20
// Floor Division 9//2 = 4 and
9.0//2.0 =
4.0, -11//3 =
-4, -11.0//3
= -4.0

Example :
a = 21
b = 10
c=0
c=a+b
print ("Line 1 - Value of c is ", c)
c=a-b
print ("Line 2 - Value of c is ", c)
c=a*b
print ("Line 3 - Value of c is ", c)
c=a/b
print ("Line 4 - Value of c is ", c)
c=a%b
print( "Line 5 - Value of c is ", c)
a=2
b=3
c = a**b
print ("Line 6 - Value of c is ", c)
a = 10
b=5
c = a//b
print ("Line 7 - Value of c is ", c)

Unit-1 Page 32
Python For Data Science

When you execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2

PYTHON COMPARISON OPERATORS


These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.
Assume variable a =10 and variable b = 20, then

Operator Description Example

== If the values of two operands are equal, then the (a == b) is


condition becomes true. not true.
!= If values of two operands are not equal, then condition (a != b) is
becomes true. true.
<> If values of two operands are not equal, then condition (a <> b) is
becomes true. true. This is
similar to !=
operator.
> If the value of left operand is greater than the value of (a > b) is not
right operand, then condition becomes true. true.
< If the value of left operand is less than the value of (a < b) is
right operand, then condition becomes true. true.

>= If the value of left operand is greater than or equal to (a >= b) is


the value of right operand, then condition becomes not true.
true.

Unit-1 Page 33
Python For Data Science

<= If the value of left operand is less than or equal to the (a <= b) is
value of right operand, then condition becomes true. true.

Example
a = 21
b = 10
c=0
if ( a == b ):
print ("Line 1 - a is equal to b")
else:
print ("Line 1 - a is not equal to b")
if ( a != b ):
print ("Line 2 - a is not equal to b")
else:
print ("Line 2 - a is equal to b")
if ( a <> b ):
print ("Line 3 - a is not equal to b")
else:
print ("Line 3 - a is equal to b")
if ( a < b ):
print ("Line 4 - a is less than b" )
else:
print ("Line 4 - a is not less than b")
if ( a > b ):
print ("Line 5 - a is greater than b")
else:
print ("Line 5 - a is not greater than b")
a = 5;
b = 20;
if ( a <= b ):
print ("Line 6 - a is either less than or equal to b")
else:
print ("Line 6 - a is neither less than nor equal to b")
if ( b >= a ):
print ("Line 7 - b is either greater than or equal to b")
else:
print ("Line 7 - b is neither greater than nor equal to b")

Unit-1 Page 34
Python For Data Science

When you execute the above program it produces the following result −
Line 1 - a is not equal to b
Line 2 - a is not equal to b
Line 3 - a is not equal to b
Line 4 - a is not less than b
Line 5 - a is greater than b
Line 6 - a is either less than or equal to b
Line 7 - b is either greater than or equal to b

PYTHON ASSIGNMENT OPERATORS


Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example

= Assigns values from right side operands to left side c=a+b


operand assigns
value of a
+ b into c

+= Add It adds right operand to the left operand and assign the c += a is
AND result to left operand equivalent
to c = c +
a

-= Subtract It subtracts right operand from the left operand and assign c -= a is
AND the result to left operand equivalent
to c = c –
a

*= Multiply It multiplies right operand with the left operand and c *= a is


equivalent

Unit-1 Page 35
Python For Data Science

AND assign the result to left operand to c = c *


a

/= Divide It divides left operand with the right operand and assign
AND the result to left operand c /= a is
equivalent
to c = c /
ac /= a is
equivalent
to c = c / a

%= It takes modulus using two operands and assign the result c %= a is


Modulus to left operand equivalent
AND to c = c %
a

**= Performs exponential (power) calculation on operators c **= a is


Exponent and assign value to the left operand equivalent
AND to c = c **
a

//= Floor It performs floor division on operators and assign value to c //= a is
Division the left operand equivalent
to c = c //
a

Example
Assume variable a holds 10 and variable b holds 20, then −
a = 21
b = 10
c=0
c=a+b
print( "Line 1 - Value of c is ", c)
c += a

Unit-1 Page 36
Python For Data Science

print ("Line 2 - Value of c is ", c )


c *= a
print ("Line 3 - Value of c is ", c )
c /= a
print ("Line 4 - Value of c is ", c )
c =2
c %= a
print ("Line 5 - Value of c is ", c)
c **= a
print ("Line 6 - Value of c is ", c)
c //= a
print ("Line 7 - Value of c is ", c)
When you execute the above program, it produces the following result −
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864

PYTHON BITWISE OPERATORS


Bitwise operator works on bits and performs bit by bit operation. Assume if a =
60; and b = 13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language

Unit-1 Page 37
Python For Data Science

Operator Description Example


& Binary AND Operator copies a bit to the result if it exists in (a & b)
both operands (means
0000 1100)

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61


(means
0011 1101)

^ Binary XOR It copies the bit if it is set in one operand but (a ^ b) = 49


not both. (means
0011 0001)
~ Binary Ones (~a ) = -61
Complement (means
1100 0011
in 2's
It is unary and has the effect of 'flipping' bits. complement
form due to
a signed
binary
number.
<< Binary Left The left operands value is moved left by the a << 2 =
Shift number of bits specified by the right operand. 240 (means
1111 0000)

>> Binary Right The left operands value is moved right by the a >> 2 = 15
Shift number of bits specified by the right operand. (means
0000 1111)

Unit-1 Page 38
Python For Data Science

Example

a= 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b; # 12 = 0000 1100
print( "Line 1 - Value of c is ", c)
c = a | b; # 61 = 0011 1101
print ("Line 2 - Value of c is ", c)
c = a ^ b; # 49 = 0011 0001
print( "Line 3 - Value of c is ", c)
c = ~a; # -61 = 1100 0011
print("Line 4 - Value of c is ", c)
c = a << 2; # 240 = 1111 0000
print ("Line 5 - Value of c is ", c)
c = a >> 2; # 15 = 0000 1111
print ("Line 6 - Value of c is ", c)
When you execute the above program it produces the following result –
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15

PYTHON LOGICAL OPERATORS


There are following logical operators supported by Python language. Assume
variable a holds 10 and variable b holds 20 then

Operator Description Example

Unit-1 Page 39
Python For Data Science

and Logical If both the operands are true then condition (a and b) is
AND becomes true. true.

or Logical OR If any of the two operands are non-zero then (a or b) is


condition becomes true. true.

not Logical NOT Used to reverse the logical state of its Not(a and b)
operand. is false.

PYTHON MEMBERSHIP OPERATORS


Python’s membership operators test for membership in a sequence, such as
strings, lists, or tuples. There are two membership operators as explained below −

Operator Description Example

in Evaluates to true if it finds a variable in x in y, here in results in


the specified a 1 if x is a member of
sequence and false otherwise. sequence y.

not in Evaluates to true if it does not finds a x not in y, here not in


variable in the specified sequence and results in a 1 if x is not a
false otherwise. member of sequence y.

Example
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print ("Line 1 - a is available in the given list")
else:
print ("Line 1 - a is not available in the given list")
if ( b not in list ):
print ("Line 2 - b is not available in the given list")
else:
Unit-1 Page 40
Python For Data Science

print ("Line 2 - b is available in the given list")


a=2
if ( a in list ):
print ("Line 3 - a is available in the given list")
else:
print ("Line 3 - a is not available in the given list")
When you execute the above program it produces the following result −
Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
Line 3 - a is available in the given list

PYTHON IDENTITY OPERATORS


Identity operators compare the memory locations of two objects. There are two
Identity operators explained below –

Operato Description Example


r

is Evaluates to true if the variables on


either side of x is y, here is results in 1 if
the operator point to the same object id(x) equals id(y).
and false otherwise.
is not Evaluates to false if the variables on
either side of x is not y, here is not results in
the operator point to the same object 1 if id(x) is not equal to id(y).
and true otherwise.

Example
a = 20
b = 20
if ( a is b ):
print ("Line 1 - a and b have same identity")
else:
print ("Line 1 - a and b do not have same identity")
if ( id(a) == id(b) ):

Unit-1 Page 41
Python For Data Science

print ("Line 2 - a and b have same identity")


else:
print ("Line 2 - a and b do not have same identity")
b = 30
if ( a is b ):
print ("Line 3 - a and b have same identity")
else:
print ("Line 3 - a and b do not have same identity")
if ( a is not b ):
print ("Line 4 - a and b do not have same identity")
else:
print ("Line 4 - a and b have same identity")
When you execute the above program it produces the following result −
Line 1 - a and b have same identity
Line 2 - a and b have same identity
Line 3 - a and b do not have same identity
Line 4 - a and b do not have same identity

PYTHON OPERATORS PRECEDENCE


The following table lists all operators from highest precedence to lowest.

Sr.No. Operator & Description

1 ** Exponentiation (raise to the power)

2 ~ + - Complement, unary plus and minus (method names


for the last two are +@ and -@)

3 * / % // Multiply, divide, modulo and floor division

4 +- Addition and subtraction

5 >> << Right and left bitwise shift

Unit-1 Page 42
Python For Data Science

6 & Bitwise 'AND'

7 ^| Bitwise exclusive `OR' and regular `OR'

8 <= < > >= Comparison operators

9 <> == != Equality operators

10 = %= /= //= -= += *= **= Assignment operators

11 is is not Identity operators

12 in not in Membership operators

13 not or and Logical operators

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has


higher precedence than +, so it first multiplies 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom.
Example
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print ("Value of (a + b) * c / d is ", e)
e = ((a + b) * c) / d # (30 * 15 ) / 5
print( "Value of ((a + b) * c) / d is ", e)
e = (+ b) * (c / d); # (30) * (15/5)
print ("Value of (a + b) * (c / d) is ", e)
e = a + (b * c) / d; # 20 + (150/5)
print ("Value of a + (b * c) / d is ", e)

Unit-1 Page 43
Python For Data Science

When you execute the above program, it produces the following result −

Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50

Unit-1 Page 44
Python For Data Science

Unit-1 Page 45
Python For Data Science

PYTHON - DECISION MAKING


Decision making is about deciding the order of execution of statements based on
certain conditions. (or repeat a group of statements until certain specified
conditions are met.)
Decision structures evaluate multiple expressions which produce TRUE or
FALSE as outcome. You need to determine which action to take and which
statements to execute if outcome is TRUE or FALSE otherwise.
Following is the general form of a typical decision making structure

Python programming language provides following types of decision making


statements.
1. If statement
2. If…Else statement
3. Nested if statement.
1. If Statement: An if statement consists of a boolean expression followed by one
or more statements.

Syntax
if expression:
statement(s)

Unit-1 Page 46
Python For Data Science

Ex: program to check the number is even or odd


n=10
if n%2==0:
print(n, "is even")
if n%2 != 0:
print(n, "is odd")
OUTPUT: is even.
2. If ….. Else statement: An if statement can be followed by an optional else
statement, which executes when the boolean expression is FALSE.
An else statement can be combined with an if statement.
The syntax of the if...else statement is −
if expression:
statement(s)
else:
statement(s)
Flow Diagram

Unit-1 Page 47
Python For Data Science

Example
marks=76
if marks>=45:
print("passed")
print("congratulations!!")
else:
print("failed")
print("good luck next time")

Output: passed
congratulations
The elif Statement
The elif statement is an abbreviation of ‘Else if’. It allows you to check the
conditions one after another. The statement associated with the first true condition
is executed. There is no limit of elif statements ,but the Last branch has to be an
else statement.
syntax
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
Ex:
marks = 75
if marks >= 80:
print("grade a")
elif marks>= 60:
print("grade b")
elif marks>= 40:
print("grade c")
else:
print("failed")
Unit-1 Page 48
Python For Data Science

Output:
Grade B

Nested If statement: You can use one if or else if statement inside


another if or else if statement(s).
Syntax:

if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
elif expression4:
statement(s)
else:
statement(s)

Ex: program to check the number is even or odd if it is positive

x=56
if x>=0: # outer if
if x%2==0: #inner if
print(x, "is even number")
else:
print(x, "is odd number")
else:
print(x, "is negative")
Output: is even number.

Unit-1 Page 49
Python For Data Science

LOOPS
In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on. There may be a
situation when you need to execute a block of code several number of times.
A loop statement allows us to execute a statement or group of statements multiple
times.

Python programming language provides following types of loops


1. While Loop
2. For loop
3. Nested loop

WHILE LOOP: A While loop repeats a statement or group of statements while a


given condition is TRUE. It tests the condition before executing the loop body.
Syntax:
while expression:
statement(s)

Unit-1 Page 50
Python For Data Science

Example
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!")
When the above code is executed, it produces the following result −

The count is: 0


The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
FOR LOOP: For Loop executes a sequence of statements multiple times.
Syntax
for iterating_var in sequence:
statements(s)

Unit-1 Page 51
Python For Data Science

Example
for letter in 'Python':
print ('Current Letter :', letter)
print ("Good bye!")
When the above code is executed, it produces the following result −

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

NESTED LOOP: You can use one or more loop inside any another while, for or
do..while loop.
Syntax:

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)

while expression:
while expression:
statement(s)
statement(s)

Example
x=1
while x<=5:
y=1
while y<=x:

Unit-1 Page 52
Python For Data Science

print(y*x, end = " ")


y+=1
print()
x+=1
When the above code is executed, it produces following result –
1
24
369
4 8 12 16
5 10 15 20 25

LOOP CONTROL STATEMENTS

Loop control statements change execution from its normal sequence. Python
supports the following control statements.
1. Break statement.
2. Continue statement.
3. Pass statement.

BREAK STATEMENT: It terminates the loop statement and transfers execution


to the statement immediately following the loop. The break statement can be used
in both while and for loops.
Example
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter :', letter)
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t

Unit-1 Page 53
Python For Data Science

CONTINUE STATEMENT: Causes the loop to skip the remainder of its body
and immediately retest its condition prior to reiterating. The continue statement
can be used in both while and for loops.
Example
for letter in 'Python': # First Example
if letter == 'h':
continue
print ('Current Letter :', letter)
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n

PASS STATEMENT: The pass statement is a null operation; nothing happens


when it executes. The pass is also useful in places where your code will
eventually go, but has not been written yet.
Example
for letter in 'Python':
if letter == 'h':
pass
print ('This is pass block')
print ('Current Letter :', letter)
print ("Good bye!")
When the above code is executed, it produces following result −
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye!

Unit-1 Page 54
Python For Data Science

Mathematical Functions
Python includes following functions that perform mathematical calculations.

Sr.No. Function & Returns ( description )

1 Abs(x)The absolute value of x: the (positive) distance between x


and zero.

2 Ceil(x) The ceiling of x: the smallest integer not less


than x

3 Cmp(x,y) -1 if x < y, 0 if x == y, or 1 if x > y

4 Exp(x) The exponential of x: ex

5 Fabs(x) The absolute value of x.

6 Floor(x) The floor of x: the largest integer not greater


than x

7 Log(x) The natural logarithm of x, for x> 0

8 Log10(x) The base-10 logarithm of x for x> 0.

9 Max(x1,x2,..) The largest of its arguments: the value closest


to positive infinity

10 Min(x1,x2,...) The smallest of its arguments: the value closest


to negative infinity

11 Modf(x) The fractional and integer parts of x in a two-item tuple.


Both parts have the same sign as x. The integer part is returned as a
float.

12 Pow(x,y) The value of x**y.

13 Round(x[,n]) x rounded to n digits from the decimal point. Python


rounds away from zero as a tie-breaker: round(0.5) is 1.0 and
round(-0.5) is -1.0.

Unit-1 Page 55
Python For Data Science

14 Sqrt(x) The square root of x for x > 0


Random Number Functions
Random numbers are used for games, simulations, testing, security, and privacy
applications. Python includes following functions that are commonly used.

1. Choice(seq):The method choice() returns a random item from a list, tuple, or


string.
import random
print ("choice([1, 2, 3, 5, 9]):", random.choice([1, 2, 3, 5, 9]))
print ("choice('A String'):", random.choice('A String'))

When we run above program, it produces following result −


choice([1, 2, 3, 5, 9]) : 2
choice('A String') : n

2.randrange([start,]stop[,step]): The method randrange() returns a randomly


selected element from range(start, stop, step).
import random
# Select an even number in 100 <= number < 1000
print ("randrange(100, 1000, 2) : ", random.randrange(100, 1000, 2))
# Select another number in 100 <= number < 1000
print ("randrange(100, 1000, 3) : ", random.randrange(100, 1000, 3))
When we run above program, it produces following result −
randrange(100, 1000, 2) : 976
randrange(100, 1000, 3) : 520

3.random() : The method random() returns a random float r, such that 0 is less
than or equal to r and r is less than 1.
import random
# First random number
print ("random() : ", random.random())
# Second random number
print ("random() : ", random.random())
When we run above program, it produces following result −
random() : 0.281954791393
Unit-1 Page 56
Python For Data Science

4.Seed([x]): The method seed() sets the integer starting value used in generating
random numbers.
import random
random.seed( 10 )
print ("Random number with seed 10 : ", random.random())
# It will generate same random number
random.seed( 10 )
print ("Random number with seed 10 : ", random.random())
# It will generate same random number
random.seed( 10 )
print ("Random number with seed 10 : ", random.random())
When we run above program, it produces following result −
Random number with seed 10 : 0.57140259469
Random number with seed 10 : 0.57140259469
Random number with seed 10 : 0.57140259469

5.Shuffle(lst): The method shuffle() randomizes the items of a list in place.


import random
list = [20, 16, 10, 5];
random.shuffle(list)
print ("Reshuffled list : ", list)
random.shuffle(list)
print ("Reshuffled list : ", list)
When we run above program, it produces following result −
Reshuffled list : [16, 5, 10, 20]
Reshuffled list : [16, 5, 20, 10]

6.Uniform(x,y): The method uniform() returns a random float r, such that x is


less than or equal to r and r is less than y.
import random
print ("Random Float uniform(5, 10) : ", random.uniform(5, 10))
print ("Random Float uniform(7, 14) : ", random.uniform(7, 14))
Let us run the above program, this will produce the following result −

Unit-1 Page 57
Python For Data Science

Random Float uniform(5, 10) : 5.52615217015


Random Float uniform(7, 14) : 12.5326369199

FUNCTIONS:
A function is a block of organized, reusable code that is used to perform
a single, related action.
 Once a function is written, it can be reused as and when required. So,
functions are also called reusable code.
 Functions provide modularity for programming. A module represents a
part of the program. Usually, a programmer divides the main task into
smaller sub tasks called modules.
 Code maintenance will become easy because of functions. When a new
feature has to be added to the existing software, a new function can be
written and integrated into the software.
 When there is an error in the software, the corresponding function can be
modified without disturbing the other functions in the software.
 The use of functions in a program will reduce the length of the program.
As you already know, Python gives you many built-in functions like sqrt( ),
etc. but you can also create your own functions. These functions are called
user-defined functions.

Difference between a function and a method:


A function can be written individually in a python program. A function
is called using its name. When a function is written inside a class, it becomes a
„method‟. A method is called using object name or class name. A method is
called using one of the following ways:
Objectname.methodname()
Classname.methodname()

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

Unit-1 Page 58
Python For Data Science

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:
def add(a,b):
"""This function sum the
numbers""" c=a+b
pri
nt c
ret
urn
Here, „def’ represents starting of function. „add’ is function name. After
this name, parentheses ( ) are compulsory as they denote that it is a function
and not a variable or something else. In the parentheses we wrote two
variables „a‟ and „b‟ these variables are called „parameters‟. A parameter is a
variable that receives data from outside a function. So, this function receives
two values from outside and those are stored in the variables „a‟ and
„b‟. After parentheses, we put colon (:) that represents the beginning of the
function body. The function body contains a group of statements called
„suite‟.

Unit-1 Page 59
Python For Data Science

Calling Function:
A function cannot run by its own. It runs only when we call it. So, the
next step is to call function using its name. While calling the function, we
should pass the necessary values to the function in the parentheses as:
add(5,12)
Here, we are calling „add‟ function and passing two values 5 and 12 to
that function.
When this statement is executed, the python interpreter jumps to the function
definition and copies the values 5 and 12 into the parameters „a‟ and „b‟
respectively.

Example:
def add(a,b):

"""This function sum the


numbers"""c=a+b

print c
add(5,12) # 17

Returning Results from a function:

We can return the result or output from the function using a „return‟
statement in the function body. When a function does not return any result, we
need not write the return statement in the body of the function.

Q) Write a program to find the sum of two numbers and return the result
from the function.
def add(a,b):

"""This function sum the


numbers"""c=a+b

return c
print add(5,12) # 17

Unit-1 Page 60
Python For Data Science

Returning multiple values from a function:


A function can returns a single value in the programming languages
like C, C++ and JAVA. But, in python, a function can return multiple values.
When a function calculates multiple results and wants to return the results, we
can use return statement as:
return a, b, c
Here, three values which are in „a‟, „b‟ and „c‟ are returned. These values are
returned bythe function as a tuple. To grab these values, we can three variables
at the time of calling the function as:
x, y, z = functionName( )
Here, „x‟, „y‟ and „z‟ are receiving the three values returned by the function.

def calc(a,b):
c=a+b
d=a-b
e=a*b
return c,d,e
x,y,z=calc(5,8)
print "Addition=",x
print "Subtraction=",y
print "Multiplication=",z
Example:
Functions are First Class Objects:

In Python, functions are considered as first class objects. It means we can use
functions as perfect objects. In fact when we create a function, the Python
interpreter internally creates an object. Since functions are objects, we can
pass a function to another function just like we pass an object (or value) to a
function. The following possibilities are:
 It is possible to assign a function to a variable.
 It is possible to define one function inside another function.
 It is possible to pass a function as parameter to another function.
 It is possible that a function can return another
function. To understand these points, we will take a
few simple programs.
Unit-1 Page 61
Python For Data Science

Q) A python program to see how to assign a function to a variable.


Outpu
def display(st):
return"hai"+st t:
x=display("cse") haicse
print x

Q) A python program to know how a function can return another function.

def display():
def message():
return "how r u?"
return message
fun=display()
print fun()
Output: how r u

Pass by Value:
Pass by value represents that a copy of the variable value is passed to
the function and any modifications to that value will not reflect outside the
function. In python, the values are sent to functions by means of object
references. We know everything is considered as an object in python. All
numbers, strings, tuples, lists and dictionaries are objects.
If we store a value into a variable as:
x=10
In python, everything is an object. An object can be imagined as a
memory block where we can store some value. In this case, an object with the
value „10‟ is created in memory for which a name „x‟ is attached. So, 10 is the
object and „x‟ is the name or tag given to that object. Also, objects are created
on heap memory which is a very huge memory that depends on the RAM of
our computer system.

Unit-1 Page 62
Python For Data Science

def modify(x):
x=15
print "inside",x,id(x)
x=10
modify(x)
print "outside",x,id(x)
Example: A Python program to pass an integer to a function and modify it.
Output:

inside 15 6356456
outside 10 6356516

From the output, we can understand that the value of „x‟ in the function is 15
and that is not available outside the function. When we call the modify( )
function and pass „x‟ as:
modify(x)
We should remember that we are passing the object references to the modify(
) function. The object is 10 and its references name is „x‟. This is being
passed to the modify( ) function. Inside the function, we are using:
x=15
This means another object 15 is created in memory and that object is
referenced by the name „x‟. The reason why another object is created in the
memory is that the integer objects are immutable (not modifiable). So in the
function, when we display „x‟ value, it will display 15. Once we come outside
the function and display „x‟ value, it will display numbers of „x‟ inside and
outside the function, and we see different numbers since they are different
objects.
In python, integers, floats, strings and tuples are immutable. That means
their data cannot be modified. When we try to change their value, a new
object is created with the modified value.

Unit-1 Page 63
Python For Data Science

Fig. Passing Integer to a Function


Pass by Reference:
Pass by reference represents sending the reference or memory address
of the variable to the function. The variable value is modified by the function
through memory address and hence the modified value will reflect outside the
function also.
In python, lists and dictionaries are mutable. That means, when we
change their data, the same object gets modified and new object is not created.
In the below program, we are passing a list of numbers to modify ( ) function.
When we append a new element to the list, the same list is modified and hence
the modified list is available outside the function also.
Example: A Python program to pass a list to a function and modify it.

def modify(a):
a.append(5)
print "inside",a,id(a)
a=[1,2,3,4]
modify(a)
print "outside",a,id(a)
Output:
inside [1, 2, 3, 4, 5] 45355616
outside [1, 2, 3, 4, 5] 45355616
In the above program the list „a‟ is the name or tag that represents the list
object.
Before calling the modify( ) function, the list contains 4 elements as: a=[1,2,3,4]

Unit-1 Page 64
Python For Data Science

Inside the function, we are appending a new element „5 „5‟‟ to the list.
Since, lists are mutable, adding a new element to the same object is possible.
Hence, append( ) method modifies the same object.

Formal and Actual Arguments:


When a function is defined, it may have some parameters. These
parameters are useful to receive values from outside of the function. They are
called „formal arguments
arguments‟. When we call the function, we should pass data or
values to the function. These values are called „actual arguments‟.
arguments In the
following code, „a‟ and „b
„b‟ are formal arguments and „x‟ and
„y‟ are actual arguments.
Example:
def add(a,b): # a, b are formal
arguments c=a+b
print
c
x,y=1
0,15
add(x,y) # x, y are actual arguments

Unit-1 Page 65
Python For Data Science

The actual arguments used in a function call are of 4 types:


a) Positional arguments
b) Keyword arguments
c) Default arguments
d) Variable length arguments
a) Positional Arguments:
These are the arguments passed to a function in correct positional order.
Here, the number of arguments and their position in the function definition
should match exactly with the number and position of argument in the
function call.
def attach(s1,s2):
s3=s1+s2
print s3
attach("New","Delhi") #Positional arguments

This function expects two strings that too in that order only. Let‟s assume that
this function attaches the two strings as s1+s2. So, while calling this function,
we are supposed to pass only two strings as: attach("New","Delhi")
The preceding statements displays the following output NewDelhi
Suppose, we passed "Delhi" first and then "New", then the result will be:
"DelhiNew". Also, if we try to pass more than or less than 2 strings, there will
be an error.

b) Keyword Arguments:
Keyword arguments are arguments that identify the parameters by their
names. For example, the definition of a function that displays grocery item
and its price can be written as:
def grocery(item, price):
At the time of calling this function, we have to pass two values and we can
mention which value is for what. For example,
grocery(item=’sugar’, price=50.75)
Here, we are mentioning a keyword „item‟ and its value and then another
keyword „price‟ and its value. Please observe these keywords are nothing but
the parameter names which receive these values. We can change the order of
the arguments as:

Unit-1 Page 66
Python For Data Science

grocery(price=88.00, item=’oil’)
In this way, even though we change the order of the arguments, there will not
be any problemas the parameter names will guide where to store that value.
def grocery(item,price):
print "item=",item
print "price=",price
grocery(item="sugar",price=50.75) # keyword arguments
grocery(price=88.00,item="oil") # keyword arguments

Output:
item=
sugar
price=
50.75
item= oil
price=
88.0
c) Default Arguments:
We can mention some default value for the function parameters in the
definition.
Let‟s take the definition of grocery( ) function as:
def grocery(item, price=40.00)
Here, the first argument is „item‟ whose default value is not mentioned. But
the second argument is „price‟ and its default value is mentioned to be 40.00.
at the time of calling this function, if we do not pass „price‟ value, then the
default value of 40.00 is taken. If we mention the „price‟ value, then that
mentioned value is utilized. So, a default argument is an argument that
assumes a default value if a value is not provided in the function call for that
argument.

Example: def grocery(item,price=40.00):


print
"item=",item
print
"price=",price
grocery(item="sugar",price=50.

Unit-1 Page 67
Python For Data Science

Output:

item=
sugar
price=
50.75
item= oil
price=
40.0
d) Variable Length Arguments:
Sometimes, the programmer does not know how many values a function may
receive. In that case, the programmer cannot decide how many arguments to
be given in the function definition. for example, if the programmer is writing
a function to add two numbers, he/she can write:
add(a,b)
But, the user who is using this function may want to use this function to find
sum of three numbers. In that case, there is a chance that the user may provide
3 arguments to this function as:
add(10,15,20)
Then the add( ) function will fail and error will be displayed. If the
programmer want to develop a function that can accept „n‟ arguments, that is
also possible in python. For this purpose, a variable length argument is used in
the function definition. a variable length argument is an argument that can
accept any number of values. The variable length argument is written with a
„*‟ symbol before it in the function definition as:
def add(farg, *args):
here, „farg‟ is the formal; argument and „*args‟ represents variable length
argument. We can pass 1 or more values to this „*args‟ and it will store them all
in a tuple.

Unit-1 Page 68
Python For Data Science

Example:
def add(farg,*args):
sum=0
for i in args:
sum=sum+i
print "sum is",sum+farg
add(5,10)
add(5,10,20)
add(5,10,20,30)

Output:
sum is 15
sum is 35
sum is 65
Recursive Functions:
A function that calls itself is known as „recursive function‟. For example, we
can write the factorial of 3 as:
factorial(3) = 3 *
factorial(2) Here,
factorial(2) = 2 *
factorial(1) And,
factorial(1) = 1 *
factorial(0)
Now, if we know that the factorial(0) value is 1, all the preceding
statements will evaluate and give the result as:
factorial(3) = 3 * factorial(2)
= 3 * 2 * factorial(1)
= 3 * 2 * 1 * factorial(0)
=3*2*1*1
=6
From the above statements, we can write the formula to calculate factorial of
any number „n‟ as:factorial(n) = n * factorial(n-1)

Unit-1 Page 69
Python For Data Science

Example-1:
def
factorial(
n): if
n==0:
resul
t=1
else:
result=n*factorial(n-
1) return result
for i in range(1,5):
print "factorial of ",i,"is",factorial(i)
Output:
factorial of 1 is 1
factorial of 2 is 2
factorial of 3 is 6
factorial of 4 is 24
Anonymous Function or Lambdas:
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.
Let‟s take a normal function that returns square of given value:

Unit-1 Page 70
Python For Data Science

def square(x):
return x*x
the same function can be written as anonymous function as:
lambda x: x*x
The colon (:) represents the beginning of the function that contains an
expression x*x. The syntax is:
lambda argument_list:
expression Example:
f=lambda x:x*x
value = f(5)
print (value)
The map() Function
The advantage of the lambda operator can be seen when it is used in
combination with the map() function. map() is a function with two arguments:
r = map(func, seq)
The first argument func is the name of a function and the second a sequence
(e.g. a list) seq. map() applies the function func to all the elements of the
sequence seq. It returns a new list with the elements changed by func
def fahrenheit(T):
return ((float(9)/5)*T + 32)
def celsius(T):
return (float(5)/9)*(T-32)
temp = (36.5, 37, 37.5,39)
F = map(fahrenheit, temp)
In the example above we haven't used lambda. By using lambda, we wouldn't
have had to
define and name the functions fahrenheit() and celsius(). You can see this in
the following interactive session:
>>> Celsius = [39.2, 36.5, 37.3, 37.8]
>>> Fahrenheit = map(lambda x: (float(9)/5)*x + 32, Celsius)
>>> print (Fahrenheit)
[102.56, 97.700000000000003, 99.140000000000001,
100.03999999999999]
>>> C = map(lambda x: (float(5)/9)*(x-32), Fahrenheit)
>>> print( C)
[39.200000000000003, 36.5, 37.300000000000004,
37.799999999999997]
map() can be applied to more than one list. The lists have to have the same

Unit-1 Page 71
Python For Data Science

length. map() will apply its lambda function to the elements of the argument
lists, i.e. it first applies to the elements with the 0th index, then to the elements
with the 1st index until the n-th index is reached:
>>> a = [1,2,3,4]
>>> b = [17,12,11,10]
>>> c = [-1,-4,5,9]
>>> map(lambda x,y:x+y, a,b) [18, 14, 14, 14]
>>> map(lambda x,y,z:x+y+z, a,b,c) [17, 10, 19, 23]
>>> map(lambda x,y,z:x+y-z, a,b,c) [19, 18, 9, 5]
We can see in the example above that the parameter x gets its values from the
list a, while ygets its values from b and z from list c.
Filtering
The function filter(function, list) offers an elegant way to filter out all the
elements of a list, for which the function function returns True. The function
filter(f,l) needs a function f as its first argument. f returns a Boolean value, i.e.
either True or False. This function will be applied to every element of the list
l. Only if f returns True will the element of the list be included in the result
list.
>>> fib = [0,1,1,2,3,5,8,13,21,34,55]
>>> result = filter(lambda x: x % 2, fib)
>>> print (result)
[1, 1, 3, 5, 13, 21, 55]
>>> result = filter(lambda x: x % 2 == 0, fib)
>>> print result [0, 2, 8, 34]
Reducing a List
The function reduce(func, seq) continually applies the function func() to the
sequence seq. It returns a single value.
If seq = [ s1, s2, s3, ... , sn ], calling reduce(func, seq) works like this:
 At first the first two elements of seq will be applied to func, i.e.
func(s1,s2) The list on which reduce() works looks now like this: [
func(s1, s2), s3, ... , sn ]
 In the next step func will be applied on the previous result and the
third element of the list, i.e. func(func(s1, s2),s3). The list looks like this
now: [ func(func(s1, s2),s3), ... , sn ]
 Continue like this until just one element is left and return this

Unit-1 Page 72
Python For Data Science

element as the result of reduce()


We illustrate this process in the following example:
>>> reduce(lambda x,y: x+y, [47,11,42,13])
113
The following diagram shows the intermediate steps of the calculation:

Examples of reduce ( )
Determining the maximum of a list of numerical values by using reduce:
>>> f = lambda a,b: a if (a > b) else b
>>> reduce(f, [47,11,42,102,13])
102
>>>
Calculating the sum of the numbers from 1 to 100:
>>> reduce(lambda x, y: x+y, range(1,101)) 5050
Function Decorators:
A decorator is a function that accepts a function as parameter and
returns a function. A decorator takes the result of a function, modifies the
result and returns it. Thus decorators are useful to perform some additional
processing required by a function.
The following steps are generally involved in creation of decorators:
 We should define a decorator function with another function name as
parameter.
 We should define a function inside the decorator function. This function
actually modifies or decorates the value of the function passed to the
decorator function.
 Return the inner function that has processed or decorated the value.

Unit-1 Page 73
Python For Data Science

Example-1:
def decor(fun):
def inner():
value=fun()
return value+2
return inner
def num():
return 10
result=decor(num)
print result()
Output:
12
To apply the decorator to any function, we can use ‘@’ symbol and decorator
name just above the function definition.
Example-2: A python program to create two
decorators. def decor1(fun):
def inner():
value=fun()
return value+2
return inner
def
decor2(fun):
def inner():
value=fun()
return value*2
return inner
def num():
return 10
result=decor1(decor2(num))
print result()

22
Function Generators:
A generator is a function that produces a sequence of results instead of a

Unit-1 Page 74
Python For Data Science

single value.
„yield‟ statement is used to return the value.
def mygen(n):
i=0
while i < n: yield i
i += 1
g=mygen(6)
for i in g:
print( i)
Output:
012345
Note: „yield‟ statement can be used to hold the sequence of results and return it.

Modules:
A module is a file containing Python definitions and statements. The
file name is the module name with the suffix.py appended. Within a module,
the module‟s name (as a string) is available as the value of the global variable
name . For instance, use your favourite text editor to create a file called
fibo.py in the current directory with the following contents:
# Fibonacci numbers module
def fib(n): # write Fibonacci
series up to n a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
def fib2(n): # return Fibonacci
series up to n result = []
a, b = 0, 1
while b < n: result.append(b)
a, b = b, a+b
return result
Now enter the Python interpreter and import this module with the following
command:
>>> import fibo
This does not enter the names of the functions defined in fibo directly in the
current symbol table; it only enters the module name fibo there. Using the
module name you can access the functions:
>>> fibo.fib(1000)

Unit-1 Page 75
Python For Data Science

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987


>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo. name 'fibo'
from statement:
 A module can contain executable statements as well as function definitions.
These statements are intended to initialize the module. They are executed
only the first time the module name is encountered in an import statement.
(They are also run if the file is executed as a script.)
 Each module has its own private symbol table, which is used as the global
symbol table by all functions defined in the module. Thus, the author of a
module can use global variables in the module without worrying about
accidental clashes with a user‟s global variables. On the other hand, if you
know what you are doing you can touch a module‟s global variables with
the same notation used to refer to its functions, modname.itemname.
 Modules can import other modules. It is customary but not required to place
all import statements at the beginning of a module (or script, for that
matter). The imported module names are placed in the importing module‟s
global symbol table.
 There is a variant of the import statement that imports names from a
module directly into the importing module‟s symbol table. For example:
>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the imports are taken in
the local symbol table (so in the example, fibo is not defined).

There is even a variant to import all names that a module defines:


>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
Namespaces and Scoping
 Variables are names (identifiers) that map to objects. A namespace is a
dictionary of variable names (keys) and their corresponding objects
(values).
 A Python statement can access variables in a local namespace and in
the global namespace. If a local and a global variable have the same
name, the local variable shadows the global variable.
 Each function has its own local namespace. Class methods follow the
same scoping rule as ordinary functions.

Unit-1 Page 76
Python For Data Science

 Python makes educated guesses on whether variables are local or


global. It assumes that any variable assigned a value in a function is
local.
 Therefore, in order to assign a value to a global variable within a
function, you must first use the global statement.
 The statement global VarName tells Python that VarName is a global
variable. Python stops searching the local namespace for the variable.
 For example, we define a variable Money in the global namespace.
Within the functionMoney, we assign Money a value, therefore Python
assumes Money as a local variable. However, we accessed the value of
the local variable Money before setting it, so an UnboundLocalError is
the result. Uncommenting the global statement fixes the problem.

Unit-1 Page 77

You might also like