Starting Python

Reply   View First Unread View First Unread

Join Date: Oct 2004
Posts: 4,003
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 927
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #81
Oct 14th, 2006
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 ...
  1. # when you set up variables like ...
  2. book = "Python for Nuts"
  3. pages = 223
  4. scripts = 77
  5.  
  6. # Python keeps this information in a local dictionary called up with vars()
  7. print vars() # { ... , 'pages': 223, 'book': 'Python for Nuts', 'scripts': 77, ... }
  8.  
  9. # now you can show the results like this ...
  10. print "%s has %s pages and contains a total of %s code examples" % (book, pages, scripts)
  11.  
  12. # or take advantage of vars() ...
  13. print "%(book)s has %(pages)s pages and contains a total of %(scripts)s code examples" % vars()
Also note that %s can be used for strings and raw numbers.
Last edited by vegaseat; Mar 1st, 2007 at 4:06 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,525
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 169
Ene Uran's Avatar
Ene Uran Ene Uran is online now Online
Posting Virtuoso

Re: Starting Python

 
0
  #82
Nov 8th, 2006
The request came up on the forum for some typical Python class sample code. Here is my nickles worth:
  1. # manage the contents of a basket
  2. # note:
  3. # "self" keeps track of instances, here basket1 and basket2
  4. # it has to be the first argument of a class method/function
  5.  
  6. class Basket(object):
  7. """
  8. a class to add elements to a list and display the result
  9. default is an empty basket
  10. """
  11. def __init__(self, contents=[]):
  12. # make a true copy of contents list to avoid surprises
  13. contents = contents[:]
  14. self.contents = contents
  15.  
  16. def add(self, element):
  17. # add elements to the basket (list)
  18. self.contents.append(element)
  19.  
  20. def remove(self, element):
  21. # remove an element from the basket
  22. if element in self.contents:
  23. self.contents.remove(element)
  24. else:
  25. print element, " not in basket!"
  26.  
  27. def print_me(self):
  28. # print out the list elements as a string
  29. result = " ".join(self.contents)
  30. print "Basket now contains:", result
  31.  
  32.  
  33. # basket1 instance of the class, it is an empty basket
  34. basket1 = Basket()
  35. # add items to basket1
  36. basket1.add('pins')
  37. basket1.add('needles')
  38. basket1.add('wurst')
  39.  
  40. # basket2 instance starts out with contents of basket1
  41. # and allows the user to add more elements
  42. basket2 = Basket(basket1.contents)
  43.  
  44. basket1.print_me()
  45. print "Add things to the basket, use -thing to remove it:"
  46. while True:
  47. thing = raw_input("Enter a thing (press Enter only to exit): ")
  48. if thing:
  49. if thing[0] == '-':
  50. basket2.remove(thing[1:])
  51. else:
  52. basket2.add(thing)
  53. basket2.print_me()
  54. else:
  55. break
  56.  
  57. # final tally, show things now in basket2
  58. print "Final tally:"
  59. basket2.print_me()
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,525
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 169
Ene Uran's Avatar
Ene Uran Ene Uran is online now Online
Posting Virtuoso

Re: Starting Python

 
0
  #83
Nov 8th, 2006
Here is a simple linear equation solver:
  1. # a Python linear equation solver
  2.  
  3. def solve(eq, var='x'):
  4. eq1 = eq.replace("=", "-(") + ")"
  5. #print eq1 # test
  6. c = eval(eq1, {var:1j})
  7. #print c # test
  8. return -c.real/c.imag
  9.  
  10.  
  11. eq = "x-2 = 2*x" # example
  12. r = solve(eq)
  13. print "equation: %s\n result: x = %s" % (eq, r)
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,003
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 927
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #84
Nov 8th, 2006
Looking at Ene's Python class sample code, I realized that it would be nice to have a sample of class inheritance ...
  1. # class Teacher and class Student inherit from class SchoolMember
  2.  
  3. # the base or super class
  4. class SchoolMember(object):
  5. '''represents any school member'''
  6. def __init__(self, name, age):
  7. self.name = name
  8. self.age = age
  9.  
  10. def detail(self):
  11. '''show name and age, stay on same line (trailing comma)'''
  12. print 'Name: %-13s Age:%s' % (self.name, self.age),
  13.  
  14. # use the base class as argument to inherit from
  15. class Teacher(SchoolMember):
  16. '''represents a teacher'''
  17. def __init__(self, name, age, subject):
  18. # call the base class constructor ...
  19. # it assigns name, age to self.name, self.age
  20. SchoolMember.__init__(self, name, age)
  21. self.subject = subject
  22.  
  23. def detail(self):
  24. '''teaches this course'''
  25. SchoolMember.detail(self)
  26. print 'Teaches course: %s' % self.subject
  27.  
  28. class Student(SchoolMember):
  29. '''represents a student'''
  30. def __init__(self, name, age, grades):
  31. SchoolMember.__init__(self, name, age)
  32. self.grades = grades
  33.  
  34. def detail(self):
  35. '''student grades'''
  36. SchoolMember.detail(self)
  37. print 'Average grades: %d' % self.grades
  38.  
  39. # teacher has name age and subject taught
  40. t1 = Teacher('Mr. Schard', 40, 'Beginning Python 101')
  41. # student has name, age and average grade (max 100)
  42. s1 = Student('Abigale Agat', 20, 92)
  43. s2 = Student('Bertha Belch', 22, 65)
  44. s3 = Student('Karl Kuss', 21, 98)
  45. s4 = Student('Tom Tippit', 22, 77)
  46. s5 = Student('Zoe Zeller', 20, 88)
  47.  
  48. print '-'*55
  49.  
  50. # list of instances, Teacher t1 and Students s1 ... s5
  51. members = [t1, s1, s2, s3, s4, s5]
  52. sumgrades = 0
  53. for member in members:
  54. memberType = member.detail()
  55. try:
  56. sumgrades += member.grades
  57. except AttributeError:
  58. pass # this would be a teacher, has no grades so skip
  59.  
  60. print "\n%s's students class-average grades = %d" % (t1.name, sumgrades/5)
  61.  
  62. """
  63. output =
  64. Name: Mr. Schard Age:40 Teaches course: Beginning Python 101
  65. Name: Abigale Agat Age:20 Average grades: 92
  66. Name: Bertha Belch Age:22 Average grades: 65
  67. Name: Karl Kuss Age:21 Average grades: 98
  68. Name: Tom Tippit Age:22 Average grades: 77
  69. Name: Zoe Zeller Age:20 Average grades: 88
  70.  
  71. Mr. Schard's students class-average grades = 84
  72. """
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #85
Nov 11th, 2006
Import the module shutil, it has functions for copying and moving files, copying whole directory trees, deleting directory trees and more.
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Feb 2002
Posts: 12,040
Reputation: cscgal is a glorious beacon of light cscgal is a glorious beacon of light cscgal is a glorious beacon of light cscgal is a glorious beacon of light cscgal is a glorious beacon of light cscgal is a glorious beacon of light 
Solved Threads: 127
Administrator
Staff Writer
cscgal's Avatar
cscgal cscgal is offline Offline
The Queen of DaniWeb

Re: Starting Python

 
0
  #86
Dec 4th, 2006
Dani the Computer Science Gal
Follow my Twitter feed! twitter.com/daniweb
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,525
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 169
Ene Uran's Avatar
Ene Uran Ene Uran is online now Online
Posting Virtuoso

Re: Starting Python

 
0
  #87
Dec 9th, 2006
Some details on the use of modules in Python, heavily commented. Here is an example of a module:
  1. # modules should be saved to the same folder as the
  2. # program or to folders listed in sys.path()
  3.  
  4. # save this module code as apple.py ...
  5. # (module-name and file-name.py have to match, are case sensitive!)
  6.  
  7. def pieCookingStatus(cooking_time):
  8. if cooking_time < 35:
  9. print "Still cooking!"
  10. elif cooking_time < 40:
  11. print "Almost done!"
  12. else:
  13. print "Take pie out of the oven!"
  14.  
  15. def piePercentCooked(cooking_time):
  16. """consider 40 minutes the fully cooked time"""
  17. return 100 * cooking_time/40
  18.  
  19. # optional, specify version number of module
  20. version = '1.2'
  21.  
  22. # this test runs when this code is used as a standalone program,
  23. # but not as an imported module of another program,
  24. # then the namespace will be apple (name of module) and not __main__
  25. if __name__ == '__main__':
  26. print "Pie is %d percent cooked." % piePercentCooked(33)
  27. pieCookingStatus(33)
