Python

Card Set Information

Author:
sddcom1
ID:
255809
Filename:
Python
Updated:
2014-01-30 19:02:16
Tags:
python flashcards
Folders:

Description:
Learn Python
Show Answers:

Home > Flashcards > Print Preview

The flashcards below were created by user sddcom1 on FreezingBlue Flashcards. What would you like to do?


  1. How do you assign string
    var = " sting in "
  2. How do you concat strings
    • Use the + sign either "   "xxx" + "xxx " or 
    • var 1 + var 2
  3. How do you multi line test
    Either use triple quotes """ and it will take into account white space or use start with quote at end of each line n
  4. string length starts at what number
    string length starts with 0
  5. How do you reference a string character
    • string character referenced by brackets 
    • var[1]  var [x] where x is a character
  6. How do you reference a string from the end
    varx[]
    • From the end the you use a -1 
    • varx[-1:]
  7. What is slicing in python in relation to a string
    Slicing referencing a range of characters.
  8. varx =  "This is the end"
    how do you reference the first word, the last word and the whole string
    • To reference the first word varx[0:4]
    • the last word  varx[-1:-4]
    • the whole string varx[1:]
  9. A list in Python is equivelant to what in other languages?
    A list in Python is equivelant to arrays in other languages
  10. What is the format for a list in Python
    Format for list is name = ['xxx','xxx']
  11. What is a nested list how do you create them
    Nested Lists are lists of lists. You create them by referencing the list in the nested list not putting it in quotes
  12. How do you test for an item in a list what does it return 
    Say if Monty is in Lista
    • To test for item
    • in list put item in list use key word 'in' comes back true if it is in list
    • false if not
    • 'monty' in lista = true if 'monty' is a item in the list or else false
    • if item in a list in a list the items in the nested list will not show as
    • true
  13. How do you or index slice a list and what is a slice and index
    • A index is a item in a list. Say the first item it would be x[1]
    • A slice is a range in a index say the first three items x[1:3] is a range
  14. How to you index a nested list say
    • Nested_List[-1][1]
    • gives you the last item of the Nested_List the first item in that
  15. What is Mutible when used on a list
    • Mutible is changing a list item list is
    • changing a item in a list that is done by calling the list item and assigning
    • it to a new item list[1] = 'xxx' this changes element 1 to xxx and puts it in
    • the list
  16. How do you change ranges of a list in Python
    • To change ranges in a list reference it and place the new items in a list it will add them to the list but as items not a list in a list
    • nested_list-1:] =['xxx','yyy'] - This will add 'xxx', 'yyy' to the last item of the list
  17. What is the list method that adds to the end of a list say on var  nested_list
    • The list method that adds something to the end of a list is append. It adds one element and the format is
    • nested_list.append('item')
  18. What method to a list do you use to insert a item into a list say  the first item of a list inserting 'super'  to nested_list
    • To insert to a list use the method .insert(element,'item') this inserts at item 1 the contents in the single quotes item'
    • nested_list.insert(1,'super') at item one will insert super and all items after it will be moved up one.
  19. To add a list to another list at the end what Python method do you use.
    Say another_list ['python', 'rocks']
    to nested_list'  ['tuts','plus']
    To add list to the end of another list use the method extend together you use the key word  .extend(<list>] to the list

    nested_list.extend(another_list) puts another_list at the end of nested_list
  20. To take items out of a list what method do you use say the item 'python' out of the list nested_list which equals
    nested_list = ['the','mighty', python', 'and']
    • Use the method remove
    • nested_list.remove('python') -- removes python from the list nested_list
  21. What is a tuple how does it look
    A tuple is a unmutable list meaning you can't change an item. it looks like a list but not in square brackets [ ] it is wrapped around parenthanses ( )
  22. Say a tuple is
    >>>  tuple('one', 'two', 'three') How do you index item 2 in the tuple
    • To index item 2 in the tuple the second item to bring up do
    • >>> tuple('one', 'two', 'three')
    • >>> tuple[2]'three'
  23. How do you slice a tuple
    say >>> tuple('one', 'two', 'three') get the first two items
    • Slicing is getting a range to get the first two items of
    • >>> tuple('one', 'two', 'three')
    • >>> tuple[:2]
    • returns ('one', 'two')
  24. You can nest tuples how to you nest
    >>> tuple('one', 'two', 'three')

    >>> tuple2('tuts', 'plus')
    • >>> tuple3 = tuple2,tuple
    • >>> tuple3(('tuts', 'plus'), ('one', 'two', 'three'))
  25. Can you change items in a tuple
    • You cannot change items in a tuple you get an error
    • >>> tuple('one', 'two', 'three0')
    • >>> tuple[1] = '2'T
    • You get the error
    • Traceback (most recent call last):  File "<pyshell#15>", line 1, in <module>    tuple[1] = '2'TypeError: 'tuple' object does not support item assignment
  26. What does this code docount = 10**3
    nums = []
    for i in range(count):
      nums.append(i)
      nums.reverse()
    it assigns i to be each number of count range 0 to count and places it in the list nums by the append. Then reverses the list by the method append
  27. “camouflaged” loops we find in list (or set or dict) comprehensions
    say
    seq = [1,2,3,4]
    than assigment
    squares = [x**2 for x in seq]
    what is squares
    squares = [1,4,9,16]

    The assigment

    • squares = [x**2 for x in seq]
    • Loops through seq building the list squares
  28. What does this nested loop do

    seq = [1,2,3,4,5]
    s = 0

    for x in seq: 
      for y in seq:  
       s += x*y
    • This nested loop will
    • sum up all the all possible products of the elements in seq,
    • for example:
    • seq = [1,2,3,4,5]
    • s = 0
    • for x in seq: 
    •   for y in seq:  
    • s += x*y

    s = 225
  29. What is a set ?
    A set is an unordered collection with no duplicates
  30. if a list is
    cars = ['honda','ford','dodge','chevy','honda','dodge']
    how do you create a set out of cars called autos
    • cars = ['honda','ford','dodge','chevy','honda','dodge']
    • autos = set(cars)
    • set(['dodge', 'chevy', 'honda', 'ford'])
  31. What operator do you use to find out what is on one set but not another
    • use the - minus operator
    • print "motos = " + str(motos)
    • print "autos =  "  + str(autos)
    • set(['yamaha', 'honda', 'bmw', 'harley'])
    • motos = set(['yamaha', 'honda', 'bmw', 'harley'])

    • print "set motos but not in autos " + str(motos - autos)
    • set motos but not in autos set(['harley', 'bmw', 'yamaha'])
  32. to find items in set1 or in set2 what operator do you use

    motos = set(['yamaha', 'honda', 'bmw', 'harley'])
    autos =  set(['dodge', 'chevy', 'honda', 'ford'])
    • Use the or operator = |
    • print "set motos or in  in autos 
    • use or operator |" + str(motos | autos)
  33. To find what is in set1 and set1 what operator

    motos = set(['yamaha', 'honda', 'bmw', 'harley'])
    autos =  set(['dodge', 'chevy', 'honda', 'ford'])
    Use the and operator '&'

    set motos and in  in autos  use and  operator &  set(['honda'])
  34. What is a dictionary in Python and what is the format
    • Dictionaries in Python are like associative arrays in other languages.
    • An unordered collection of key value pairs. create them with curley braces {}
    • The format for dictionary is dict = {'key': 'value'}
  35. If dictionary is
    If dict = {'name' : 'Jesse', 'location' : 'Denver', 'awsome' : 'yep!'}
    How do you print out the location
    print dict['location']
  36. if dictionary is
    dict = {'name' : 'Jesse', 'location' : 'Denver', 'awsome' : 'yep!'}
    How do you add 'favorite site' :'tutsplus'
    dict['favorite site'] = 'tutsplus'
  37. if directory is dict = {'name' : 'Jesse', 'location' : 'Denver', 'awsome' : 'yep!'}
    How do you delet 'location' pair from dict
    • del dict['location']
    • dict is now  {'awsome': 'yep!', 'name': 'Jesse'}
  38. To see all the keys in a dictionary you use say in dictionary = dict
    {'name' : 'Jesse', 'location' : 'Denver', 'awsome' : 'yep!'}

    What do you need to enter
    • dict.keys() will return all the keys in dictionary
    • equal to
    • ['awsome', 'name', 'location']
  39. if dictionary keys are ['awsome', 'name', 'location'
    ]How to you enter to see if 'name is a key in dict
    • you enter 'name' in dict
    • returns True if in or False if not in
  40. If conditionals what is the format say if length of name is less than 5 characters
    You have the condition if, the condition the colon : what you do next line indented

    • if len(name) < 5:  
    •      print "Your name has fewer than 5 charactors"
  41. If condition what is the format of an else if say if
    if len(name) < 5:   print "Your name has fewer than 5 characters"
    How do you add a else if if name is equal to 5 characters
    • if len(name) < 5:  
    •     print "Your name has fewer than 5 characters"
    •  elif len(name) == 5:        
    •      print "your name has excatly 5 characters"

    the name for else if is  'elif'  Colens after the comparsion condition
  42. You can nest if statments in one another say here How would you add in if  yourname has 5 characters and equal to Steve print out "Hay Steve" after printing your name has excally 5 characters.

    if len(name) < 5:  
       print "Your name has fewer than 5 characters"
    elif len(name) == 5:        
        print "your name has excatly 5characters"
    else:        
       print "Your name has greater than 5 characters"
    • if len(name) < 5:  
    •   print "Your name has fewer than 5 characters"
    • elif len(name) == 5:        
    •    print "your name has excatly 5 characters"        
    •    If name == "Steve":      
    •      print "Hay Steve"
    • else:        
    •     print "Your name has greater than 5 characters"
  43. You can combine conditions or statments by using the == sign  for each statment sperated by the 'or'
    Here is an example
    dinner = raw_input('Please choose pizza or spaghetti: ')

    • if dinner == "pizza" or dinner == "spaghetti":  
    •    print "bon appetit!"
    • else:  
    •    print "you can't have ",dinner, "for dinner"
  44. For loops in python are equal to what in other languages?
    For loops in python are equal to for each loops in other languages
  45. You have a list
    languages = ['python', 'java','C++','PHP']

    How would you loop through it print it out with the string
    "rocks" after each item
    • languages = ['python', 'java','C++','PHP'
    • ]for language in languages:  
    •       print language, "rocks"
  46. you can loop through a dictionary to print the key and the value of the key
    say the dictionary is
    dict = {"name":"Jesse","locattion":"Denver","favorite site":"tutsplus"}

    How to you loop through to get an output like this disregard the order

    his favorite site is tutsplushis
    name is Jessehis
    locattion is Denver
    • dict = {"name":"Jesse","locattion":"Denver","favorite site":"tutsplus"}
    • for key in dict:  
    •     print "his",key, "is", dict[key]
  47. Range in python creats a list of the range whatever you assign how would you print outa range of the first 10 integers
    • print range(10) 
    • gives you this
    • [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  48. You use range(x) for incrementing in loops like a counterHow would you loop through a range to print out the first 10 integers in the formint = 0
    int = 1i
    nt = 2
    int = 3
    int = 4
    int = 5
    int = 6
    int = 7
    int = 8
    int = 9
    • for int in range(10):  
    •   print "int =",int
  49. While  loops do what
    While loops allow you to do something while a condition is true
  50. Use a while loop to print out  this statment
    0 count is less then 10
    1 count is less then 10
    2 count is less then 10
    3 count is less then 10
    4 count is less then 10
    5 count is less then 10
    6 count is less then 10
    7 count is less then 10
    8 count is less then 10
    9 count is less then 10
    • count = 0
    • while count <10:  
    •    print count,"count is less then 10"  
    •    count +=1
  51. for i in range(10): 
    print "i =",i

    how do you break out of the loop when i is 5
    and then print "done looping"
    • for i in range(10): 
    •    print "i =",i 
    •     if i ==5:      
    •      break
    • print "done looping"
  52. You can use the continue in a loop that will execute if a condition is met
    Just information
    You can use the continue in a loop that will execute if a condition is met
  53. if you have a for loop or if statment that does nothing you get an error "expeted an indented block"
    How do you avoid that?
    • for i in range(2):   
    •    pass
  54. how do you define a function
    use the def keyword it defines a function

    def madlib():   

    print "The nerdy jesse ate all the pizza"

    this does nothing for madlib was not called
  55. if you have a function called
    def madlib():   
        print "The nerdy jesse ate all the pizza"

    How do you execute it
    • def madlib():  
    •     print "The nerdy jesse ate all the pizza"

    madlib()

    this wil execute it

    The nerdy jesse ate all the pizza
  56. You can pass arguments to functions say replace jesse with a string variable name

    def madlib():   
    print "The nerdy jesse ate all the pizza"

    madlib()
    • def madlib(name):   
    •   print "The nerdy %s ate all the pizza" % name

    madlib('scott')

    This will use %s string type the argument will be name
  57. You can pass arguments to functions say replace jesse with a string variable name and neardy with an adjective

    def madlib():   
      print "The nerdy jesse ate all the pizza"
    • def madlib(adjective,name):  
    •   print "The %s %s ate all the pizza" % (adjective,name)

    madlib('asshole','scott')

    Returns

    The asshole scott ate all the pizza

    This takes two arguments
  58. Use default values in functions so if you don't include them they will default to the defaults
    • def madlib(adjective='thirsty',name='adam'):   
    •   print "The %s %s ate all the pizza" % (adjective,name)

    madlib()

    The thirsty adam ate all the pizza
  59. You can make call statments in functions more readable by including the reference argument to the call function
    • def madlib(adjective='thirsty',name='adam'):  
    •   print "The %s %s ate all the pizza" % (adjective,name)

    madlib(adjective='hungry',name='jimmy')

    The hungry jimmy ate all the pizza
  60. In functions you might want to reference multiple arguments without having to reference each argument.

    How do you do it
    • def shoppingCart(itemname, *avgPrices):    
    •   print avgPrices

    shoppingCart('computer',100,120,34)     

    Returns this tuple

    (100, 120, 34)
  61. In functions you might want to reference multiple arguments without having to reference each argument. You can loop through the multiple arguments in the function
    • def shoppingCart(itemname, *avgPrices):   
    •      for price in avgPrices:    
    •       print 'price',price

    gives you

    • price 100
    • price 120
    • price 34
  62. What does this return

    def shoppingCart(itemname, **avgPrices):     
     print avgPrices

    shoppingCart('computer',amazon=100,ebay=120,bestBuy=34)
    It returns a dictionary

    {'amazon': 100, 'bestBuy': 34, 'ebay': 120}
  63. The dictionary is
    {'amazon': 100, 'bestBuy': 34, 'ebay': 120}
    Keys and values

    def shoppingCart(itemname, **avgPrices):
      for price in avgPrices:     
    print price,'price:',avgPrices[price]

    shoppingCart('computer',amazon=100,ebay=120,bestBuy=34)

    Want to print out the key and the item
    like

    amazon price:  100
    bestBuy price:  34
    ebay price:  120
    • def shoppingCart(itemname, **avgPrices):
    •   for price in avgPrices:    
    •   print price,'price: ',avgPrices[price]

    shoppingCart('computer',amazon=100,ebay=120,bestBuy=34)

    • price in avgPrices is the key and
    • avgPrices[prices]  is the item
  64. What does this do

    def dbLookup():   
      dict = {}   
      dict['amazon'] = 100   
      dict['ebay'] = 120   
      dict['bestBuy'] = 34   
      return dict

    def shoppingCart(itemname, avgPrices):  
       print 'item ',itemname  
      for price in avgPrices:     
      print price,'price: ',avgPrices[price]

    shoppingCart('computer',dbLookup())
    • You define a dictionary and return that to the second
    • item of shopping cart


    • item  computer
    • amazon price:  100
    • bestBuy price:  34
    • ebay price:  120
  65. If a variable is not defined inside a function but global if the function calls it it will get the variable from the global

    If a function declares a variable inside it even though it is the same name as a global variable when the function calls it it will use the function assigment
    that;s the answer
  66. You can declare a variable global inside a function and it will always use the global assigment even though you assign a function to it the same name
    the answer
  67. Recursion is what
    When you call a function from itself.
  68. def factorial(number):   
       if number == 1:     
          return 1   
      else:     
         return number*factorial(number-1)
           print factorial(5)

    print factorial(5)

    what is this how does it work
    recurssion calls itself till it hits 1 then returns the factorial
  69. What are modules in python

    What is the python standard library
    Modules are files containing python definitions and statements


    The python standard library contains built in modules that allow us to access system functionally and functions created by other python programmers
  70. In order to use a module you use the following syntex import <module> declaration
    import <module>
  71. Where do you get a list and explatationof python modules
    Python has a lot of modules included that you can view on the python documention on their website

    http://docs.python.org/3/py-modindex.html
  72. How do you reference a function in a module
    To reference something in a module after you include it you <module>.<function>(arguments)

    ex

    • import os
    • os.chdir('/home/steved')
    • print os.getcwd()

    prints

    >>> /home/steved
  73. If you are only using one function in a module you can import just that  functionthe format is what
    • from <module> import <module.function> but then you don't use the module quilifies youonly use the function name
    • example

    from sys import

    argvprint argv
  74. You can reference arguments to python scripts by using the from sys import argv
    how do you reference the last argument in a python script
    argv[-1]
  75. Module re.search is used to match objects it returns a match object which is a memory location to return what it references you need to use the .group()
    example

    import reprint

    re.search('a','apple').group()  returns 'a'

    re.search('a(.*)e','apple').group()   returns 'apple'

    print re.search('a(.*)e','apple').group(1) returns 'ppl'
  76. What does this do

    import re

    print re.findall('w+@w+.com','email 1 is jesseshaw@gmail.com and email2 is bob@exammple.com')
    • here the w is all alfa a-z,A--Z,_,0-9 then the @ sign
    • followed by .com

    It finds all the emails

    ['jesseshaw@gmail.com', 'bob@exammple.com']
  77. To find all the paths that python looks for what do you do?
    • at ptyhon prompt
    • >>> import sys
    •  >>> type sys.path
    • that gives you all the places python looks for built in modules.
  78. To use a module you can
    We can append a directory with the module we want to use to the end of sys.path  with sys.path.append<path>
    What is the problem with that
    • The problem is that you would have to do this every time you use python.
    • A better way is
    • Another way is to create a path configuration file, so python looks in our custom directory every-time.
  79. In ubuntu where are the libraies located where python looks for modules
    '/usr/lib/python2.7/dist-packages'
  80. $ cd /usr/lib/python2.7/dist-packageshere at this directory you can
    $sudo nano <filename (he used mymodules.pth  for my modules path) 
    then after entering your password you get into nano file editor.
    • type in the path for the custom modules directory for me it is
    • /home/steved/python   ctrl-o to write  ctrl-x to exityou can check it
    • from python >>>import.sys>>>sys.paththen to use at
    • python >>>import <module>
  81. In python to read a file in the same directory that the file is located in what do you type to open the file?
    you open the file with the command

    • >>>file = open('<filename>,'r')  
    • - this opens a file for reading
  82. Once a file is opened with
    >>>file = open('<filename>,'r') you can read the file in python how?
    • file.read()  
    • This returns the file as a string each line sperated by /n
  83. In order to close a file that is opened what do you type at python
    >>>file.close()

    This frees the file from system memory.
  84. In order to read a file as a list what do you do ?
    • >>>file = open('<filename>')
    • then
    • >>>file.readlines()  reads the file as a list
  85. To loop thorugh a file that is done frequently do you open the file what do you do?
    file = open('<filename')

    Loop through each line of the list using a loop

    • >>>for line in file     
    •    pirnt "LINE: ", line
  86. To append to an end of a file you open a file in append mode
    what is it and how does it work?
    • >>>file = open('<filename>', 'a')
    • >>>file.wirte('<text to file>')  will add it to the end of the file
    • You will not get written to the file till it is closed
    • sometimes you needto add a /n   before you do your inputs in order to get a newline.
  87. To open a file for reading and writing at the end of the file what command do you use ?
    You use the file = open('<filename>',''r++)
  88. If you add a b to any file commands like '+r' , '+w' '+rr.
    What is that for
    you can read and write binary files jpeg exe files. In windows the 'b' might corrupt them but in mack or lynnix system it will not
  89. You can combine open and close in python files by using the with open
    • with open('<filename>') as <name>:   
    •    name.read()

    this will open the file read it and close it
  90. PIckling in python is used to save lists, dictionaries and other data structures in files.
    import pickle
    data = open('mydata.pkl','w')
    cred = {"user" : "jesse", "pass""essej"}
    pickle.dump(cred,data)
    data.close()
    • You import the pickle modules
    • create an object name 'data' set to open since it wasn't created will create it and open for writing
    • created a dictionary called cred for "credentals"
    • use pickle.dump to dump  (takes the object to store and then where) here the dictionary into data
    • then close the data object.
  91. to retrieve a dataobject stored with pickle do
    • Create a data object to open the file
    • >>> <dataobject> = open(<datafile>, 'r')
    • >>>pickle.load(<datafile>)

    this will retrieve the dataobject
  92. Class you create a class and give it attrbutes using the formclass <classname>:

    you create a instance of the class<classinstance> = <class>()
    ok
  93. In a class you can assign attributes and give them default value.

    After the class is defined you can change the attributes and what
    when instanance a class these values will be the defaults

    After a class is defined the attributes can be changed and are stored in the class instance
  94. When declaring methods in classes format line format is very important

    class house:   

       doors = 10     

      def slamDoors(self):    
            for door in range(self.doors):         
               print "SLAM!"     

    myhouse = house()
    myhouse.slamDoors()
    indents def linedup below door declaration

    • the declaring the method and calling the method are
    • formatted too at beginging
  95. Methods are bound to a class when you declare a method in the class you use the 'self' declaration if not you get a similar error to this
    File "/home/steved/python/oop.py", line 15, in <module>   

    myhouse.slamDoors()TypeError:

    slamDoors() takes no arguments (1 given)>>>
  96. When defining methods in classes you need to bind the class variable how
    to the method by using  self.<variableName>
  97. class house:   
       doors = 10   

       def addDoors(self,number):       
           self.doors = number     

       def slamDoors(self):      
           for door in range(self.doors):         
             print "SLAM!"           

    myhouse = house()myhouse.
    addDoors(2)myhouse.slamDoors()
    self binds to the class
  98. what is encaplasulatin
    encaplasulation is keeping methods and attributs private from the outside world meaning outside the class. when declaring a variable in a class you want to keep hidden from outside the class use double underscore '__'
  99. How do you reference an encaplasulated attribute in a class
    You need to do it inside the class
  100. Constructors allow you to do what in a class
    Constructors allow you to create default values whenever you create an instance of a class

    example

    class house:

    • def __init__(self):     
    •    self.doors = 4
  101. Constructors can have default values like functions that can be overwritten when you instanance the class
    example

    class house:

    •     def __init__(self,doors=3):    
    •        self.doors = doors

    myhouse = house(53) 

    - sets doors to 53 if no argument it would be 3
  102. Inheritance of a class is what
    • interference which are classes that inhereant form another class but have other attributes the base class doesn't have
    • This way you can have methods the inherentenced class can access but the bass class can't
  103. Polymorphism of classes allows you do do what ?
    Polymorphism of classes allows you to access methods of the same names to different classses so if you inherenent a class the you declare a method with the same name in each inherented class it can do different things depending on the inherentend class
  104. errors cause programs to bomb. One way to protect is to use what ?
    • try: method with except <error> will try if it in-counders an error will not bomb the program.
    • You use the else if you want it to do something if there was no error
    • example

    If it hits this error it will pass thorugh and execute the print statment

    • try:   
    •   open('fakefile')
    • except IOError:   
    •      print "Unable to open file"
    • else:
    •    print "No problem opening the file"
    • print "this is important"


    print "this is important"
  105. raw_input([prompt]) what is raw_input?
    • If the prompt argument is present, it is written to standard output without a
    • trailing newline. The function then reads a line from input, converts it to a
    • string (stripping a trailing newline), and returns that.
  106. You can create your own exceptiions how?
    If you have an imput or something you can test it and type raise ExceptionIt will flag it and stop the program but will not give you any meaningful data

    example

    • def makeDinner():   
    •   userinput = raw_input("Please choose a dinner item: ")   
    •    if userinput == "ice cream":       
    •       raise Exception  

     makeDinner()   

    the exception will be this

    Traceback (most recent call last):  File "/home/steved/python/excepthons.py", line 8, in <module>    makeDinner()  File "/home/steved/python/excepthons.py", line 6, in makeDinner    raise Exception
  107. If you make your own user exceptions you can pass arguments to the raise Excetpions in order to make it more meaningful.
    If you have a user exception block that raises exceptions you can make it more meaningfule by passing arguments to the exception to make it more meaningful. It will print all the error stuff plus what you type as the passing arugument.
  108. if you want to print out multiple exception errors to a block and omit the machine error codes what do you do?
    • make a try section where you call the function
    • set an

    • except Exception explanation:
    •    print <"errormessage">, explantation

    this will print out what you type in the raise Exception block
  109. a nice exception block with a sub class or class "Exception?
    • class DinnerError(Exception):   
    •    pass

    • def makeDinner():   
    •    userinput = raw_input("Please choose a dinner   
    •                 item: ")   
    •     if userinput == "ice cream":       
    •           raise DinnerError("Not nutritious enoug")   
    •      if userinput == "computer":       
    •          raise DinnerError("Not a dinner error")

    • try:     
    •     makeDinner()
    • except DinnerError, explanation:     
    •      print "Error", explanation
  110. In order to work with web pages what module do you need to import
    import the module  urllib — URL handling modules
  111. You can open a url as a object how?

    How would you make it so you
    • You can open a url as a object with
    • importing urllib

    then <objectname> = orllib.urlopen(<web address>)this opens the web page as an object

    To read the source code for the page print

    print <objectname>.read()

    example

    import urllib

    • html = urllib.urlopen("http://jshawl.com/python-
    •        playground/")

    print html.read()
  112. In order to extract email address from a web page you need two i
    mport modulesI
    mport ulllibimport re     (this for regular expresssions
    example

    html = urllib.urlopen("http://jshawl.com/python-playground/").read()

    print re.findall('[\w]+@[[\w.]+',html)

What would you like to do?

Home > Flashcards > Print Preview