Starting Python

Reply

Join Date: Oct 2004
Posts: 3,856
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: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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. try:
  4. # Python2
  5. import Tkinter as tk
  6. except ImportError:
  7. # Python3
  8. import tkinter as tk
  9.  
  10. toggleFlag = True
  11.  
  12. def entryColor():
  13. """toggle the entry color between white and red"""
  14. global toggleFlag
  15. if toggleFlag:
  16. e1.config(bg='red')
  17. toggleFlag = False
  18. else:
  19. e1.config(bg='white')
  20. toggleFlag = True
  21.  
  22. # create the root window
  23. root = tk.Tk()
  24. # create a button, command runs the given function
  25. # when button is clicked
  26. b1 = tk.Button(root, text="Toggle Color", command=entryColor)
  27. # pack button into root window
  28. b1.pack(fill=tk.BOTH, expand=1)
  29. # create an entry box to color
  30. e1 = tk.Entry(root)
  31. e1.pack(fill=tk.BOTH, expand=1)
  32.  
  33. # start the event loop
  34. root.mainloop()
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.
Last edited by vegaseat; Aug 29th, 2009 at 5:40 pm. Reason: [code=python] tag, Python3 ready
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,856
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: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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/showsnippet.php?codeid=354
It talks about class inheritance and sheds some light on object and self.
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,856
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: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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 triple quotes and line continuation (\)
  26. # the text lines up properly and
  27. # IMHO the easiest to write and read
  28. str4 = """\
  29. The alien gasps and says, 'Oh, this is it. I will die!
  30. Tell my 2.4 million larvae that I loved them...
  31. Good-bye, cruel universe.' """
  32.  
  33.  
  34. # note: indentations become part of the string
  35. str5 = """The alien gasps, 'Oh, this is it. I will die!
  36. Tell my 2.4 million larvae that I loved them...
  37. Good-bye, cruel universe.' """
  38.  
  39.  
  40. # gee, one more way to do a multiline string with the + concatinator ...
  41. str6 = "The alien gasps and says, 'Oh, this is it. I will die! \n"
  42. str6 = str6 + "Tell my 2.4 million larvae that I loved them... \n"
  43. str6 = str6 + "Good-bye, cruel universe.'"
  44.  
  45.  
  46. # another variation using +
  47. str7 = "The alien gasps and says, 'Oh, this is it. I will die! \n"
  48. str8 = "Tell my 2.4 million larvae that I loved them... \n"
  49. str9 = "Good-bye, cruel universe.'"
  50. str10 = str7 + str8 + str9
  51.  
  52. # will work with Python2 and Python3
  53. print('-'*60) # pretty up with 60 dashes
  54. print(str1)
  55. print('-'*60)
  56. print(str2)
  57. print('-'*60)
  58. print(str3)
  59. print('-'*60)
  60. print(str4)
  61. print('-'*60)
  62. print(str5)
  63. print('-'*60)
  64. print(str6)
  65. print('-'*60)
  66. print(str10)
Last edited by vegaseat; Aug 29th, 2009 at 5:54 pm. Reason: [code=python] tag, Python3 ready
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,856
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: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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) )
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; Aug 29th, 2009 at 5:57 pm. Reason: [code=python] tag. Python3 ready
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,856
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: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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" % \
  26. (john.name, john.dept, john.salary) )
  27.  
  28. print('-'*60)
  29.  
  30. # or use a list of Employee() instances ...
  31. empList = [john, ted, mark]
  32. for emp in empList:
  33. print( "%s works in the %s and earns $%s/month" % \
  34. (emp.name, emp.dept, emp.salary) )
  35.  
  36. """my output -->
  37. John Johnson works in the computer lab and earns $3000/month
  38. ------------------------------------------------------------
  39. John Johnson works in the computer lab and earns $3000/month
  40. Ted Tetris works in the human resources and earns $5000/month
  41. Mark Marksman works in the shipping area and earns $3200/month
  42. """
Click on "Toggle Plain Text" so you can highlight and copy the code to your editor without the line numbers.
Last edited by vegaseat; Aug 29th, 2009 at 6:13 pm. Reason: [code=python] tag
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jun 2005
Posts: 146
Reputation: G-Do is an unknown quantity at this point 
Solved Threads: 28
G-Do's Avatar
G-Do G-Do is offline Offline
Junior Poster