Now the program that would use the above module:
  1. # test the module apple.py
  2.  
  3. # import creates a namespace with the module's name (apple)
  4. # also Python creates a precompiled bytecode file apple.pyc for speed
  5. import apple
  6.  
  7. # optional, check version if it has been specified
  8. if 'version' in dir(apple):
  9. print 'Version =', apple.version
  10.  
  11. # optional, show namespaces used
  12. # note that namespace __name__ is assumed for this program
  13. # you don't have to use it, but you have to prefix the
  14. # modules namespace to functions/variables of the module
  15. # in this case prefix with apple and a dot
  16. print "Namespace of program:", __name__ # __main__
  17. print "Namespace of module :", apple.__name__ # apple
  18.  
  19. # also optional, list filenames used
  20. print __file__ # C:/Python24/Atest/AppleTest.py
  21. print apple.__file__ # C:/Python24/Atest/apple.pyc
  22.  
  23. # now let's do something with the apple module
  24. minutes_cooking = 45
  25. percent_cooked = apple.piePercentCooked(minutes_cooking)
  26. print "Pie is %0.1f percent cooked." % percent_cooked
  27. apple.pieCookingStatus(minutes_cooking)
If you have your module in a subdirectory of your own that is not on the PYTHONPATH then you can change the import statement:
  1. """
  2. your program myprog.py may be in C:\Python24\myprog.py
  3. the module is in C:\Python24\directory1\directory2\module1.py
  4. C:\Python24\ would be listed in sys.path() (PYTHONPATH)
  5. """
  6.  
  7. # import modules from subfolders:
  8. from directory1.directory2 import module1
Last edited by Ene Uran; Dec 9th, 2006 at 12:07 pm.
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 2,273
Reputation: sneekula has a spectacular aura about sneekula has a spectacular aura about 
Solved Threads: 175
sneekula's Avatar
sneekula sneekula is offline Offline
Nearly a Posting Maven

Re: Starting Python

 
0
  #88
Dec 10th, 2006
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
No one died when Clinton lied.
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 4,003
Reputation: vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice vegaseat is just really nice 
Solved Threads: 927
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #89
Dec 10th, 2006
Originally Posted by sneekula View Post
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
There is no fly in your dessert, just poor syntax! There was a post that cluttered the sticky with a large question that was moved to the regular forum.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,525
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 169
Ene Uran's Avatar
Ene Uran Ene Uran is online now Online
Posting Virtuoso

Re: Starting Python

 
0
  #90
Dec 13th, 2006
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:
  1. # sort a list of names by last name
  2.  
  3. def sort_names(names):
  4. """
  5. sort names by last name, avoiding title, first and middle names
  6. """
  7. names_mod = []
  8. for name in names:
  9. # split each name into a list
  10. name_list = name.split()
  11. # pick the last name from list
  12. last_name = name_list[-1]
  13. # create a list of temporary sublists [last_name, name]
  14. names_mod.append([last_name, name])
  15. # sort the modified list of names inplace
  16. # this will sort by the first item in the
  17. # sublists which is last_name
  18. names_mod.sort()
  19. # use list comprehension to
  20. # to remove the temporary last_name item
  21. return [name[1] for name in names_mod]
  22.  
  23. names = [
  24. "Dr. Heidi Karin Hirsch",
  25. "Miss Arlene Auerbach",
  26. "Mr. and Mrs. Larry Zoom",
  27. "Mr. Frank Paul Lummer",
  28. "Vicepresident Colter"
  29. ]
  30.  
  31. print "Original list of names:"
  32. for name in names:
  33. print name
  34.  
  35. print
  36. print "List of names sorted by last name:"
  37. names_sorted = sort_names(names)
  38. for name in names_sorted:
  39. print name
  40.  
  41. """
  42. output -->
  43. Original list of names:
  44. Dr. Heidi Karin Hirsch
  45. Miss Arlene Auerbach
  46. Mr. and Mrs. Larry Zoom
  47. Mr. Frank Paul Lummer
  48. Vicepresident Colter
  49.  
  50. List of names sorted by last name:
  51. Miss Arlene Auerbach
  52. Vicepresident Colter
  53. Dr. Heidi Karin Hirsch
  54. Mr. Frank Paul Lummer
  55. Mr. and Mrs. Larry Zoom
  56. """
drink her pretty
Reply With Quote Quick reply to this message  
Reply

Tags
code, hints, python, tricks, tutorial

Message:



Similar Threads
Other Threads in the Python Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC