Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
194 views

Python With Data Science

This document provides an overview of the Python programming language. It discusses that Python was invented in the 1990s in the Netherlands and is an interpreted, interactive, object-oriented scripting language with a broad standard library. It is easy to learn and use for a variety of applications including web development, data science, and prototyping. The document then covers Python basics like variables, data types, strings, numbers, conditionals, and loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
194 views

Python With Data Science

This document provides an overview of the Python programming language. It discusses that Python was invented in the 1990s in the Netherlands and is an interpreted, interactive, object-oriented scripting language with a broad standard library. It is easy to learn and use for a variety of applications including web development, data science, and prototyping. The document then covers Python basics like variables, data types, strings, numbers, conditionals, and loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 102

PYTHON WITH Shahila shahul

Assistant Professor
DATA SCIENCE MES-AIMAT Marampilly
BRIEF HISTORY OF
PYTHON
Invented in the Netherlands, early 90s by Guido van Rossum

Named after Monty Python

Open sourced from the beginning

Considered a scripting language, but is much more

Used by Google from the beginning

Increasingly popular
INTRODUCTION
Python is a

 high-level

 Interpreted

 interactive

 object-oriented scripting language


PYTHON FEATURES

Easy-to-learn

Easy-to-read

broad standard library

Interactive Mode

Portable

Databases
APPLICATIONS OF PYTHON

Web Applications

Scientific and Numeric Computing

Creating software Prototypes

Good Language to Teach Programming


HELLO WORLD
•Open a terminal window and type “python”
•At the prompt type ‘hello world!’

>>> 'hello world!'


'hello world!'
THE PYTHON
INTERPRETER
•Python is an interpreted >>> 3 + 7
language 10
>>> 3 < 15
•The interpreter provides an
True
interactive environment to
>>> 'print me'
play with the language
'print me'
•Results of expressions are >>> print 'print me'
printed on the screen print me
>>>
OUTPUT: THE PRINT
STATEMENT
•Elements separated by
commas print with a space
between them >>> print 'hello'
•A comma at the end of the hello
statement (print ‘hello’,) will >>> print 'hello', 'there'
not print a newline character hello there
DOCUMENTATION
The ‘#’ starts a line comment

>>> 'this will print'


'this will print'
>>> #'this will not'
>>>
VARIABLES
• Are not declared, just assigned

• The variable is created the first time you assign it a value

• Are references to objects

• The variable name is case sensitive: ‘val’ is not the same as ‘Val’

• Everything in Python is an object

• The type of the variable is determined by Python.


Two execution modes
1.interactive mode
2.script mode
**Write a python program to find the sum of 2 numbers
Num1=10
Num2=14
Result=num1 +num2
Print(result)
EVERYTHING IS AN
OBJECT???
Everything means
everything, including >>> x = 7
functions and classes >>> x
7
>>> x = 'hello'
>>> x
'hello'
>>>

Type info is with the object


PYTHON DATA TYPES
SEQUENCE DATA TYPES
·Numbers
·String
·List
·Tuple
·Dictionary
·Set
NUMBERS
Number data types store numeric values. Number objects are created when you assign a
value to them.
 For example − var1 = 1var2 = 10

Python supports the following numerical types −


 signed integers
 floating point real values
 complex (complex numbers)
 All integers in Python3 are represented as long integers. Hence there is no separate number type as long.
 10
 10.0
 3.14j
NUMBERS:
FLOATING POINT
The interpreter shows >>> 1.3E7
a lot of digits. To avoid this use 13000000.0
“print” >>>quantity=10
>>>type(quantity)
>>> int(2.0)
<class ‘int’>
2

>>> float(2) >>>price =-192.2


2.0 >>>type(price)
int(x) converts x to an integer
<class ‘float’>

float(x) converts x to a floating point


