====== 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. - **Hello World:**\\ Create a program called **''myhello.py''** that prints "Hello World!" on the screen. \\ \\ # HINT: Typical print statement print "This gets printed!" - **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 myfunc(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 - **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 - **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. - 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''**. - 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. - 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). - 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. - 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) c.show() # 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" - **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 - **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!" - **EXTRA: Networking and XML:**\\ Instead of using the **''favorites''**, only fix tools for those that exist in the online Símaskrá (http://www.simaskra.is). \\ \\ # 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("http://weather.yahoo.com/forecastrss?p=ICXX0002") rssweather_xml = minidom.parse(rssweather_socket) rssweather_socket.close() # 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 is "+ current_weather_element.getAttribute("temp")+" deg."