Re: Starting Python

 
0
  #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:
  1. import sys
  2. # -- The Container class
  3. class Container:
  4. # Instance variables:
  5. # self.even is a dictionary which stores key-value pairs
  6. # where the key has an even length
  7. # self.odd is a dictionary which stores key-value pairs
  8. # where the key has an odd length
  9. # Initialize new Container objects
  10. def __init__(self):
  11. self.even = dict(); self.odd = dict()
  12. # __len__() lets you use len() to evaluate this object
  13. def __len__(self):
  14. return len(self.even)+len(self.odd)
  15. # __repr__() lets you use str() to evaluate this object
  16. def __repr__(self):
  17. return str(self.even)+"\n"+str(self.odd)
  18. # __getitem__ allows evaluation of container[key]
  19. def __getitem__(self, key):
  20. if len(key)%2 == 0: return self.even[key]
  21. else: return self.odd[key]
  22. # __setitem__ allows assignment to container[key]
  23. def __setitem__(self, key, value):
  24. if len(key)%2 == 0: self.even[key] = value
  25. else: self.odd[key] = value
  26. # __delitem__ lets you use del container[key] to remove keys
  27. def __delitem__(self, key):
  28. if len(key)%2 == 0: del self.even[key]
  29. else: del self.odd[key]
  30. # __contains__ lets you use "key in container" boolean expressions
  31. def __contains__(self, key):
  32. return (key in self.even or key in self.odd)
  33. # __iter__ lets you iterate through the items via "for x in container"
  34. def __iter__(self):
  35. ret = []
  36. ret.extend(self.even.keys())
  37. ret.extend(self.odd.keys())
  38. return ret.__iter__()
  39. # -- The main function (diagnostic)
  40. def main(args):
  41. # __init__
  42. c = Container()
  43. # __setitem__
  44. print "Adding key-value pairs\n"
  45. c["Laverne"] = "Shirley"
  46. c["Ozzie"] = "Harriet"
  47. c["Abbott"] = "Costello"
  48. c["Carl"] = "Steve"
  49. # __len__
  50. print "The length of our container is", len(c), "\n"
  51. # __repr__
  52. print "One string representation is:\n", str(c), "\n"
  53. # __getitem__
  54. print "The partner of Abbott is", c["Abbott"], "\n"
  55. # __delitem__
  56. del c["Laverne"]
  57. print "We have just deleted the Laverne:Shirley key-value pair"
  58. print "The new length is", len(c)
  59. print "Now, the container looks like\n", str(c), "\n"
  60. # __contains__
  61. print "Is the key 'Batman' in our container?"
  62. if "Batman" in c: print c["Batman"]
  63. else: print "Sorry, Boy Wonder"
  64. print "Is the key 'Ozzie' in our container?"
  65. if "Ozzie" in c: print "Yes, and it is", c["Ozzie"], "\n"
  66. else: print "No Ozzies here", "\n"
  67. # __iter__
  68. print "Let's iterate through all available keys and their values"
  69. for x in c: print x, "\t", c[x]
  70. # -- The following code executes upon program invocation
  71. 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 Quick reply to this message  
Join Date: Oct 2004
Posts: 3,856
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: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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. """
  6. class names by convention are capitalized, (object) is
  7. a basic class inheritance signifying the new style class
  8. """
  9. def __init__(self, depth, height, width):
  10. """__init__() is called first (acts as Constructor)
  11. brings in data from outside the class and makes it
  12. usable within the class via the instance object self.
  13. Look at self as the data carrier within the class.
  14. """
  15. self.depth = depth
  16. self.height = height
  17. self.width = width
  18.  
  19. def volume(self):
  20. """class methods have self as first argument"""
  21. return self.height * self.width * self.depth
  22.  
  23. def surface(self):
  24. return 2*self.height*self.width + 2*self.height*self.depth + 2*self.width*self.depth
  25.  
  26. # construct an instance of a 10x10x10 box and reference it with box1
  27. box1 = Box(10, 10 ,10)
  28. print( "A 10x10x10 box has a volume of", box1.volume() )
  29. print( "and a surface area of", box1.surface() )
  30.  
  31. print('') # empty line in Python3 and Python2
  32.  
  33. print( "Let's change the depth to 5" )
  34. # construct an instance of a 5x10x10 box and reference it with box2
  35. box2 = Box(5, 10 ,10)
  36. print( "A 5x10x10 box has a volume of", box2.volume() )
  37. print( "and a surface area of", box2.surface() )
  38.  
  39. print('')
  40.  
  41. print( "Optional tests for the inquisitive folks:" )
  42. print( "box1 =", box1 )
  43. print( "box2 =", box2 )
  44. print( "The depth of box2 is", box2.depth )
  45.  
  46. print('')
  47.  
  48. # Can we set the box dimensions directly? Let's try it.
  49. box1.depth = 5
  50. box1.height = 5
  51. box1.width = 5
  52. 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; Aug 29th, 2009 at 6:23 pm. Reason: [code=python] tag, Python3 ready
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,856
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: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #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
  2. # number, 0x is the official prefix for a hexnumber
  3. # the results appear different, but both are of type string
  4. # and change back to base 10 properly
  5.  
  6. # using the hex() function
  7. hex1 = hex(705083)
  8. print( hex1, type(hex1), int(hex1,16) )
  9.  
  10. # using the format operator %
  11. hex2 = "%X" % 705083
  12. print( hex2, type(hex2), int(hex2, 16) )
  13.  
  14. # let's time the two options ...
  15.  
  16. import timeit
  17.  
  18. print( "Timing study ..." )
  19.  
  20. t = timeit.Timer('hex(705083)')
  21. elapsed = (10 * t.timeit(number=100000))
  22. print( 'hex(705083) takes %0.3f microseconds/pass' % elapsed )
  23.  
  24. t = timeit.Timer('"%X" % 705083')
  25. elapsed = (10 * t.timeit(number=100000))
  26. print( 'Format operator takes %0.3f microseconds/pass' % elapsed )
  27.  
  28. """my output (Python 3.1) -->
  29. 0xac23b <class 'str'> 705083
  30. AC23B <class 'str'> 705083
  31. Timing study ...
  32. hex(705083) takes 0.591 microseconds/pass
  33. Format operator takes 0.048 microseconds/pass
  34. """
Last edited by vegaseat; Aug 29th, 2009 at 6:38 pm. Reason: [code=python] tag, Python3 ready
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Oct 2004
Posts: 3,856
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: 866
Moderator
vegaseat's Avatar
vegaseat vegaseat is offline Offline
DaniWeb's Hypocrite

Re: Starting Python

 
0
  #29
Sep 17th, 2005
Writing a module and testing it ...
  1. # save as den2bin.py and use
  2. # import den2bin in any program that needs it
  3. # call the function with something like den2bin.denary2binary(76)
  4. # (it's easiest to keep this file in the working folder)
  5.  
  6. def denary2binary(n):
  7. '''
  8. convert denary integer n (base 10) to binary string bStr (base 2)
  9. '''
  10. bStr = ''
  11. if n <= 0:
  12. return '0'
  13. while n > 0:
  14. bStr = str(n % 2) + bStr
  15. n = n >> 1
  16. return bStr
  17.  
  18. # the test code below only runs when used as a standalone program
  19. # let's say you save this module as den2bin.py
  20. # when you import den2bin the __name__ namespace would now be
  21. # 'den2bin' and not '__main__' and the module test will be ignored
  22. if __name__ == '__main__':
  23. print( denary2binary(255) ) # 11111111
  24. # convert back to test it
  25. print( int(denary2binary(255), 2) ) # 255
  26.  
  27. # with Python3 you can simply use builtin function bin()
  28. #print( bin(255), type(bin(255)) ) # 0b11111111 <class 'str'>
Last edited by vegaseat; Aug 29th, 2009 at 7:10 pm. Reason: [code=python] tag, Python3 ready
May 'the Google' be with you!
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 1,205
Reputation: bumsfeld will become famous soon enough bumsfeld will become famous soon enough 
Solved Threads: 130
bumsfeld's Avatar
bumsfeld bumsfeld is offline Offline
Nearly a Posting Virtuoso

Re: Starting Python

 
0
  #30
Sep 17th, 2005
This is kind of neat:
  1. # assigning the same value to several variable names:
  2. a = b = c = 7
  3.  
  4. print( a ) # 7
  5. print( c ) # 7
  6.  
  7. # contents of local dictionary ...
  8. print( vars() ) # {'a': 7, 'c': 7, 'b': 7, ... }
Last edited by vegaseat; Aug 29th, 2009 at 7:21 pm. Reason: correction and Python3 update
Reply With Quote Quick reply to this message  
Reply

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