NUMBERS:
COMPLEX
>>> x = 3 + 2j
>>> y = -1j
Built into Python >>> x + y
(3+1j)
>>> x * y
Same operations are supported as
integer and float (2-3j)
EXAMPLES OF NUMBERS
• Integers: 12 0 -12987 0123 0X1A2
– Type ‘int’
– Octal literals begin with 0 (0981 illegal!)
– Hex literals begin with 0X, contain 0-9 and A-F

• Floating point: 12.03 1E1 -1.54E-21


– Type ‘float’
– Same precision and magnitude as C double

• Long integers: 10294L


– Type ‘long’
– Any magnitude
– Python usually handles conversions from int to long

• Complex numbers: 1+3J


– Type ‘complex’
NUMBERS: A WRAP UP
Numbers are immutable
Many math functions in the math module

>>> import math


>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2',
'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod',
'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow',
'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>>
STRING

enclosed in single quotes ('...') or double quotes ("...") it defines the


starting and ending of a sequences of character.
>>>str1=‘hello friend’
>>>str2=‘452’
The print() function produces a more readable output, by omitting
the enclosing quotes and by printing escaped and special characters:
STRING INDEXING
SLICING
slicing allows you to obtain substring:
ACCESSING SINGLE
CHARACTERS
You can access individual characters by using indices in square brackets.

>>> myString = “GATTACA”


>>> myString[0]
‘G’
>>> myString[1]
‘A’ Negative indices start at
>>> myString[-1]
the end of the string and
‘A’
>>> myString[-2] move left.
‘C’
>>> myString[7]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: string index out of range
ACCESSING SUBSTRINGS

>>> myString = “GATTACA”


>>> myString[1:3]
‘AT’
>>> myString[:3]
‘GAT’
>>> myString[4:]
‘ACA’
>>> myString[3:5]
‘TA’
>>> myString[:]
‘GATTACA’
SPECIAL CHARACTERS
The backslash is used to introduce a special
character. Escape Meaning
sequence
>>> "He said, "Wow!"" \\ Backslash
File "<stdin>", line 1
"He said, "Wow!"" \’ Single quote
^
SyntaxError: invalid syntax \” Double
>>> "He said, 'Wow!'" quote
"He said, 'Wow!'"
\n Newline
>>> "He said, \"Wow!\""
'He said, "Wow!"' \t Tab
MORE STRING
>>>FUNCTIONALITY
len(“GATTACA”) ←Length
7
>>> “GAT” + “TACA” ←Concatenation
‘GATTACA’
>>> “A” * 10
←Repeat
‘AAAAAAAAAA
>>> “GAT” in “GATTACA”
←Substring test
True
>>> “AGT” in “GATTACA”
False
STRING METHODS

In Python, a method is a function that is defined with respect to a


particular object.
The syntax is <object>.<method>(<parameters>)

>>> dna = “ACGT”


>>> dna.find(“T”)
3
STRING METHODS
>>> "GATTACA".find("ATT")

>>> "GATTACA".count("T")

>>> "GATTACA".lower()

'gattaca'

>>> "gattaca".upper()

'GATTACA'

>>> "GATTACA".replace("G", "U")

'UATTACA‘

>>> "GATTACA".replace("C", "U")

'GATTAUA'

>>> "GATTACA".replace("AT", "**")

'G**TACA'

>>> "GATTACA".startswith("G")

True

>>> "GATTACA".startswith("g")

False
STRINGS ARE IMMUTABLE

Strings cannot be modified; instead, create a new one.

>>> s = "GATTACA"
>>> s[3] = "C"
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object doesn't support item assignment
>>> s = s[:3] + "C" + s[4:]
>>> s
'GATCACA'
>>> s = s.replace("G","U")
>>> s
'UATCACA'
STRINGS ARE IMMUTABLE
• String methods do not modify the string; they return a new string.

>>> sequence = “ACGT”


>>> sequence.replace(“A”, “G”)
‘GCGT’
>>> print sequence
ACGT

>>> sequence = “ACGT”


