User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 361,896 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,340 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser:
Views: 48617 | Replies: 139
Reply
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 167
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #21  
Jul 14th, 2005
Just simple code to construct a toggle button, in this case we are using the venerable Tkinter for the GUI implementation.
  1. # make a toggle button with Tkinter
  2.  
  3. from Tkinter import *
  4.  
  5. toggleFlag = True
  6.  
  7. def entryColor():
  8. """toggle the entry color between white and red"""
  9. global toggleFlag
  10. if toggleFlag:
  11. e1.config(bg='red')
  12. toggleFlag = False
  13. else:
  14. e1.config(bg='white')
  15. toggleFlag = True
  16.  
  17. # create the root window
  18. root = Tk()
  19. # create a button, command runs the given function when button is clicked
  20. b1 = Button(root, text="Toggle Color", command=entryColor)
  21. # pack button into root window
  22. b1.pack(fill=BOTH, expand=1)
  23. # create an entry box to color
  24. e1 = Entry(root)
  25. e1.pack(fill=BOTH, expand=1)
  26.  
  27. # this allows the program to be an importable module and a runnable program
  28. if __name__ == "__main__":
  29. # start the event loop
  30. root.mainloop()
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.
Last edited by vegaseat : Mar 1st, 2007 at 3:13 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 167
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #22  
Jul 18th, 2005
I have donated a fair number of code snippets to DaniWeb. Many of the snippets are written like "Almost Tutorials" concentrating on Strings, Lists, Sets, Dictionaries and so on. I think and hope that they can be a good source of information for Beginners in the Python language. Click on this ...
http://www.daniweb.com/code/python.html

For instance check the code snippet at:
http://www.daniweb.com/code/snippet354.html
It talks about class inheritance and sheds some light on object and self.
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 167
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #23  
Jul 22nd, 2005
In a recent thread we looked at ways to create a multiline string. Here are a few code samples showing you how to do this, some are preference, some are cosmetic ...
  1. # a look at multiline strings
  2.  
  3. # using line continuation (\) to form one long/multiline string
  4. # complex and tough to read
  5. # (no space right after \ or an empty line following \)
  6. str1 = "The alien gasps and says, 'Oh, this is it. I will die! \n\
  7. Tell my 2.4 million larvae that I loved them... \n\
  8. Good-bye, cruel universe.' "
  9.  
  10.  
  11. # using line continuation (\) to combine three strings to one string
  12. # ignores indentations between strings, easy on the eye
  13. str2 = "The alien gasps and says, 'Oh, this is it. I will die! \n"\
  14. "Tell my 2.4 million larvae that I loved them... \n"\
  15. "Good-bye, cruel universe.'"
  16.  
  17.  
  18. # using just triple quotes, still tough to read?
  19. # note: newline characters are taken care of
  20. str3 = """The alien gasps, 'Oh, this is it. I will die!
  21. Tell my 2.4 million larvae that I loved them...
  22. Good-bye, cruel universe.' """
  23.  
  24.  
  25. # using line continuation (\) and triple quotes
  26. # might be easier to read
  27. str4 = \
  28. """The alien gasps and says, 'Oh, this is it. I will die!
  29. Tell my 2.4 million larvae that I loved them...
  30. Good-bye, cruel universe.' """
  31.  
  32.  
  33. # note: indentations become part of the string
  34. str5 = """The alien gasps, 'Oh, this is it. I will die!
  35. Tell my 2.4 million larvae that I loved them...
  36. Good-bye, cruel universe.' """
  37.  
  38.  
  39. # gee, one more way to do a multiline string with the + concatinator ...
  40. str6 = "The alien gasps and says, 'Oh, this is it. I will die! \n"
  41. str6 = str6 + "Tell my 2.4 million larvae that I loved them... \n"
  42. str6 = str6 + "Good-bye, cruel universe.'"
  43.  
  44.  
  45. # another variation using +
  46. str7 = "The alien gasps and says, 'Oh, this is it. I will die! \n"
  47. str8 = "Tell my 2.4 million larvae that I loved them... \n"
  48. str9 = "Good-bye, cruel universe.'"
  49. str10 = str7 + str8 + str9
  50.  
  51.  
  52. print '-'*60 # pretty up with 60 dashes
  53. print str1
  54. print '-'*60
  55. print str2
  56. print '-'*60
  57. print str3
  58. print '-'*60
  59. print str4
  60. print '-'*60
  61. print str5
  62. print '-'*60
  63. print str6
  64. print '-'*60
  65. print str10
