Python Unit1
Python Unit1
Unit-1
Definition:
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:
Unit-1 Page 2
Python For Data Science
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.
Unit-1 Page 6
Python For Data Science
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.
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.
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.
Unit-1 Page 8
Python For Data Science
def If return
del import try
elif In while
else Is with
except lambda yield
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.
Unit-1 Page 10
Python For Data Science
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:
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
Unit-1 Page 13
Python For Data Science
PYTHON STRINGS
To access substrings, use the square brackets for slicing along with the index or
indices to obtain your substring. For example −
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.
Ex:
Str1= “STRINGS IN PYTHON”
Print(str1)
STRINGS IN PYTHON
print(str1[0])
S
print (str1[-1])
N
print(str1[-3])
H
Unit-1 Page 15
Python For Data Science
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
Output:
12345
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
Unit-1 Page 20
Python For Data Science
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[0]: physics
tup2[1:5]: (2, 3, 4, 5)
Updating Tuples
We cannot update or change the values of tuple elements
Unit-1 Page 22
Python For Data Science
This produces the following result. Note an exception raised, this is because
after del tup tuple does not exist any more −
Unit-1 Page 23
Python For Data Science
Unit-1 Page 24
Python For Data Science
Set:
Example:
s={1, 2.5, “abc” }
print s # display set( [ 1, 2.5, “abc” ] )
Unit-1 Page 25
Python For Data Science
Unit-1 Page 26
Python For Data Science
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
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 −
Unit-1 Page 27
Python For Data Science
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 −
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
Unit-1 Page 29
Python For Data Science
Unit-1 Page 30
Python For Data Science
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 −
Unit-1 Page 31
Python For Data Science
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
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
+= 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
Unit-1 Page 35
Python For Data Science
/= 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
//= 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
Unit-1 Page 37
Python For Data Science
>> 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
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.
not Logical NOT Used to reverse the logical state of its Not(a and b)
operand. is false.
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
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
Unit-1 Page 42
Python For Data Science
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
Syntax
if expression:
statement(s)
Unit-1 Page 46
Python For Data Science
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
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
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.
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 −
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:
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
Loop control statements change execution from its normal sequence. Python
supports the following control statements.
1. Break statement.
2. Continue statement.
3. Pass statement.
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
Unit-1 Page 54
Python For Data Science
Mathematical Functions
Python includes following functions that perform mathematical calculations.
Unit-1 Page 55
Python For Data Science
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
Unit-1 Page 57
Python For Data Science
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.
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
return [expression]
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):
print c
add(5,12) # 17
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):
return c
print add(5,12) # 17
Unit-1 Page 60
Python For Data Science
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
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
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.
Unit-1 Page 65
Python For Data Science
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.
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
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
Unit-1 Page 76
Python For Data Science
Unit-1 Page 77