>>> new_sequence = sequence.replace(“A”, “G”)
>>> print new_sequence
GCGT
Basic string operations:

S = "AATTGG" # assignment - or use single quotes ' '

s1 + s2 # concatenate STRING SUMMARY


s2 * 3 # repeat string

s2[i] # index character at position 'i'

s2[x:y] # index a substring

len(S) # get length of string

int(S) # or use float(S) # turn a string into an integer or


floating point decimal

Methods:

S.upper()

S.lower()

S.count(substring)

S.replace(old,new)

S.find(substring)

S.startswith(substring), S. endswith(substring)

Printing:

print var1,var2,var3 # print multiple variables

print "text",var1,"text" # print a combination of explicit text


(strings) and variables
STRING COMPARISON
To test for equality, use the == operator
To compare order, use the < and > operators
user_name=raw_input("Enter your name- ")
if user_name==“Sam":
print "Welcome back Sam“
elif user_name<"Sam":
print "Your name is before Sam“
else:
print "Your name is after Sam“
These operators are case sensitive.
Upper case characters are ‘less than’ lower case
OPERATIONS: TRAVERSING
Use aTHROUGH A STRING
loop to examine each character in a string

strng="count # of u"
index=0
count=0
while index < len(strng):
if strng[index] == "u“ or strng[index] == “U":
count+=1
index+=1
Try it out
 How would we traverse backwards?
STRING OPERATIONS: FIND
find() searches for a string within a string
To use it, insert this at the top of your code:
 import string

find() returns the first index of a substring


 full_name = "Henry James"
 string.find(full_name,"e")

You can specify the starting point of the search:


string.find(full_name,"e",2)

If the string is not found, find() returns -1


find() is case sensitive
COLLECTION DATA
TYPES

Sequence Types
 List
 Tuple

Mapping Types
 Dictionary
LIST
List - list of comma-separated values (items) between square brackets
 Lists might contain items of different types, but usually the items all have the same type.

lists can be indexed and sliced:

All slice operations return a new list containing the requested elements. This
means that the following slice returns a new (shallow) copy of the list:
Concatenation

Lists are mutable

Add new items at the end of the list, by using the append() method
Assignment to slices is possible

remove items from list by del []


Del letters[0]

clear the list by replacing all the elements with an empty list
Length of string

create lists containing other lists


TUPLE
A tuple is a sequence of immutable Python objects.
The differences between tuples and lists are
 the tuples cannot be changed unlike lists and
 tuples use parentheses, whereas lists use square brackets.

The empty tuple is written as two parentheses containing nothing

To write a tuple containing a single value you have to include a comma, even though
there is only one value .
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.
UPDATING TUPLES

Tuples are immutable which means you cannot update or change the values
of tuple elements.

It is possible to take portions of existing tuples to create new tuples


tup1 = (12, 34.56)

tup2 = ('abc', 'xyz')

tup1[0] = 100 # invalid for tuples

tup3 = tup1 + tup2; # a new tuple can be created like this

print tup3
DELETE TUPLE ELEMENTS

Removing individual tuple elements is not possible.

Undesired elements that are discarded can be put together into another tuple.

To explicitly remove an entire tuple, just use the del statement.


tup = ('physics', 'chemistry', 1997, 2000);
print tup
del tup
print "After deleting tup : “
print tup # invalid NameError: name 'tup' is not defined
BASIC TUPLES
OPERATIONS
indexing and slicing work the same way for tuples as they do for strings
DICTIONARIES
A set of key-value pairs
Any key of the dictionary is associated (or mapped) to a value
The values of a dictionary can be any Python data type
Dictionaries are mutable
Dictionaries are unordered key-value-pairs.
Also known as associative array or hash table

>>> d = {1 : 'hello', 'two' : 42, 'blah' : [1,2,3]}


>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['blah']
[1, 2, 3]
DICTIONARIES:
ADD/MODIFY
Entries can be changed by assigning to that entry
Assigning to a key that does not exist adds an entry

