| | |
Starting Python
![]() | View First Unread |
I know you have seen hints of this before, but you can use formatted print to display the key:value of a dictionary. Here is an example ...
Also note that %s can be used for strings and raw numbers.
python Syntax (Toggle Plain Text)
# when you set up variables like ... book = "Python for Nuts" pages = 223 scripts = 77 # Python keeps this information in a local dictionary called up with vars() print vars() # { ... , 'pages': 223, 'book': 'Python for Nuts', 'scripts': 77, ... } # now you can show the results like this ... print "%s has %s pages and contains a total of %s code examples" % (book, pages, scripts) # or take advantage of vars() ... print "%(book)s has %(pages)s pages and contains a total of %(scripts)s code examples" % vars()
Last edited by vegaseat; Mar 1st, 2007 at 4:06 pm. Reason: [code=python] tag
May 'the Google' be with you!
The request came up on the forum for some typical Python class sample code. Here is my nickles worth:
python Syntax (Toggle Plain Text)
# manage the contents of a basket # note: # "self" keeps track of instances, here basket1 and basket2 # it has to be the first argument of a class method/function class Basket(object): """ a class to add elements to a list and display the result default is an empty basket """ def __init__(self, contents=[]): # make a true copy of contents list to avoid surprises contents = contents[:] self.contents = contents def add(self, element): # add elements to the basket (list) self.contents.append(element) def remove(self, element): # remove an element from the basket if element in self.contents: self.contents.remove(element) else: print element, " not in basket!" def print_me(self): # print out the list elements as a string result = " ".join(self.contents) print "Basket now contains:", result # basket1 instance of the class, it is an empty basket basket1 = Basket() # add items to basket1 basket1.add('pins') basket1.add('needles') basket1.add('wurst') # basket2 instance starts out with contents of basket1 # and allows the user to add more elements basket2 = Basket(basket1.contents) basket1.print_me() print "Add things to the basket, use -thing to remove it:" while True: thing = raw_input("Enter a thing (press Enter only to exit): ") if thing: if thing[0] == '-': basket2.remove(thing[1:]) else: basket2.add(thing) basket2.print_me() else: break # final tally, show things now in basket2 print "Final tally:" basket2.print_me()
drink her pretty
Here is a simple linear equation solver:
python Syntax (Toggle Plain Text)
# a Python linear equation solver def solve(eq, var='x'): eq1 = eq.replace("=", "-(") + ")" #print eq1 # test c = eval(eq1, {var:1j}) #print c # test return -c.real/c.imag eq = "x-2 = 2*x" # example r = solve(eq) print "equation: %s\n result: x = %s" % (eq, r)
drink her pretty
Looking at Ene's Python class sample code, I realized that it would be nice to have a sample of class inheritance ...
python Syntax (Toggle Plain Text)
# class Teacher and class Student inherit from class SchoolMember # the base or super class class SchoolMember(object): '''represents any school member''' def __init__(self, name, age): self.name = name self.age = age def detail(self): '''show name and age, stay on same line (trailing comma)''' print 'Name: %-13s Age:%s' % (self.name, self.age), # use the base class as argument to inherit from class Teacher(SchoolMember): '''represents a teacher''' def __init__(self, name, age, subject): # call the base class constructor ... # it assigns name, age to self.name, self.age SchoolMember.__init__(self, name, age) self.subject = subject def detail(self): '''teaches this course''' SchoolMember.detail(self) print 'Teaches course: %s' % self.subject class Student(SchoolMember): '''represents a student''' def __init__(self, name, age, grades): SchoolMember.__init__(self, name, age) self.grades = grades def detail(self): '''student grades''' SchoolMember.detail(self) print 'Average grades: %d' % self.grades # teacher has name age and subject taught t1 = Teacher('Mr. Schard', 40, 'Beginning Python 101') # student has name, age and average grade (max 100) s1 = Student('Abigale Agat', 20, 92) s2 = Student('Bertha Belch', 22, 65) s3 = Student('Karl Kuss', 21, 98) s4 = Student('Tom Tippit', 22, 77) s5 = Student('Zoe Zeller', 20, 88) print '-'*55 # list of instances, Teacher t1 and Students s1 ... s5 members = [t1, s1, s2, s3, s4, s5] sumgrades = 0 for member in members: memberType = member.detail() try: sumgrades += member.grades except AttributeError: pass # this would be a teacher, has no grades so skip print "\n%s's students class-average grades = %d" % (t1.name, sumgrades/5) """ output = Name: Mr. Schard Age:40 Teaches course: Beginning Python 101 Name: Abigale Agat Age:20 Average grades: 92 Name: Bertha Belch Age:22 Average grades: 65 Name: Karl Kuss Age:21 Average grades: 98 Name: Tom Tippit Age:22 Average grades: 77 Name: Zoe Zeller Age:20 Average grades: 88 Mr. Schard's students class-average grades = 84 """
May 'the Google' be with you!
Some details on the use of modules in Python, heavily commented. Here is an example of a module:
Now the program that would use the above module:
If you have your module in a subdirectory of your own that is not on the PYTHONPATH then you can change the import statement:
python Syntax (Toggle Plain Text)
# modules should be saved to the same folder as the # program or to folders listed in sys.path() # save this module code as apple.py ... # (module-name and file-name.py have to match, are case sensitive!) def pieCookingStatus(cooking_time): if cooking_time < 35: print "Still cooking!" elif cooking_time < 40: print "Almost done!" else: print "Take pie out of the oven!" def piePercentCooked(cooking_time): """consider 40 minutes the fully cooked time""" return 100 * cooking_time/40 # optional, specify version number of module version = '1.2' # this test runs when this code is used as a standalone program, # but not as an imported module of another program, # then the namespace will be apple (name of module) and not __main__ if __name__ == '__main__': print "Pie is %d percent cooked." % piePercentCooked(33) pieCookingStatus(33)
python Syntax (Toggle Plain Text)
# test the module apple.py # import creates a namespace with the module's name (apple) # also Python creates a precompiled bytecode file apple.pyc for speed import apple # optional, check version if it has been specified if 'version' in dir(apple): print 'Version =', apple.version # optional, show namespaces used # note that namespace __name__ is assumed for this program # you don't have to use it, but you have to prefix the # modules namespace to functions/variables of the module # in this case prefix with apple and a dot print "Namespace of program:", __name__ # __main__ print "Namespace of module :", apple.__name__ # apple # also optional, list filenames used print __file__ # C:/Python24/Atest/AppleTest.py print apple.__file__ # C:/Python24/Atest/apple.pyc # now let's do something with the apple module minutes_cooking = 45 percent_cooked = apple.piePercentCooked(minutes_cooking) print "Pie is %0.1f percent cooked." % percent_cooked apple.pieCookingStatus(minutes_cooking)
python Syntax (Toggle Plain Text)
""" your program myprog.py may be in C:\Python24\myprog.py the module is in C:\Python24\directory1\directory2\module1.py C:\Python24\ would be listed in sys.path() (PYTHONPATH) """ # import modules from subfolders: from directory1.directory2 import module1
Last edited by Ene Uran; Dec 9th, 2006 at 12:07 pm.
drink her pretty
I am confused, why does this nice sticky continue somewhere else as csgal suggested. I went there and it sort of dead ends!
http://www.daniweb.com/techtalkforums/thread63753.html
http://www.daniweb.com/techtalkforums/thread63753.html
No one died when Clinton lied.
•
•
•
•
I am confused, why does this nice sticky continue somewhere else as csgal suggested. I went there and it sort of dead ends!
http://www.daniweb.com/techtalkforums/thread63753.html
May 'the Google' be with you!
Okay, with all that Administrator stuff out of the way let's return to the "Starting Python" sticky.
If you had a list of names with title, first, middle and last name, how would you sort that list by the last name only? Well here is a solution commonly used to sort lists by item or modified item:
If you had a list of names with title, first, middle and last name, how would you sort that list by the last name only? Well here is a solution commonly used to sort lists by item or modified item:
python Syntax (Toggle Plain Text)
# sort a list of names by last name def sort_names(names): """ sort names by last name, avoiding title, first and middle names """ names_mod = [] for name in names: # split each name into a list name_list = name.split() # pick the last name from list last_name = name_list[-1] # create a list of temporary sublists [last_name, name] names_mod.append([last_name, name]) # sort the modified list of names inplace # this will sort by the first item in the # sublists which is last_name names_mod.sort() # use list comprehension to # to remove the temporary last_name item return [name[1] for name in names_mod] names = [ "Dr. Heidi Karin Hirsch", "Miss Arlene Auerbach", "Mr. and Mrs. Larry Zoom", "Mr. Frank Paul Lummer", "Vicepresident Colter" ] print "Original list of names:" for name in names: print name print "List of names sorted by last name:" names_sorted = sort_names(names) for name in names_sorted: print name """ output --> Original list of names: Dr. Heidi Karin Hirsch Miss Arlene Auerbach Mr. and Mrs. Larry Zoom Mr. Frank Paul Lummer Vicepresident Colter List of names sorted by last name: Miss Arlene Auerbach Vicepresident Colter Dr. Heidi Karin Hirsch Mr. Frank Paul Lummer Mr. and Mrs. Larry Zoom """
drink her pretty
![]() |
Similar Threads
- CGPA calculator (Python)
- Beginning: Starting Python (Python)
- Clear the console screen (Python)
- Re: Starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: need help
- Next Thread: Python - Using a text file to feed into a python dictionary
| Thread Tools | Search this Thread |
access ada advanced anti api arax array beginner blogger blogging bug c++ code combo convert csv cx-freeze daniweb data database development dictionary digital dropdownlist embed event exam examples excel fanniemay file format function game gdata google gui images innovation input introduction itunes java joomla keycontrol linux list lists maze method microsoft module mouse mvcmodel2 net news obexftp parameters password php post problem program programming projects py2exe pygame pyopengl python random reuse reverse rss ruby script security shutdown skinning source sprite string syntax terminal text threading tutorial ubuntu url urllib urllib2 variable vb virus vista visual visualbasic6 web web-scrape wxpython xml









