100 likes | 216 Views
Lecture 21. Review of functions and dictionaries; Intro to Unix. A Dictionary problem.
E N D
Lecture 21 Review of functions and dictionaries; Intro to Unix
A Dictionary problem • 6. CourseDict is a dictionary which is indexed by course names such as “CSC117”. CourseDict[“CSC117”] is a list of all the students who are currently registered in the class. It is used by the registration program to add students to their desired classes. So for example, early in the process, CourseDict[“CSC117”] might be equal to the list [“George Brown”, “Molly Black”]
Write the code for the following function. Be sure to handle the case that a particular course is not yet in the dictionary • def addStudent (dict, name, courseList): #dictis a dictionary such as the one described #above, name is the name of the student who is #registering, and courseList is the list of courses the #student wishes to take. #the function adds the student to all the desired #courses. The function returns the modified #dictionary. Assume unlimited room is each course!
def addStudent (dict, name, courseList): for c in courseList: if dict.has_key(c): dict[c].append(name) else: dict[c] = [name] return dict
Josh Burns wishes to take CSC117, REL110, ART116 and MAT170. What line(s) of code would use this function to record his request in CourseDict • CourseDict = addStudent(CourseDict, “Josh Burns”, [“CSC117”, “REL110”, “ART116”, “MAT170”] ) Note: We should assign the result of addStudent to CourseDict because the function returns a value. It should be noted that the dictionary is changed by the function even if the modified dictionary is not returned.
def getData(): #returns a non-empty list of numbers from the user def countPos(aList): # returns the number of positive numbers in aList def countNeg(aList): #returns the number of negative numbers in aList def detWinner( posTeam, negTeam): # returns the string”positive” if the first number is greater #and the string”negative” if the second number is greater Write a main() that uses all of these functions. It asks the user for a bunch of numbers, and prints whether there are more negative or positive numbers on the list. It should simply print “positive” or “negative depending on which occur more frequently on the list.
Introduction to cgi programming How to process a form
<html> <head> <title> First example </title> </head> <body> <form action = "cgi-bin/test.py" method = "get"> <form> Please enter your name. <input type = "text" name = "name"> <br> <input type = "submit"> </form> </body> </html>
#!/usr/bin/python print "Content-type: text/html" print import cgi import cgitb cgitb.enable() form = cgi.FieldStorage() fname = form.getvalue("name") print "<html>" print "<head> <title> Reply </title></head>" print '<body >' print print "<h2> Hello, " + fname + "<br>" print "</body></html>"