>>> d
{1: 'hello', 'two': 42, 'blah': [1, 2, 3]}
>>> d['two'] = 99
>>> d
{1: 'hello', 'two': 99, 'blah': [1, 2, 3]}
>>> d[7] = 'new entry'
>>> d
{1: 'hello', 'two': 99, 'blah': [1, 2, 3], 7: 'new
entry'}
USER-DEFINED INDEXES AS MOTIVATION FOR
DICTIONARIES

>>> employee = {
'864-20-9753': ['Anna', 'Karenina'],
'987-65-4321': ['Yu', 'Tsun'],
'100-01-0010': ['Hans', 'Castorp']}

>>> employee['987-65-4321']
['Yu', 'Tsun']

>>> employee['864-20-9753']
['Anna', 'Karenina']
Write a function birthState() that takes as input the full name of a recent
U.S. president (as a string) and returns his birth state. You should use this
dictionary to store the birth state for each recent president:

{'Barack Hussein Obama II':'Hawaii',


'George Walker Bush':'Connecticut',
'William Jefferson Clinton':'Arkansas',
'George Herbert Walker Bush':'Massachussetts',
'Ronald Wilson Reagan':'Illinois',
'James Earl Carter, Jr':'Georgia'}

>>> birthState('Ronald Wilson Reagan')


'Illinois'
COPYING DICTIONARIES
AND LISTS
The built-in list function
will copy a list >>> l1 = [1] >>> d = {1 : 10}
The dictionary has a >>> l2 = list(l1) >>> d2 = d.copy()
method called copy >>> l1[0] = 22 >>> d[1] = 22
>>> l1 >>> d
[22] {1: 22}
>>> l2 >>> d2
[1] {1: 10}
DICTIONARY METHODS

>>> h = {'key': 12, 'nyckel': 'word'}

>>> 'Per' in h # test if key in dictionary


False

>>> h.keys() # all keys in a list; unordered


['nyckel', 'key']

>>>h.has_key(‘nyckel’)
True
>>> h.values() # all values in a list; unordered
['word', 12]

>>> len(h) # number of keys in dictionary


2
>>> g = h.copy() # a separate copy of the dictionary
>>> del h['key']
>>> h
{'nyckel': 'word'}
>>> g
{'nyckel': 'word', 'key': 12}

>>> h['Per'] = 'Johansson'


>>> h
{'nyckel': 'word', 'Per': 'Johansson'}
>>> h.update(g) # add or update all key/value from g
>>> h
{'nyckel': 'word', 'key': 12, 'Per': 'Johansson'}
PYTHON SET
CLASS
SET
used to store an unordered collection of items, with no duplicate items
allowed.
items must be immutable objects
Supports operators that implement the classical set operations: set
membership, intersection, union, symmetric difference etc.

>>> phonebook1 = {'123-45-67', '234-56-78', '345-67-89'}

>>> phonebook1
{'123-45-67', '234-56-78', '345-67-89'}

>>> type(phonebook1)
<class 'set'>

>>> phonebook1 = {'123-45-67', '234-56-78', '345-67-89',


'123-45-67', '345-67-89'}

>>> phonebook1
{'123-45-67', '234-56-78', '345-67-89'}
SET
Create two sets s1 and s2 consisting of elements s1= rose, jasmine, lily, lotus and s2= rose, daisy, lily, iris,
poppy and perform all the set operations.

i) Intersection

ii) Union

iii) Difference

iv) Symmetric Difference

s1=set(['rose','jasmine','lily','lotus'])

s2=set(['rose','daisy','lily','iris','poppy'])

print "s1= ",s1

print "s2= ",s2

print ("i) s1&s2= ",s1&s2)

print ("ii) s1|s2= ",s1|s2)

print ("iii) s1-s2= ",s1-s2)

Print ( "iv) s1^s2= ",s1^s2)


