PYTHON FOR DATA SCIENCE PROFESSIONALS

Introduction to Python







Welcome to the Python Workshop

CRUD in Python

  • Creating a file
  • Reading a file
  • Updating /Appending a file
  • Deleting a file

Where am I ? What is my current working Directory ?

In [56]:
import os
cwd = os.getcwd()
a = os.getlogin()
print a
print cwd
sudhirwadhwa
/Users/sudhirwadhwa/Desktop/tmp/INTELFINALBUNDLE/Day1_Introduction_Lab

Create a file attendee.txt

In [57]:
# Define a fucntion which will create a file attendee.txt ( in current working dir)
def makeTxtFile():
    a=open('attendee.txt',"w")
    a.write("This is a TXT file Placeholder")
    a.close()
In [58]:
# Calling the function. This function takes no argument 
makeTxtFile()

Write a fucntion to create a file – we will give the filename

In [59]:
def makeTxtFileWith(filename):
    f1=open(filename,"w")
    f1.write("This is a sample file created")
    f1.close()
    print ("File Successfully Created!!")
In [60]:
# Calling a function which takes an argument - filename 
# Function promises - gibe me a filename and I will created a file
makeTxtFileWith('SanFran.txt')
makeTxtFileWith('SanJose.txt')
makeTxtFileWith('Shanghai.txt')
File Successfully Created!!
File Successfully Created!!
File Successfully Created!!
In [61]:
ls
GoodIntro.ipynb*                    PastHires.csv*
GoodIntro.ipynb.backup*             QueryResults1.csv
Hamburg.txt                         SanFran.txt
Intro.html                          SanJose.txt
Introduction to Python.ipynb        Shanghai.txt
IsDeepLearningGettingPopular.ipynb* Untitled.ipynb
LabIntro.ipynb                      anaconda.mp4*
MatPlotLibIntroduction.ipynb*       attendee.txt
NewPastHires.csv                    m.txt
OldDelhiNewText.txt                 ml-100k/
Paris.txt                           plot22.png

What if the file already exists, I don’t want to overwrite it. Write a function to check if the file already exists.

In [62]:
def checkIfFileExists(fi):
    if os.path.isfile(fi):
        print ("Warning:: File already exists")
In [63]:
checkIfFileExists('SanJose.txt')
Warning:: File already exists

Now bring it all togeather, Write a function which will create a new file and if the file exists, it gives us a warning and finish the program

In [ ]:
In [64]:
def CreateNewFileOnly(fileName):
    if os.path.isfile(fileName):
        print("You are trying to create a file that already exists!")
    else:
        f=open(fileName,"w")
        f.write("A new text file")
        print("file created successfully!")
In [65]:
CreateNewFileOnly('OldDelhiNewText.txt')
You are trying to create a file that already exists!
In [66]:
CreateNewFileOnly('SanFran.txt')
CreateNewFileOnly('SanJose.txt')
CreateNewFileOnly('Shanghai.txt')
You are trying to create a file that already exists!
You are trying to create a file that already exists!
You are trying to create a file that already exists!
In [67]:
CreateNewFileOnly('SanFran.txt')
CreateNewFileOnly('SanJose.txt')
CreateNewFileOnly('Shanghai.txt')
You are trying to create a file that already exists!
You are trying to create a file that already exists!
You are trying to create a file that already exists!
In [68]:
CreateNewFileOnly('Hamburg.txt')
CreateNewFileOnly('Paris.txt')
You are trying to create a file that already exists!
You are trying to create a file that already exists!

What version of Python I have? What are the Python Kewords? How many Total Keywords we have in Python?

In [69]:
import sys
import keyword

print "Python version: ", sys.version_info
print "===================================="
print "Python keywords: ", keyword.kwlist
print "===================================="
# Put all Keword in a List and use Lenght of the List
print "Total Keyword:", len((list(keyword.kwlist)))
Python version:  sys.version_info(major=2, minor=7, micro=11, releaselevel='final', serial=0)
====================================
Python keywords:  ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
====================================
Total Keyword: 31
In [70]:
pythonKeyWordList = []
pythonKeyWordList = list(keyword.kwlist)
print pythonKeyWordList


print "============================================================================"
print "Now let's print one Keyword at a time"
print "============================================================================"


for k in pythonKeyWordList:
    print k
    
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']
============================================================================
Now let's print one Keyword at a time
============================================================================
and
as
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
with
yield
In [71]:
# Importing a module and using it
import random
dir(random)
Out[71]:
['BPF',
 'LOG4',
 'NV_MAGICCONST',
 'RECIP_BPF',
 'Random',
 'SG_MAGICCONST',
 'SystemRandom',
 'TWOPI',
 'WichmannHill',
 '_BuiltinMethodType',
 '_MethodType',
 '__all__',
 '__builtins__',
 '__doc__',
 '__file__',
 '__name__',
 '__package__',
 '_acos',
 '_ceil',
 '_cos',
 '_e',
 '_exp',
 '_hashlib',
 '_hexlify',
 '_inst',
 '_log',
 '_pi',
 '_random',
 '_sin',
 '_sqrt',
 '_test',
 '_test_generator',
 '_urandom',
 '_warn',
 'betavariate',
 'choice',
 'division',
 'expovariate',
 'gammavariate',
 'gauss',
 'getrandbits',
 'getstate',
 'jumpahead',
 'lognormvariate',
 'normalvariate',
 'paretovariate',
 'randint',
 'random',
 'randrange',
 'sample',
 'seed',
 'setstate',
 'shuffle',
 'triangular',
 'uniform',
 'vonmisesvariate',
 'weibullvariate']
In [72]:
a = random.randint(1,100)
print a
77

Getting Help on a function

In [73]:
help(random.randint)
Help on method randint in module random:

randint(self, a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.

In [ ]:
In [74]:
help(os.path.exists)
Help on function exists in module genericpath:

exists(path)
    Test whether a path exists.  Returns False for broken symbolic links

In [ ]:
In [75]:
import random
pythonRandomNumber = random.randint(1,100)
userInput = 'Guess a number between 1 and 100? '

while True:
    playersGuessNumber = raw_input(userInput)
    if pythonRandomNumber == int(playersGuessNumber):
        print('You got it !')
        break
    elif pythonRandomNumber > int(playersGuessNumber):
        print('Too low')
    else: 
        print('Too high')
Guess a number between 1 and 100? 34
Too low
Guess a number between 1 and 100? 77
Too low
Guess a number between 1 and 100? 88
Too high
Guess a number between 1 and 100? 82
Too low
Guess a number between 1 and 100? 84
You got it !

You have a list of numbers , you want to find the sum and average

In [76]:
listOfNumbers = [10,20,30, 40,50, 60, 70, 80, 90,100]
print listOfNumbers[0]
print listOfNumbers[1]
print listOfNumbers[2]
print listOfNumbers[3]
print listOfNumbers[4]
print listOfNumbers[5]
print listOfNumbers[6]
print listOfNumbers[7]
print listOfNumbers[8]
print listOfNumbers[9]
10
20
30
40
50
60
70
80
90
100
In [77]:
sumOfNumbers = 0

lengthOfListOfNumbers = len(listOfNumbers)

while (lengthOfListOfNumbers != 0):
    lengthOfListOfNumbers = lengthOfListOfNumbers - 1
    sumOfNumbers = sumOfNumbers + listOfNumbers[lengthOfListOfNumbers]

print "The sum is:", sumOfNumbers
print "The Average:", sumOfNumbers/len(listOfNumbers)
The sum is: 550
The Average: 55