BTW, the php code field seems to eat up some of the trailing \ characters, so I switched to the regular code=python field.
Last edited by vegaseat : Mar 1st, 2007 at 2:44 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 167
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #24  
Jul 31st, 2005
Since Python does not need type declarations, I wanted to test the numeric capacity with a program that calculates factorials since they quickly give very large numbers. I stopped at the factorial of 69 only because the line started wrapping.
  1. # check the numeric range of Python with huge factorials
  2. # factorial(69) still checks out accurately! Has 98 digits in it!
  3. # 171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000
  4.  
  5. def fact(n):
  6. """returns the factorial of n"""
  7. if n == 0:
  8. return 1
  9. else:
  10. k = n*fact(n-1)
  11. return k
  12.  
  13. for k in range(1, 70):
  14. print "factorial of", k,"=", fact(k)
  15.  
This boggles my mind since it took all sorts of hoops to try this with C++ earlier in my life. In C++ the unsigned long integer fizzles out at a measly 4.3 billion. Those are only ten digits!

Here is another little number trick I picked up from one of the forums. This poor fellow wanted to do it in C, but the old compiler just couldn't handle the number of digits in the result. No sweat for Python ...
  1. # another little number trick ...
  2.  
  3. a = 111111111 # that's nine ones
  4.  
  5. print "%d * %d = %d" % (a, a, a * a) # result = 12345678987654321
Last edited by vegaseat : Mar 1st, 2007 at 2:45 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 167
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #25  
Aug 11th, 2005
This shows you how to mimic a C struct type with an empty Python class ...
  1. # create a structure similar to C struct using an empty class
  2.  
  3. class Employee(object):
  4. pass
  5.  
  6.  
  7. john = Employee() # Create empty employee record/struct
  8. ted = Employee()
  9. mark = Employee()
  10.  
  11. # fill the fields of the record/struct
  12. john.name = 'John Johnson'
  13. john.dept = 'computer lab'
  14. john.salary = 3000
  15.  
  16. ted.name = 'Ted Tetris'
  17. ted.dept = 'human resources'
  18. ted.salary = 5000
  19.  
  20. mark.name = 'Mark Marksman'
  21. mark.dept = 'shipping area'
  22. mark.salary = 3200
  23.  
  24. # this works like a struct or record
  25. print "%s works in the %s and earns $%s/month" % (john.name, john.dept, john.salary)
  26.  
  27. print
  28.  
  29. # good for large employee lists, make a list of objects (not strings)
  30. empList = [john, ted, mark]
  31. for emp in empList:
  32. print "%s works in the %s and earns $%s/month" % \
  33. (getattr(emp, "name"), getattr(emp, "dept"), getattr(emp, "salary"))
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor without the line numbers.
Last edited by vegaseat : Mar 1st, 2007 at 3:14 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Jun 2005
Posts: 141
Reputation: G-Do is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 11
G-Do's Avatar
G-Do G-Do is offline Offline
Junior Poster

Re: Starting Python

  #26  
Aug 16th, 2005
While Python offers flexible container data structures, such as lists and dictionaries, it is occasionally helpful to create our own. Suppose, for example, that we wanted to create a data structure with two dictionaries: one for key-value pairs where len(key) is even, and one for key-value pairs where len(key) is odd. We would like to allow the Python builtins, such as str(), len(), container[key], etc, to access our objects in a meaningful way, and Python lets us do this via container-emulation methods:
import sys
# -- The Container class
class Container:
     # Instance variables:
     # self.even is a dictionary which stores key-value pairs
     # where the key has an even length
     # self.odd is a dictionary which stores key-value pairs
     # where the key has an odd length
     # Initialize new Container objects
     def __init__(self):
          self.even = dict(); self.odd = dict()
     # __len__() lets you use len() to evaluate this object
     def __len__(self):
          return len(self.even)+len(self.odd)
     # __repr__() lets you use str() to evaluate this object
     def __repr__(self):
          return str(self.even)+"\n"+str(self.odd)
     # __getitem__ allows evaluation of container[key]
     def __getitem__(self, key):
          if len(key)%2 == 0: return self.even[key]
          else: return self.odd[key]
     # __setitem__ allows assignment to container[key]
     def __setitem__(self, key, value):
          if len(key)%2 == 0: self.even[key] = value
          else: self.odd[key] = value
     # __delitem__ lets you use del container[key] to remove keys
     def __delitem__(self, key):
          if len(key)%2 == 0: del self.even[key]
          else: del self.odd[key]
     # __contains__ lets you use "key in container" boolean expressions
     def __contains__(self, key):
          return (key in self.even or key in self.odd)
     # __iter__ lets you iterate through the items via "for x in container"
     def __iter__(self):
          ret = []
          ret.extend(self.even.keys())
          ret.extend(self.odd.keys())
          return ret.__iter__()