Using the set Constructor to Remove Duplicates
The fact that sets cannot have duplicates gives us the first great application for sets:
removing duplicates from a list.

Suppose we have a list with duplicates, such as this list of ages of students in a class:

>>> ages = [23, 19, 18, 21, 18, 20, 21, 23, 22, 23, 19, 20]

To remove duplicates from this list, we can convert the list to a set, using the set
constructor. The set constructor will eliminate all duplicates because a set is not supposed
to have them.

By converting the set back to a list, we get a list with no duplicates:

>>> ages = list(set(ages))

>>> ages
[18, 19, 20, 21, 22, 23]
EMPTY SETS
>>> phonebook2 = {}

>>> type(phonebook2)

<class 'dict'>

The problem here is that curly braces ({}) are used to define dictionaries as well, and {} represents
an empty dictionary.

use the set constructor explicitly when creating an empty set:

>>> phonebook2 = set()

>>> phonebook2

set()

>>> type(phonebook2)

<class 'set'>
SET OPERATORS
>>> phonebook1

{'123-45-67', '234-56-78', '345-67-89'}

>>> '123-45-67' in phonebook1

True

>>> '456-78-90' in phonebook1

False

>>> '456-78-90' not in phonebook1

True

The len() operator returns the size of the set:

>>> len(phonebook1)

3
SET METHODS
add() is used to add an item to a set:

>>> phonebook3.add('123-45-67')

>>> phonebook3

{'123-45-67', '345-67-89', '456-78-90'}

remove() is used to remove an item from a set:

>>> phonebook3.remove('123-45-67')

>>> phonebook3

{'345-67-89', '456-78-90'}

method clear() is used to empty a set:

>>> phonebook3.clear()

>>> phonebook3

set()
Implement function sync() that takes a list of phone books (where each
phone book is a set of phone numbers) as input and returns a phone
book (as a set) containing the union of all the phone books.

>>> phonebook4 = {'234-56-78', '456-78-90'}

>>> phonebooks = [phonebook1, phonebook2, phonebook3,


phonebook4]

>>> sync(phonebooks)
{'234-56-78', '456-78-90', '123-45-67', '345-67-89'}
Python operators
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
ARITHMETIC OPERATORS

A=10,b=20
COMPARISON(RELATIONAL) OPERATOR
ASSIGNMENT OPERATORS
BITWISE OPERATOR

Bitwise operator works on bits and performs bit by bit


operation. Assume if a = 60; and b = 13; Now in the
binary format their values will be 0011 1100 and
0000 1101 respectively. Following table lists out the
bitwise operators supported by Python language with
an example each in those, we use the above two
variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a  = 1100 0011
LOGICAL OPERATORS
MEMBER SHIP OPERATORS
IDENTITY OPERATORS

Identity operators compare the memory


locations of two objects
PYTHON OPERATOR PRESEDENCE
PYTHON CONTROL STRUCTURES
DECISION MAKING
if expression:
statement(s)

var1 = 100
if var1==100:
print var1
if expression:
statement(s)
else:
statement(s)

if var1<150:
print var1
else:
print var2
DECISION MAKING[ CONTINUED ..]

if expression1: var = 100


statement(s) if var < 200:
if expression2: print "Expression value is less than 200“
statement(s) if var == 150:
elif expression3: print "is 150"
statement(s) elif var == 100:
else print “ is 100"
statement(s) elif var == 50:
elif expression4: print “is 50“
statement(s) else: print "Could not find true
else: expression" print "Good bye!
statement(s)
LOOP STATEMENTS
While
Iterating by Sequence Index
while expression:
statement(s) range([start], stop[, step])
 start: Starting number of the sequence.
count = 0
 stop: Generate numbers up to, but not including this number.
while (count < 9):
 step: Difference between each number in the sequence.
print 'The count is:', count
count = count + 1
print "Good bye!”

for

for iterating_var in sequence:


statements(s)

for letter in 'Python':


print 'Current Letter :‘,letter
fruits = ['banana', 'apple', 'mango']

for fruit in fruits:


print 'Current fruit :', fruit
print"Good bye!"
PYTHON NESTED LOOPS
LOOP CONTROL STATEMENTS
break
· terminates the current loop and resumes
execution at the next statement Pass
for letter in 'Python':  The pass statement in Python is used when a
if letter == 'h': statement is required syntactically but you do not
want any command or code to execute
break
print 'Current Letter :', letter
for letter in 'Python':
Current Letter : P if letter == 'h':
Current Letter : y pass
Current Letter : t print 'This is pass block' print 'Current
Letter :', letter
print "Good bye!“
continue
 Causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating.
for letter in 'Python': Current Letter : P
if letter == 'h': Current Letter : y
continue Current Letter : t
print 'Current Letter :', letter This is pass block
Current Letter : h
Current Letter : P Current Letter : o
Current Letter : y Current Letter : n
Current Letter : t Good bye!
Current Letter : o
Current Letter : n
PROGRAM INPUT AND
OUTPUT
Python provides two built-in functions to read a line of text from standard
input.
 raw_input()
 Input()
The raw_input([prompt]) function reads one line from standard input and returns
it as a string (removing the trailing newline).
str = raw_input("Enter your input: ");
print "Received input is : ", str

The input([prompt]) function is equivalent to raw_input, except that it assumes


the input is a valid Python expression and returns the evaluated result to you.

str = input("Enter your input: ");


print "Received input is : ", str

Enter your input: [x*5 for x in range(2,10,2)] Recieved


input is : [10, 20, 30, 40]
SUM AND AVERAGE OF
FIRST N NATURAL
NUMBERS
n = int(input("Enter number"))
sum = 0
# loop from 1 to n
for num in range(1, n + 1):
sum = sum + num
print("Sum of first ", n, "numbers is: ", sum)
average = sum / n
print("Average of ", n, "numbers is: ", average)
FUNCTIONS
A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

a function is defined using the def keyword


FUNCTIONS WITH PARAMETERS
Everything is call by reference
Information can be passed to functions as parameter.

Parameters are specified after the function name, inside the parentheses.

You can add as many parameters as you want, just separate them with a comma.

The following example has a function with one parameter (fname).

When the function is called, we pass along a first name, which is used inside the function to print
the full name:
DEFAULT PARAMETER VALUE

If we call the function without parameter, it uses the default value:


RETURN VALUES
ANONYMOUS FUNCTIONS

One way to define a simple function is anonymously using a lambda


expression. For example, a function that evaluates a single
expression, like addition, can be replaced with a lambda expression.
Since this is a simple function that does nothing more than evaluate a
single expression, “x-y”, it can be replaced with a lambda expression.

The biggest difference is the absence of the ‘def’ keyword, ‘return’


keyword and function name in our lambda expression.
What is recursion?
Recursion is the process of defining something in terms of itself.
A physical world example would be to place two parallel mirrors
facing each other. Any object in between them would be reflected
recursively.
 factorial() is a recursive function as it calls itself.
Our recursion ends when the number reduces to 1. This is called the
base condition.
Every recursive function must have a base condition that stops the
recursion or else the function calls itself infinitely.
The Python interpreter limits the depths of recursion to help avoid
infinite recursions, resulting in stack overflows.
By default, the maximum depth of recursion is 1000. If the limit is
crossed, it results in RecursionError. Let's look at one such condition.
USER DEFINED
FUNCTION
Functions that we define ourselves to do certain specific task are
referred as user-defined functions.
Functions that readily come with Python are called built-in functions.
If we use functions written by others in the form of library, it can be
termed as library functions.
All the other functions that we write on our own fall under user-
defined functions. So, our user-defined function could be a library
function to someone else.
In the above example, print() is a built in function. 

You might also like