User Tools

Site Tools


Lab 1 - Introduction to Python

To work through these exercises, use the reference materials on the main course page. The hints are there for a quick reference, but you'll probably need to look a few things up as well.

  1. Hello World:
    Create a program called that prints “Hello World!” on the screen.

    # HINT: Typical print statement
    print "This gets printed!"
  2. Creating a Function:
    Add the function greet to your program, which takes a person's name as input and prints out a greeting addressed to that person. Call your new function with your own name from within the program.

    # HINT: Declaring and calling a function
    def myfunc(x):
       """ Prints out the value of x, regardless of type """
       print x
    # Let's use our function to print out the number 3
  3. Using a List:
    Declare a list of names, called friends, in your program and then make the program greet everyone on that list.

    # HINT: Printing out all the members of a list, regardless of type
    mylist = [1,3,5,'A','B']
    for x in mylist:
       print x
  4. Randomness and Command Line:
    Instead of greeting each friend once, make the program greet one at random and repeat this process as many times as you specify on the command line when you launch it.

    # HINT: Picking a random entry
    import random # Import the 'random' functions module
    # Print a single random entry from a list
    print random.choice(['A',4,'B','hello'])
    # NOTE: 'random.choice' means you're calling 'choice' from 
    #       the module 'random', however, to save yourself the typing 
    #       of the module name every time you call a specific function 
    #       from it,  you could also have imported it explicitly first:
    from random import choice
    print choice(['A',4,'B','hello'])
    # HINT: Reading a command line argument
    from sys import argv # Import the command line argument list 'argv'
    if (len(argv)>1):    # Only if some arguments exist...
       print argv[1]     # ...print the first argument (They are all strings)
    # HINT: Converting a string to a number and looping 
    i = int('3')
    for j in range(i):  # j = 0, 1, 2 
       print j
  5. A Class:
    Add the class Tool to your program. This class represents a useful object that is made from some particular material. The problem is that the tool sometimes breaks when it is being used, depending on its material strength. You will simulate this behavior with this class.
    1. Initialize the Tool class properties name, material and working in the constructor, with the first two being passed in and the last one set to the default value of True.
    2. Add the method use to the class, which prints out “You can't use this broken [name]” if the tool is not working (working is False), prints out “Dang! The [name] just broke!” (ands sets working=False) if a test of material strength fails (see next) or prints out “The [name] really came in handy!” if nothing catastrophic occurs.
    3. To help with testing the material strength, declare a global dictionary called material_strength, keyed on material names (like “glass”, “plastic”, “wood”, “metal”) and mapping them to strength values between 0 and 100 (your choice).
    4. The test in the use method of a tool fails if a random value in the 0 to 100 range is higher than the strength of the item's named material.
    5. Declare a global list of instanced tools (like “hammer”, “glasses”, “blender”, “raygun”…) and make the program use them all to see if your class works.

      # HINT: Creating a new class
      class MyClass:
         """ This is a simple class with two properties, one of which is 
             set through a parameter passed into the constructor """
         def __init__(self, x):
         """ Pass in a value of x, which will get stored along with the default
             value of y.  Note that 'self' is a reference to the class instance and
             gets passed in automatically - but has to be included in the definition """
            self.x = x
            self.y = "defaultY"
         def show(self):
            print "I have x="+str(self.x)+" and y="+str(self.y)
      # Let's creat an instance and call the show method
      c = MyClass(5) # It should print "I have x=5 and y=defaultY"
      # HINT: Creating and using a dictionary (also called a map or a hash table)
      mydict = {"A":20, "B":30, "C":"Hello"}
      print mydict["B"] # Prints 30, which is the value associated with the key "B"
  6. List of Tuples of Objects:
    Make your list of friends now contain a list of tuples where the first element is the friend's name like before, but the second element should be a list of 2-3 instanced tools in that friend's possession. Make your program pick one person at random, greet them, and then ask to borrow one random tool from them and finally try to use that borrowed tool. As before, have the program repeat this as many times as you specify or until tools have been unsuccessfully used 10 times in a row (you can make the use method return True or False to help you keep track).

    # HINT: A tuple is an immutable sequence, unlike a list which can be modified.
    mytuple = (3, 5, 7)
    # HINT: Tuples, like other sequences can contain any types of objects
    mytuple = (3, "Hello", MyClass(5), [7, 6, 4])
    # Any contained object can be referenced
    print mytuple[1]     # Prints "Hello"
    mytuple[2].show()    # Prints "I have x=5 and y=defaultY"
    print mytuple[3][0]  # Prints 7
  7. Searching Lists:
    Add the function fix to your program that takes in a single Tool and forces its working value to True. Declare a list of names, called favorites, and instead of quitting after 10 failed attempts at using borrowed tools, make the program fix all tools possessed by those that have their name appear on the favorites list, but not the others. Print out the names of those that got their tools fixed and let the program borrow a few more tools to see if it can now continue it's habit a bit longer.

    # HINT: Finding matches between two lists
    listA = [1, 3, 5, 7, 9]
    listB = [4, 5, 6, 8, 9]
    for x in listA:
       if x in listB:
          print str(x)+" is common!"  # Prints "5 is common!, 9 is common!"
  8. EXTRA: Networking and XML:
    Give each tool a price in some foreign currency and when you break it, print out its value in ISK. Use an up-to-date currency exchange rate, like the one you can get here in XML format:

    # HINT: Reading and parsing a source on the Internet
    import urllib                # Module for simple Internet sockets
    from xml.dom import minidom  # Module for simple XML handling
    # We'll call the Yahoo RSS weather service and request info for Reykjavik (ICXX0002)
    rssweather_socket = urllib.urlopen("")
    rssweather_xml = minidom.parse(rssweather_socket) 
    # We can extract XML elements by name (we get a list, but only take the first match)
    current_weather_element = rssweather_xml.getElementsByTagName("yweather:condition")[0]
    print "Current temperature in Reykjavik is "+ current_weather_element.getAttribute("temp")+" deg. Farenheit"
    # Here we got the attribute of an element node, but to get the text of a text node, we can use node.nodeValue
/var/www/ailab/WWW/wiki/data/pages/public/t-vien-11-1/lab_1_materials.txt · Last modified: 2011/05/02 09:52 by hannes