Intro to Python Part 2

Intro to Python Part 2 Intro to Python Part 2

<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> <strong>Part</strong> 2P. TenHoopen - WMLUG<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 1


What is <strong>Python</strong>?<strong>Python</strong> is a cross-platform object-oriented programminglanguage invented by Guido van Rossum. It is an interpretedlanguage but there is support for compiling the programs.The most recent version is 3.0 (also known as <strong>Python</strong> 3000)which was released on December 3, 2008. It is incompatiblewith the 2.x releases.<strong>Python</strong> Home Page - http://www.python.org/Beginners Guide - http://wiki.python.org/moin/BeginnersGuide/NonProgrammers<strong>Python</strong> Language Reference - http://docs.python.org/reference/index.html#reference-indexGuido van Rossum Personal Page - http://www.python.org/~guido/<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 2


Native Data TypesNative <strong>Python</strong> Data Types:●Dictionaries●Lists●Tuples<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 3


DictionariesDictionaries are an unordered collection ofkey-value data pairs.It is unordered in the fact that as you additems, they are not necessarily appended<strong>to</strong> the end.Keys need <strong>to</strong> be unique.<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 4


Creating DictionariesCreating an empty dictionary:name={} # empty dictionaryExample:colors={}<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 5


Creating DictionariesCreating a pre-popluated dictionary:name={"key":"value"}Example:hexColor={"white":"ffffff", "black":"000000","red":"ff0000"} # prepopulated dictionaryprint hexColor{'white': 'ffffff', 'black': '000000', 'red':'ff0000'}<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 6


Adding ItemsAdding items <strong>to</strong> a dictionary:name["key"]="value"hexColor["blue"]="0000ff"print hexColor{'blue': '0000ff', 'white': 'ffffff','black': '000000', 'red': 'ff0000'}Notice that the item was inserted at the beginning,and not the end – hence unordered!<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 7


Changing Item ValuesChanging values in a dictionary:Same syntax as adding but the value isupdated.hexColor["blue"]="blue"print hexColor{'blue': 'blue', 'white': 'ffffff','black': '000000', 'red': 'ff0000'}<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 8


Deleting ItemsDeleting items from a dictionary:del name["key"]Example:del hexColor["blue"]print hexColor{'white': 'ffffff', 'black':'000000', 'red': 'ff0000'}<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 9


Clearing All ItemsClearing all items from a dictionary:name.clear()Example:hexColor.clear()print hexColor{}<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 10


ListsLists are an ordered collection of indexedvalues.The values can be strings or numbers andcan be duplicated.List indexes are zero-based.<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 11


Creating New ListsCreating new lists:name[] # empty listExample:list1[]<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 12


Creating New ListsCreating a prepopulated list:list2["white", "black", "42"]print list2['white', 'black', '42']<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 13


Insert Item In<strong>to</strong> ListInserting items in<strong>to</strong> a list:list2.insert(2, "purple")print list2['white', 'black', 'purple', '42']<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 14


Appending ItemsAppending items <strong>to</strong> a list:list2.append("red")print list2['white', 'black', 'purple', '42','red']<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 15


Deleting ItemsDeleting items from a list:list2.remove("white")This will remove the first occurance of thevalue "white" from the list.print list2['black', 'purple', '42', 'red']<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 16


Using List ValuesUsing values from a list:name[index]Example:List2[1]'purple'<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 17


Searching ListsSearching for values in a list:name.index("key")Example:list2.index("42")2<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 18


Check A List For ValuesIf you try <strong>to</strong> search a list for a value thatisn't present, python will give an exception.To avoid this, you can check a list for acertain value:"black" in list2TrueYou get a True or False response back.<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 19


ListYou can use the len function <strong>to</strong> get thenumber of items in a list:len(list2)4<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 20


TuplesA tuple is an indexed immutable list.It can't be changed once it is created.Good for constant variables.<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 21


Why Use TuplesTuples are faster than lists.Lists can be turned in<strong>to</strong> tuples using thetuple function.Tuples can be turned in<strong>to</strong> lists using thelist function.<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 22


Creating TuplesCreating a new tuple:name=(“value1”, “value2”)Examples:t=("a", "b", "c")screensize=(800, 600)<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 23


Checking A Tuple for ValueYou can check a tuple for a certain value:"b" in tTrueYou get a True or False response back.<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 24


FunctionsFunctions are blocks of code that perform acertain function.The statements are indented inside thefunction.<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 25


Defining A FunctionTo define a function use the def command:def functionName(parameters):The parameters are optional variablenames.<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 26


DocumentingYou can document functions use a docstring.A doc string is a triple quotation markenclosed string. It can be multi-lined.Example:def function():“””This is a doc string.”””<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 27


Return ValuesYou can return a value back from thefunction using the return command. Ifthat is not done, the function au<strong>to</strong>maticallyreturns None which is the <strong>Python</strong> null value.def functionName(parameters):print “Hello from the function”return 1<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 28


Variable ScopeThe scope of a variable is where the variable isaccessible. There is local and global scope.A variable defined within a function only isaccessible within that function, hence it has localscope.A variable can have global scope so that it isaccessible <strong>to</strong> all functions.<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 29


Using Global VariablesSometimes you need <strong>to</strong> use variables thatwere declared outside of the function whichare normally inaccessible.Use the global command <strong>to</strong> access thevalues.global variableA<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 30


Using FunctionsTo call a function:def sayHello():“””Function <strong>to</strong> print a message.”””print “Hello, how are you?”return 1sayHello()Hello, how are you?<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 31


Function ParametersTo call a function that takes a parameter:def sayHello(passedName):“””Function <strong>to</strong> print a message.The passedName variable accepts the value passed <strong>to</strong> it fromthe calling statement. It has local scope in the function.”””print “Hello, %s how are you?” % passedNameExample 1 – Static string as a parameter:sayHello(“Homer”)Hello, Homer how are you?Example 2 – Variable as a parameter:myName=”Bart”sayHello(myName)Hello, Bart how are you?<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 32


Putting It All TogetherDemo<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 33


Putting It All Together#!/usr/bin/python"""FileStats.pyP. TenHoopen, 11/21/08Read the statistics of files from a specified direc<strong>to</strong>ry and subdirec<strong>to</strong>ries.Display number of files, types and number of files, average size, smallest size,largest size"""# Import Modulesimport os# Global Variablesextensions = {}largestFileSz = 0largestFile = ""numFiles = 0sumFileSizes = 0.0# dictionary <strong>to</strong> hold extensions and counts# size of largest file# name of largest file# number of files found# <strong>to</strong>tal size of files used <strong>to</strong> calc average file size<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 34


Putting It All Together# Functionsdef recordExtension(thisExtension):"""This function keeps track of the extensions that are found."""# add <strong>to</strong> dictionary if new, or update count if existingif thisExtension not in extensions:extensions[thisExtension] = 1else:extensions[thisExtension] += 1return 1<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 35


Putting It All Togetherdef collectFileInfo(fileName):"""This function examines file statistics <strong>to</strong> keep track of largest file and<strong>to</strong>tal file sizes."""# use global variables defined aboveglobal largestFileSzglobal largestFileglobal sumFileSizes# collect file statisticsfileStats = os.stat(fileName)# get file sizesize = fileStats.st_size# keep size of all filessumFileSizes += size# is this the largest file found so far?if size > largestFileSz:largestFileSz = sizelargestFile = fileNamereturn 1<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 36


Putting It All Togetherdef displayStats():"""This function displays the collected statistics."""print "\n\nResults:"print "\nThere were %d files found." % numFilesprint "\nCount \t File Ext"print "­­­­­ \t ­­­­­­­­"for extension in extensions:print "%d \t %s" % (extensions[extension], extension)print "\n"print "Largest file: %s at %d bytes" % (largestFile, largestFileSz)print "Total size of files is %d bytes" % (sumFileSizes)print "Average size of files is %.2f bytes" % (sumFileSizes / numFiles)print "\n"return 1<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 37


Putting It All Togetherdef main():"""This function is called when the program starts. It analyzes thefiles specified in the <strong>to</strong>pDir variable."""# variables<strong>to</strong>pDir = "."# direc<strong>to</strong>ry <strong>to</strong> search, default <strong>to</strong> current direc<strong>to</strong>ry# use global variables defined aboveglobal numFiles# get <strong>to</strong>p direc<strong>to</strong>ry <strong>to</strong> analyze from useruserDir = raw_input("Input the direc<strong>to</strong>ry <strong>to</strong> analyze: ")if (len(userDir) > 0): # weak error checking!<strong>to</strong>pDir = userDir # as long as the user enters something, useit otherwise use default value of "."print "\nAnalyzing files in '%s'..." % <strong>to</strong>pDir# walk through the fileswalklist = os.walk(<strong>to</strong>pDir)# os.walk returns {dirpath, dirnames, filenames}<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 38


Putting It All Togetherfor root, dirs, files in walklist:# examine each file foundfor eachFile in files:numFiles += 1# look for a extension delimiter (.) in the file nameif "." in eachFile:# get the file extension using a string slice# extract all text after the periodextension = eachFile[eachFile.index(".")+1:]else:# no period delimiter so no extension can be determinedextension = "none"# keep track of extensions that are foundrecordExtension(extension)# get file name and pathfileName = os.path.join(root, eachFile)# examine files statscollectFileInfo(fileName)# display the results of the analysisdisplayStats()Return 1# This calls the 'main' function when this script is executed.if __name__ == '__main__': main()<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 39


That's All FolksQuestions?<strong>Intro</strong> <strong>to</strong> <strong>Python</strong> 2February 2009Slide 40

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!