# -- The main function (diagnostic)
def main(args):
    # __init__
    c = Container()
    # __setitem__
    print "Adding key-value pairs\n"
    c["Laverne"] = "Shirley"
    c["Ozzie"] = "Harriet"
    c["Abbott"] = "Costello"
    c["Carl"] = "Steve"
    # __len__
    print "The length of our container is", len(c), "\n"
    # __repr__
    print "One string representation is:\n", str(c), "\n"
    # __getitem__
    print "The partner of Abbott is", c["Abbott"], "\n"
    # __delitem__
    del c["Laverne"]
    print "We have just deleted the Laverne:Shirley key-value pair"
    print "The new length is", len(c)
    print "Now, the container looks like\n", str(c), "\n"
    # __contains__
    print "Is the key 'Batman' in our container?"
    if "Batman" in c: print c["Batman"]
    else: print "Sorry, Boy Wonder"
    print "Is the key 'Ozzie' in our container?"
    if "Ozzie" in c: print "Yes, and it is", c["Ozzie"], "\n"
    else: print "No Ozzies here", "\n"
    # __iter__
    print "Let's iterate through all available keys and their values"
    for x in c: print x, "\t", c[x]
# -- The following code executes upon program invocation
if __name__ == "__main__": main(sys.argv)
What this gives you is the freedom to define your own container data structures, and then use them just like you would use Python-supplied containers. Pretty snazzy!

The trick here is that you can define these functions any way you want. For example, your __repr__ method could always return "fish" regardless of the values of the object's instance variables - but that would be counter-intuitive, because programmers generally expect str() to return a string value that represents, at least in part, the internal state of the object. So beware!

Also, the __iter__ method I provided doesn't really build an iterator object - it just compiles a list of keys, then borrows the iterator from that. For more information on iterators and generators, see van Rossum's reference manual.
Vi veri veniversum vivus vici
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 167
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #27  
Aug 24th, 2005
A look at a simple Python class example for the OOP beginner ...
  1. # looking at a simple Python class
  2. # a class combines a number of methods/functions that belong together
  3.  
  4. class Box(object):
  5. """class names by convention are capitalized, (object) is an optional inheritance"""
  6. def __init__(self, depth, height, width):
  7. """__init__() is called first (acts as Constructor)
  8. brings in data from outside the class and makes it
  9. usable within the class via the instance object self.
  10. Look at self as the data carrier within the class.
  11. """
  12. self.depth = depth
  13. self.height = height
  14. self.width = width
  15.  
  16. def volume(self):
  17. return self.height * self.width * self.depth
  18.  
  19. def surface(self):
  20. return 2*self.height*self.width + 2*self.height*self.depth + 2*self.width*self.depth
  21.  
  22. # construct an instance of a 10x10x10 box and reference it with box1
  23. box1 = Box(10, 10 ,10)
  24. print "A 10x10x10 box has a volume of", box1.volume()
  25. print "and a surface area of", box1.surface()
  26.  
  27. print
  28.  
  29. print "Let's change the depth to 5"
  30. # construct an instance of a 5x10x10 box and reference it with box2
  31. box2 = Box(5, 10 ,10)
  32. print "A 5x10x10 box has a volume of", box2.volume()
  33. print "and a surface area of", box2.surface()
  34.  
  35. print
  36.  
  37. print "Optional tests for the inquisitive folks:"
  38. print "box1 =", box1
  39. print "box2 =", box2
  40. print "The depth of box2 is", box2.depth
  41.  
  42. print
  43.  
  44. # Can we set the box dimensions directly? Let's try it.
  45. box1.depth = 5
  46. box1.height = 5
  47. box1.width = 5
  48. print "Box1 volume after setting box1 dimensions to 5x5x5 =", box1.volume()
Here class Box inherits the most basic container class object (actually just a place holder), this is the newer class writing convention, adding (object) is "still" optional.
Last edited by vegaseat : Mar 1st, 2007 at 2:46 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 167
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Re: Starting Python

  #28  
Sep 10th, 2005
The question came up in the forum how to represent an integer as a hexadecimal. There were two obvious ways to do this, the hex() function and the format operator %X. The resulting strings 0xac23b and AC23B look different. If you have to display the result, AC23B might be your choice. Otherwise speed might be important, particularly, if you call the function a lot. Here is a way to measure speed ...
  1. # two different ways to represent integer 705083 as a hexadecimal number
  2. # 0x is the official prefix for a hexnumber
  3. # the results appear different, but both are of type string and change back to base 10 properly
  4.  
  5. # using the hex() function
  6. hex1 = hex(705083)
  7. print hex1, type(hex1), int(hex1,16) # result = 0xac23b <type 'str'> 705083
  8.  
  9. # using the format operator %
  10. hex2 = "%X" % 705083
  11. print hex2, type(hex2), int(hex2, 16) # result = AC23B <type 'str'> 705083
  12.  
  13. # let's time the two options ...
  14.  
  15. import timeit
  16.  
  17. t = timeit.Timer('hex(705083)')
  18. elapsed = (10 * t.timeit(number=100000))
  19. print 'Function hex(705083) takes %0.3f micro-seconds/pass' % elapsed
  20.  
  21. t = timeit.Timer('"%X" % 705083')
  22. elapsed = (10 * t.timeit(number=100000))
  23. print 'The format operator takes %0.3f micro-seconds/pass' % elapsed
Last edited by vegaseat : Mar 1st, 2007 at 2:47 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Oct 2004
Location: Mojave Desert
Posts: 2,275
Reputation: vegaseat is on a distinguished road 
Rep Power: 8
Solved Threads: 167
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
Kickbutt Moderator

Solution Re: Starting Python

  #29  
Sep 17th, 2005
Writing a module and testing it ...
  1. # save as den2bin.py and use import den2bin in any program that needs it
  2. # call the function with something like den2bin.Denary2Binary(76)
  3. # (it's easiest to keep this file in the working folder)
  4.  
  5. def Denary2Binary(n):
  6. '''convert denary integer n (base 10) to binary string bStr (base 2)'''
  7. bStr = ''
  8. if n < 0: raise ValueError, "must be a positive integer"
  9. if n == 0: return '0'
  10. while n > 0:
  11. bStr = str(n % 2) + bStr
  12. n = n >> 1
  13. return bStr
  14.  
  15. # this test runs when used as a standalone program, but not as an imported module
  16. # let's say you save this module as den2bin.py and use it in another program
  17. # when you import den2bin the __name__ namespace would now be den2bin and the
  18. # test would be ignored
  19. if __name__ == '__main__':
  20. print Denary2Binary(255)
  21. # convert back to test it
  22. print int(Denary2Binary(255), 2)
  23.  
  24. # check the exceptions
  25. print Denary2Binary(0)
  26. print Denary2Binary(-5) # should give a ValueError
  27.  
Last edited by vegaseat : Mar 1st, 2007 at 2:48 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote  
Join Date: Jul 2005
Location: France
Posts: 914
Reputation: bumsfeld is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 40
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Posting Shark

Solution Re: Starting Python

  #30  
Sep 17th, 2005
This is kind of neat:
# assigning the same value to several variables:
a, b, c = 3

print a, b, c   # shows   3 3 3 

import sys
# shows a dictionary of present objects including a, b, c with values
print sys._getframe().f_locals
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

DaniWeb Python Marketplace
Thread Tools Display Modes

Similar Threads
Other Threads in the Python Forum

All times are GMT -4. The time now is 8:32 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC